Example usage for org.bouncycastle.asn1 DEROctetString DEROctetString

List of usage examples for org.bouncycastle.asn1 DEROctetString DEROctetString

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 DEROctetString DEROctetString.

Prototype

public DEROctetString(ASN1Encodable obj) throws IOException 

Source Link

Document

Constructor from the encoding of an ASN.1 object.

Usage

From source file:org.kse.gui.dialogs.extensions.DSelectStandardExtensionTemplate.java

License:Open Source License

private byte[] wrapInOctetString(byte[] extensionValue) throws IOException {
    return new DEROctetString(extensionValue).getEncoded(ASN1Encoding.DER);
}

From source file:org.ndnx.ndn.impl.security.crypto.MerkleTree.java

License:Open Source License

/**
 * Compute the intermediate node values by digesting the concatenation of the
 * left and right children (or the left child alone if there is no right child).
 * @throws NoSuchAlgorithmException if digestAlgorithm is unknown
 *///from  www . j  a v  a2 s.  c o m
protected void computeNodeValues() throws NoSuchAlgorithmException {
    // Climb the tree
    int firstNode = firstLeaf() - 1;
    for (int i = firstNode; i >= ROOT_NODE; --i) {
        byte[] nodeDigest = NDNDigestHelper.digest(digestAlgorithm(), get(leftChild(i)), get(rightChild(i)));
        _tree[i - 1] = new DEROctetString(nodeDigest);
    }
}

From source file:org.ndnx.ndn.impl.security.crypto.NDNMerkleTree.java

License:Open Source License

/**
 * Compute the leaf values of the ContentObjects in this tree
 * @param contentObjects the content//w w w. j ava 2  s.c  om
 * @throws NoSuchAlgorithmException if the digestAlgorithm unknown
 */
protected void computeLeafValues(ContentObject[] contentObjects) throws NoSuchAlgorithmException {
    // Hash the leaves
    for (int i = 0; i < numLeaves(); ++i) {
        // DKS -- need to make sure content() doesn't clone
        try {
            ContentObject co = contentObjects[i];
            byte[] blockDigest = NDNDigestHelper.digest(co.prepareContent());
            _tree[leafNodeIndex(i) - 1] = new DEROctetString(blockDigest);

            if (Log.isLoggable(Log.FAC_SIGNING, Level.FINER)) {
                Log.finer(Log.FAC_SIGNING, "offset: " + 0 + " block length: " + co.contentLength()
                        + " blockDigest " + DataUtils.printBytes(blockDigest) + " content digest: "
                        + DataUtils.printBytes(NDNDigestHelper.digest(co.content(), 0, co.contentLength())));
            }

        } catch (ContentEncodingException e) {
            Log.info("Exception in computeBlockDigest, leaf: " + i + " out of " + numLeaves() + " type: "
                    + e.getClass().getName() + ": " + e.getMessage());
            e.printStackTrace();
            // DKS todo -- what to throw?
        }
    }
}

From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java

License:Open Source License

protected CertificationRequest generateCSR(KeyPair keyPair, UserInfo userInfo) throws CertException {

    CertificationRequest csr;/*from ww w.  j  av a2 s.c  om*/

    GeneralNames subjectAltName = new GeneralNames(
            new GeneralName(GeneralName.rfc822Name, userInfo.getUserFields().get(CNField.Email)));

    Vector<DERObjectIdentifier> objectIdentifiers = new Vector<DERObjectIdentifier>();
    Vector<X509Extension> extensionValues = new Vector<X509Extension>();

    objectIdentifiers.add(X509Extensions.SubjectAlternativeName);
    extensionValues.add(new X509Extension(false, new DEROctetString(subjectAltName)));

    X509Extensions extensions = new X509Extensions(objectIdentifiers, extensionValues);

    Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
            new DERSet(extensions));
    try {
        csr = new PKCS10CertificationRequest(CERT_SIGNATURE_ALGORITHM, userInfo.getX500Principal(),
                keyPair.getPublic(), new DERSet(attribute), keyPair.getPrivate());
    } catch (InvalidKeyException e) {
        throw new CertException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertException(e);
    } catch (NoSuchProviderException e) {
        throw new CertException(e);
    } catch (java.security.SignatureException e) {
        throw new CertException(e);
    } catch (Exception e) {
        throw new CertException(e);
    }
    return csr;
}

From source file:org.opcfoundation.ua.utils.CertificateUtils.java

License:Open Source License

@Deprecated //Use createApplicationInstanceCertificate instead of this...all the x.509 cert fields are not fulfilled in this
public static org.opcfoundation.ua.transport.security.KeyPair generateKeyPair(String CN) throws Exception {
    KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(KEY_ALG, PROV);
    keyGenerator.initialize(KEY_SIZE);/*from   w  w w .  j a v  a  2 s  .co  m*/
    KeyPair key = keyGenerator.generateKeyPair();
    PublicKey publicKey = key.getPublic();
    PrivateKey privateKey = key.getPrivate();

    //Keystore not needed in this function (at the moment)
    ///KeyStore keyStore = null;

    ////keyStore = KeyStore.getInstance(STORE_TYPE);
    ///keyStore.load(null,STORE_PASSWD.toCharArray());

    //Use BouncyCastle as Security provider
    new CryptoUtil();
    //////X509Certificate[] chain = new X509Certificate[1];

    //Generates new certificate..add the information needed for the generator
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    X500Principal subjectName = new X500Principal("CN=" + CN);
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    //X509Certificate caCert=null;
    certGen.setIssuerDN(subjectName);
    Date notBefore = new Date();
    Date notAfter = new Date();
    notBefore.setTime(notBefore.getTime() - 1000 * 60 * 60);
    notAfter.setTime(notAfter.getTime() + 1000 * 60 * 60 * 24 * 365);
    certGen.setNotBefore(notBefore);
    certGen.setNotAfter(notAfter);
    certGen.setSubjectDN(subjectName);
    certGen.setPublicKey(publicKey);
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    //X.509 V3 Extensions...these are just examples

    //certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,new AuthorityKeyIdentifierStructure(caCert));
    ///7certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
    ////      new SubjectKeyIdentifierStructure(key.getPublic()));

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, true,
            new DEROctetString(new SubjectKeyIdentifierStructure(key.getPublic())));

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.keyCertSign));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    /////chain[0]= certGen.generate(privateKey, "BC"); // note: private key of CA
    //Generate
    X509Certificate caCert = certGen.generate(privateKey, "BC");

    //Encapsulate Certificate and private key to CertificateKeyPair
    Cert cert = new Cert(caCert);
    org.opcfoundation.ua.transport.security.PrivKey UAkey = new org.opcfoundation.ua.transport.security.PrivKey(
            (RSAPrivateKey) privateKey);
    return new org.opcfoundation.ua.transport.security.KeyPair(cert, UAkey);
    /*keyStore.setEntry(ALIAS,new KeyStore.PrivateKeyEntry(privateKey, chain),
    new KeyStore.PasswordProtection(KEY_PASSWD.toCharArray())
    );
            
    // Write out the keystore
    FileOutputStream keyStoreOutputStream = new FileOutputStream(keystorePath);
    keyStore.store(keyStoreOutputStream, "123456".toCharArray());
    keyStoreOutputStream.close();*/

}

From source file:org.openconcerto.modules.finance.payment.ebics.crypto.X509CertificateGenerator.java

License:Open Source License

/**
 * This is only a small helper function for adding X.509v3 extensions
 * /*  w  w w .  ja va  2 s.  co  m*/
 * @throws IOException
 */
private void addExtensionHelper(DERObjectIdentifier extId, boolean critical, ASN1Encodable extVal,
        Vector extensionsOrder, Hashtable extensions) throws IOException {
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(extVal);
    extensions.put(extId, new X509Extension(critical, new DEROctetString(bOut.toByteArray())));
    extensionsOrder.addElement(extId);
}

From source file:org.opensc.pkcs15.asn1.attr.PinAttributes.java

License:Apache License

@Override
public ASN1Object toASN1Object() {

    ASN1EncodableVector v = new ASN1EncodableVector();

    if (this.pinFlags != null)
        v.add(this.pinFlags);

    if (this.pinType != null)
        v.add(this.pinType);

    v.add(new DERInteger(this.minLength));
    v.add(new DERInteger(this.storedLength));
    if (this.maxLength != null)
        v.add(new DERInteger(this.maxLength.intValue()));

    if (this.pinReference != null)
        v.add(new DERTaggedObject(0, new DERInteger(this.pinReference)));

    if (this.padChar != null)
        v.add(new DEROctetString(new byte[] { this.padChar.byteValue() }));

    if (this.lastPinChange != null)
        v.add(this.lastPinChange);

    if (this.path != null)
        v.add(this.path);

    return new DERSequence(v);
}

From source file:org.opensc.pkcs15.asn1.basic.TokenInfo.java

License:Apache License

@Override
public DERObject toASN1Object() {

    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(new DERInteger(0));
    v.add(new DEROctetString(this.getSerialNumber()));

    if (this.getManufacturerID() != null)
        v.add(new DERUTF8String(this.getManufacturerID()));

    if (this.getLabel() != null)
        v.add(new DERTaggedObject(0, new DERUTF8String(this.getLabel())));

    v.add(this.getTokenflags());

    if (this.getSeInfo() != null) {

        ASN1EncodableVector vse = new ASN1EncodableVector();

        for (SecurityEnvironmentInfo si : this.getSeInfo())
            vse.add(si);/*from   w  w w .ja  v a  2  s . co m*/

        v.add(new DERSequence(vse));
    }

    if (this.getRecordInfo() != null)
        v.add(new DERTaggedObject(1, this.getRecordInfo()));

    if (this.getSupportedAlgotihms() != null) {

        ASN1EncodableVector vai = new ASN1EncodableVector();

        for (AlgorithmInfo ai : this.getSupportedAlgotihms().values())
            vai.add(ai);

        v.add(new DERTaggedObject(2, new DERSequence(vai)));
    }

    if (this.getIssuerId() != null)
        v.add(new DERTaggedObject(3, new DERUTF8String(this.getIssuerId())));

    if (this.getHolderId() != null)
        v.add(new DERTaggedObject(4, new DERUTF8String(this.getHolderId())));

    if (this.getLastUpdate() != null)
        v.add(new DERTaggedObject(5, this.getLastUpdate()));

    if (this.getPreferredLanguage() != null)
        v.add(new DERPrintableString(this.getPreferredLanguage()));

    return new DERSequence(v);
}

From source file:org.opensc.pkcs15.asn1.ref.Path.java

License:Apache License

@Override
public DERObject toASN1Object() {
    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(new DEROctetString(this.path));
    if (this.index != null)
        v.add(new DERInteger(this.index.intValue()));
    if (this.length != null)
        v.add(new DERTaggedObject(0, new DERInteger(this.length.intValue())));

    return new DERSequence(v);
}

From source file:org.poreid.verify.ocsp.OCSPClient.java

License:Open Source License

private OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber)
        throws CertificateEncodingException, OperatorCreationException, OCSPException, IOException {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    OCSPReqBuilder gen = new OCSPReqBuilder();
    gen.addRequest(new JcaCertificateID(
            new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1),
            issuerCert, serialNumber));//from   w ww  . j  a va2  s  . co m

    BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
    Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true,
            new DEROctetString(nonce.toByteArray()));
    gen.setRequestExtensions(new Extensions(new Extension[] { ext }));
    sentNonce = ext.getExtnId().getEncoded();

    return gen.build();
}