Example usage for org.bouncycastle.asn1.x509 X509Extensions SubjectKeyIdentifier

List of usage examples for org.bouncycastle.asn1.x509 X509Extensions SubjectKeyIdentifier

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 X509Extensions SubjectKeyIdentifier.

Prototype

ASN1ObjectIdentifier SubjectKeyIdentifier

To view the source code for org.bouncycastle.asn1.x509 X509Extensions SubjectKeyIdentifier.

Click Source Link

Document

Subject Key Identifier

Usage

From source file:org.openmaji.implementation.security.utility.cert.CertUtil.java

License:Open Source License

/**
 * Creates a lower level certificate, adding authority key-id and subject
  * key-id extensions to the resulting certificate (version 3).
 * //  w  w  w  . jav a 2 s .  co m
 * @param pubKey
 * @param serialNumber
 * @param name
 * @param notBefore
 * @param notAfter
 * @param signatureAlgorithm
 * @param issuerPrivKey
 * @param issuerCert
 * @param friendlyName
 * @return X509Certificate
 * @throws Exception
 */
public static X509Certificate createCert(PublicKey pubKey, BigInteger serialNumber, String name, Date notBefore,
        Date notAfter, String signatureAlgorithm, PrivateKey issuerPrivKey, X509Certificate issuerCert,
        String friendlyName) throws Exception {
    byte[] nameBytes = new X500Principal(name).getEncoded();

    //
    // create the certificate - version 3
    //
    v3CertGen.reset();

    v3CertGen.setSerialNumber(serialNumber);
    v3CertGen.setIssuerDN(new X509Principal(issuerCert.getSubjectX500Principal().getEncoded()));
    v3CertGen.setNotBefore(notBefore);
    v3CertGen.setNotAfter(notAfter);
    v3CertGen.setSubjectDN(new X509Principal(nameBytes));
    v3CertGen.setPublicKey(pubKey);
    v3CertGen.setSignatureAlgorithm(signatureAlgorithm);

    //
    // add the extensions
    //
    v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, createSubjectKeyId(pubKey));

    v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            createAuthorityKeyId(issuerCert.getPublicKey(),
                    new X509Principal(issuerCert.getSubjectX500Principal().getEncoded()), serialNumber));

    v3CertGen.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false));

    v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false,
            new NetscapeCertType(NetscapeCertType.sslServer | NetscapeCertType.sslClient
                    | NetscapeCertType.objectSigning | NetscapeCertType.smime));

    X509Certificate cert = v3CertGen.generateX509Certificate(issuerPrivKey);

    if (friendlyName != null) {
        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert;

        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(friendlyName));
        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, createSubjectKeyId(pubKey));
    }

    return cert;
}

From source file:org.openmaji.implementation.security.utility.cert.CertUtil.java

License:Open Source License

/**
 * Generate a certificate which is a "copy" of another certificate, but 
* resigned by a different issuer.//from   w  w  w. j  a va2  s.c  om
 *
 * @param initialCert
 * @param serialNumber
 * @param signatureAlgorithm
 * @param issuerPrivKey
 * @param issuerCert
 * @return X509Certificate
 */
public static X509Certificate resignCert(X509Certificate initialCert, BigInteger serialNumber,
        String signatureAlgorithm, PrivateKey issuerPrivKey, X509Certificate issuerCert) throws Exception {
    //
    // create the certificate - version 3
    //
    v3CertGen.reset();

    v3CertGen.setSerialNumber(serialNumber);
    v3CertGen.setIssuerDN(new X509Principal(issuerCert.getSubjectX500Principal().getEncoded()));
    v3CertGen.setNotBefore(initialCert.getNotBefore());
    v3CertGen.setNotAfter(initialCert.getNotAfter());
    v3CertGen.setSubjectDN(new X509Principal(initialCert.getSubjectX500Principal().getEncoded()));
    v3CertGen.setPublicKey(initialCert.getPublicKey());
    v3CertGen.setSignatureAlgorithm(signatureAlgorithm);

    //
    // add the extensions
    //
    v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            createSubjectKeyId(initialCert.getPublicKey()));

    v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            createAuthorityKeyId(issuerCert.getPublicKey(),
                    new X509Principal(issuerCert.getSubjectX500Principal().getEncoded()), serialNumber));

    v3CertGen.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(false));

    v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false, new NetscapeCertType(
            NetscapeCertType.sslClient | NetscapeCertType.objectSigning | NetscapeCertType.smime));

    X509Certificate cert = v3CertGen.generateX509Certificate(issuerPrivKey);

    return cert;
}

From source file:org.openmaji.implementation.server.security.auth.CoreAdminHelper.java

License:Open Source License

private static void userAdd(String userID, char[] userPass, String userName, String emailAddress,
        Date expiryDate) throws Exception {
    if (!userID.toLowerCase().equals(userID)) {
        throw new IllegalArgumentException("username's cannot have mixed case - must be lower case only.");
    }/*  w  w  w. j av  a 2 s . c  om*/

    String keyStorePasswd = System.getProperty(MeemCoreRootAuthority.KEYSTORE_PASSWD);
    if (keyStorePasswd == null) {
        throw new RuntimeException("unable to find property for key store password.");
    }

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    MajiKeyStore keyStore = MeemCoreRootAuthority.getMajiKeyStore();
    KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA");

    kpGen.initialize(1024);

    // get "server" key
    PrivateKey signingKey = (PrivateKey) keyStore.getKey(MeemCoreRootAuthority.KEY_ID,
            keyStorePasswd.toCharArray());
    Certificate[] certs = keyStore.getCertificateChain(MeemCoreRootAuthority.KEY_ID);
    X509Certificate signingCert = (X509Certificate) certs[0];
    KeyPair userKey = kpGen.generateKeyPair();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(signingCert));
    certGen.setNotBefore(new Date());
    certGen.setNotAfter(expiryDate);
    certGen.setPublicKey(userKey.getPublic());

    if (emailAddress != null) {
        certGen.setSubjectDN(new X509Principal(new X500Principal("CN=" + userName + ", T=" + userID
                + ", EMAILADDRESS=" + emailAddress + ", OU=Maji, O=Majitek, C=AU").getEncoded()));
    } else {
        certGen.setSubjectDN(new X509Principal(
                new X500Principal("CN=" + userName + ", T=" + userID + ", OU=Maji, O=Majitek, C=AU")
                        .getEncoded()));
    }
    certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, createSubjectKeyId(userKey.getPublic()));

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            createAuthorityKeyId(certs[0].getPublicKey(), PrincipalUtil.getSubjectX509Principal(signingCert),
                    signingCert.getSerialNumber()));

    X509Certificate newCert = certGen.generateX509Certificate(signingKey);

    Certificate[] chain = new Certificate[certs.length + 1];

    chain[0] = newCert;
    System.arraycopy(certs, 0, chain, 1, certs.length);

    //
    // having set up the chain add the user.
    //
    MajiKeyStore userKeyStore = MeemCoreRootAuthority.getUserKeyStore();

    try {
        Certificate[] testCerts = userKeyStore.getCertificateChain(userID);
        if (testCerts != null) {
            logger.log(Level.WARNING,
                    "User, \"" + userID + "\" already exists.  The certificate chain might not be updated");
        }
    } catch (KeyStoreException e) {
    }

    userKeyStore.setKeyEntry(userID, userKey.getPrivate(), userPass, chain);

    logger.log(Level.INFO, "User, \"" + userID + "\" added.");

    userKeyStore.store();

    //
    // store the encrypted password
    //
    byte[] userPassBytes = new byte[userPass.length];
    for (int i = 0; i != userPass.length; i++) {
        userPassBytes[i] = (byte) userPass[i];
    }

    Cipher cipher = Cipher.getInstance("RSA/NONE/OAEPPadding", "BC");

    cipher.init(Cipher.ENCRYPT_MODE, certs[0].getPublicKey());

    MeemCoreRootAuthority.getUserPasswordFile().setPassword(userID, cipher.doFinal(userPassBytes));
}

From source file:org.opensaml.xml.security.x509.X509Util.java

License:Apache License

/**
 * Get the plain (non-DER encoded) value of the Subject Key Identifier extension of an X.509 certificate, if
 * present.//from www  . j a v  a  2 s  . c o m
 * 
 * @param certificate an X.509 certificate possibly containing a subject key identifier
 * @return the plain (non-DER encoded) value of the Subject Key Identifier extension, or null if the certificate
 *         does not contain the extension
 * @throws IOException
 */
public static byte[] getSubjectKeyIdentifier(X509Certificate certificate) {
    byte[] derValue = certificate.getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId());
    if (derValue == null || derValue.length == 0) {
        return null;
    }

    SubjectKeyIdentifier ski = null;
    try {
        ski = new SubjectKeyIdentifierStructure(derValue);
    } catch (IOException e) {
        log.error("Unable to extract subject key identifier from certificate: ASN.1 parsing failed: " + e);
        return null;
    }

    if (ski != null) {
        return ski.getKeyIdentifier();
    } else {
        return null;
    }
}

From source file:org.openuat.channel.X509CertificateGenerator.java

License:Open Source License

/** This method implements the public one, but offers an additional parameter which is only used when
 * creating a new CA, namely the export alias to use.
 * @param commonName @see #createCertificate(String, int, String, String)
 * @param validityDays @see #createCertificate(String, int, String, String)
 * @param exportFile @see #createCertificate(String, int, String, String)
 * @param exportPassword @see #createCertificate(String, int, String, String)
 * @param exportAlias If this additional parameter is null, a default value will be used as the "friendly name" in the PKCS12 file.
 * @return @see #createCertificate(String, int, String, String)
 * /*from  ww w .  ja  v a  2 s.  c o  m*/
 * @see #X509CertificateGenerator(boolean)
 */
protected boolean createCertificate(String commonName, int validityDays, String exportFile,
        String exportPassword, String exportAlias) throws IOException, InvalidKeyException, SecurityException,
        SignatureException, NoSuchAlgorithmException, DataLengthException, CryptoException, KeyStoreException,
        CertificateException, InvalidKeySpecException {
    if (commonName == null || exportFile == null || exportPassword == null || validityDays < 1) {
        throw new IllegalArgumentException("Can not work with null parameter");
    }

    logger.info("Generating certificate for distinguished common subject name '" + commonName + "', valid for "
            + validityDays + " days");
    SecureRandom sr = new SecureRandom();

    // the JCE representation
    PublicKey pubKey;
    PrivateKey privKey;

    // the BCAPI representation
    RSAPrivateCrtKeyParameters privateKey = null;

    logger.debug("Creating RSA keypair");
    // generate the keypair for the new certificate
    if (useBCAPI) {
        RSAKeyPairGenerator gen = new RSAKeyPairGenerator();
        // TODO: what are these values??
        gen.init(new RSAKeyGenerationParameters(BigInteger.valueOf(0x10001), sr, 1024, 80));
        AsymmetricCipherKeyPair keypair = gen.generateKeyPair();
        logger.debug("Generated keypair, extracting components and creating public structure for certificate");
        RSAKeyParameters publicKey = (RSAKeyParameters) keypair.getPublic();
        privateKey = (RSAPrivateCrtKeyParameters) keypair.getPrivate();
        // used to get proper encoding for the certificate
        RSAPublicKeyStructure pkStruct = new RSAPublicKeyStructure(publicKey.getModulus(),
                publicKey.getExponent());
        logger.debug("New public key is '" + new String(Hex.encodeHex(pkStruct.getEncoded())) + ", exponent="
                + publicKey.getExponent() + ", modulus=" + publicKey.getModulus());
        // TODO: these two lines should go away
        // JCE format needed for the certificate - because getEncoded() is necessary...
        pubKey = KeyFactory.getInstance("RSA")
                .generatePublic(new RSAPublicKeySpec(publicKey.getModulus(), publicKey.getExponent()));
        // and this one for the KeyStore
        privKey = KeyFactory.getInstance("RSA")
                .generatePrivate(new RSAPrivateCrtKeySpec(publicKey.getModulus(), publicKey.getExponent(),
                        privateKey.getExponent(), privateKey.getP(), privateKey.getQ(), privateKey.getDP(),
                        privateKey.getDQ(), privateKey.getQInv()));
    } else {
        // this is the JSSE way of key generation
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024, sr);
        KeyPair keypair = keyGen.generateKeyPair();
        privKey = keypair.getPrivate();
        pubKey = keypair.getPublic();
    }

    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, validityDays);

    X509Name x509Name = new X509Name("CN=" + commonName);

    V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
    certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis())));
    if (caCert != null) {
        // Attention: this is a catch! Just using "new X509Name(caCert.getSubjectDN().getName())" will not work!
        // I don't know why, because the issuerDN strings look similar with both versions.
        certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert));
    } else {
        // aha, no CA set, which means that we should create a self-signed certificate (called from createCA)
        certGen.setIssuer(x509Name);
    }
    certGen.setSubject(x509Name);
    DERObjectIdentifier sigOID = X509Util.getAlgorithmOID(CertificateSignatureAlgorithm);
    AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull());
    certGen.setSignature(sigAlgId);
    //certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(sigAlgId, pkStruct.toASN1Object()));
    // TODO: why does the coding above not work? - make me work without PublicKey class
    certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(
            (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded())).readObject()));
    certGen.setStartDate(new Time(new Date(System.currentTimeMillis())));
    certGen.setEndDate(new Time(expiry.getTime()));

    // These X509v3 extensions are not strictly necessary, but be nice and provide them...
    Hashtable extensions = new Hashtable();
    Vector extOrdering = new Vector();
    addExtensionHelper(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey),
            extOrdering, extensions);
    if (caCert != null) {
        // again: only if we have set CA
        addExtensionHelper(X509Extensions.AuthorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(caCert), extOrdering, extensions);
    } else {
        // but if we create a new self-signed cert, set its capability to be a CA
        // this is a critical extension (true)!
        addExtensionHelper(X509Extensions.BasicConstraints, true, new BasicConstraints(0), extOrdering,
                extensions);
    }
    certGen.setExtensions(new X509Extensions(extOrdering, extensions));

    logger.debug("Certificate structure generated, creating SHA1 digest");
    // attention: hard coded to be SHA1+RSA!
    SHA1Digest digester = new SHA1Digest();
    AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
    TBSCertificateStructure tbsCert = certGen.generateTBSCertificate();

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(tbsCert);

    // and now sign
    byte[] signature;
    if (useBCAPI) {
        byte[] certBlock = bOut.toByteArray();
        // first create digest
        logger.debug("Block to sign is '" + new String(Hex.encodeHex(certBlock)) + "'");
        digester.update(certBlock, 0, certBlock.length);
        byte[] hash = new byte[digester.getDigestSize()];
        digester.doFinal(hash, 0);
        // and sign that
        if (caCert != null) {
            rsa.init(true, caPrivateKey);
        } else {
            // no CA - self sign
            logger.info("No CA has been set, creating self-signed certificate as a new CA");
            rsa.init(true, privateKey);
        }
        DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash);
        byte[] digest = dInfo.getEncoded(ASN1Encodable.DER);
        signature = rsa.processBlock(digest, 0, digest.length);
    } else {
        // or the JCE way
        Signature sig = Signature.getInstance(sigOID.getId());
        if (caCert != null) {
            PrivateKey caPrivKey = KeyFactory.getInstance("RSA")
                    .generatePrivate(new RSAPrivateCrtKeySpec(caPrivateKey.getModulus(),
                            caPrivateKey.getPublicExponent(), caPrivateKey.getExponent(), caPrivateKey.getP(),
                            caPrivateKey.getQ(), caPrivateKey.getDP(), caPrivateKey.getDQ(),
                            caPrivateKey.getQInv()));
            sig.initSign(caPrivKey, sr);
        } else {
            logger.info("No CA has been set, creating self-signed certificate as a new CA");
            sig.initSign(privKey, sr);
        }
        sig.update(bOut.toByteArray());
        signature = sig.sign();
    }
    logger.debug("SHA1/RSA signature of digest is '" + new String(Hex.encodeHex(signature)) + "'");

    // and finally construct the certificate structure
    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCert);
    v.add(sigAlgId);
    v.add(new DERBitString(signature));

    X509CertificateObject clientCert = new X509CertificateObject(
            new X509CertificateStructure(new DERSequence(v)));
    logger.debug("Verifying certificate for correct signature with CA public key");
    /*        if (caCert != null) {
               clientCert.verify(caCert.getPublicKey());
            }
            else {
               clientCert.verify(pubKey);
            }*/

    // and export as PKCS12 formatted file along with the private key and the CA certificate 
    logger.debug("Exporting certificate in PKCS12 format");

    PKCS12BagAttributeCarrier bagCert = clientCert;
    // if exportAlias is set, use that, otherwise a default name
    bagCert.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
            new DERBMPString(exportAlias == null ? CertificateExportFriendlyName : exportAlias));
    bagCert.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
            new SubjectKeyIdentifierStructure(pubKey));

    // this does not work as in the example
    /*PKCS12BagAttributeCarrier   bagKey = (PKCS12BagAttributeCarrier)privKey;
    bagKey.setBagAttribute(
    PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
    new SubjectKeyIdentifierStructure(tmpKey));*/

    Object store;
    if (!useBCAPI) {
        store = java.security.KeyStore.getInstance("PKCS12");
        ((java.security.KeyStore) store).load(null, null);
    } else {
        store = new JDKPKCS12KeyStore(null, sigOID, sigOID);
        ((JDKPKCS12KeyStore) store).engineLoad(null, null);
    }

    FileOutputStream fOut = new FileOutputStream(exportFile);
    X509Certificate[] chain;

    if (caCert != null) {
        chain = new X509Certificate[2];
        // first the client, then the CA certificate - this is the expected order for a certificate chain
        chain[0] = clientCert;
        chain[1] = caCert;
    } else {
        // for a self-signed certificate, there is no chain...
        chain = new X509Certificate[1];
        chain[0] = clientCert;
    }

    if (!useBCAPI) {
        ((java.security.KeyStore) store).setKeyEntry(exportAlias == null ? KeyExportFriendlyName : exportAlias,
                privKey, exportPassword.toCharArray(), chain);
        ((java.security.KeyStore) store).store(fOut, exportPassword.toCharArray());
    } else {
        ((JDKPKCS12KeyStore) store).engineSetKeyEntry(exportAlias == null ? KeyExportFriendlyName : exportAlias,
                privKey, exportPassword.toCharArray(), chain);
        ((JDKPKCS12KeyStore) store).engineStore(fOut, exportPassword.toCharArray());
    }

    return true;
}

From source file:org.overlord.commons.karaf.commands.saml.GenerateSamlKeystoreUtil.java

License:Apache License

/**
 * Creates a new key pair and self-signed certificate.
 *
 * @param alias//ww w  . j  av a2s.c  o  m
 *            the alias
 * @param dname
 *            the dname
 * @param keyAlgName
 *            the key alg name
 * @param keysize
 *            the keysize
 * @param sigAlgName
 *            the sig alg name
 * @throws Exception
 *             the exception
 */
private void doGenKeyPair(String alias, String dname, String keyAlgName, int keysize, String sigAlgName)
        throws Exception {

    if (keysize == -1) {
        if ("EC".equalsIgnoreCase(keyAlgName)) { //$NON-NLS-1$
            keysize = 256;
        } else if ("RSA".equalsIgnoreCase(keyAlgName)) { //$NON-NLS-1$
            keysize = 2048;
        } else {
            keysize = 1024;
        }
    }

    if (keyStore.containsAlias(alias)) {
        throw new Exception(Messages.getString("Key.pair.not.generated.alias.alias.already.exists")); //$NON-NLS-1$
    }

    if (sigAlgName == null) {
        sigAlgName = getCompatibleSigAlgName(keyAlgName);
    }

    KeyPairGenerator generator = KeyPairGenerator.getInstance(keyAlgName);
    generator.initialize(keysize);
    KeyPair keypair = generator.generateKeyPair();
    PrivateKey privKey = keypair.getPrivate();

    X509Certificate[] chain = new X509Certificate[1];

    Date date = getStartDate(startDate);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date); // Configuramos la fecha que se recibe
    calendar.add(Calendar.DAY_OF_YEAR, validity);
    // time from which certificate is valid
    Date expiryDate = calendar.getTime(); // time after which certificate is not valid
    BigInteger serialNumber = new BigInteger("10"); // serial number for certificate //$NON-NLS-1$
    // private key of the certifying authority (ca) certificate

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    X500Principal subjectName = new X500Principal(dname);

    certGen.setSerialNumber(serialNumber);
    certGen.setIssuerDN(subjectName);
    certGen.setNotBefore(date);
    certGen.setNotAfter(expiryDate);
    certGen.setSubjectDN(subjectName);
    certGen.setPublicKey(keypair.getPublic());
    certGen.setSignatureAlgorithm("SHA256withRSA"); //$NON-NLS-1$

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(keypair.getPublic()));

    X509Certificate cert = certGen.generate(keypair.getPrivate(), providerName);
    chain[0] = cert;

    keyStore.setKeyEntry(alias, privKey, keyPass, chain);
}

From source file:org.owasp.proxy.util.BouncyCastleCertificateUtils.java

License:Open Source License

private static void addCertificateExtensions(PublicKey pubKey, PublicKey caPubKey,
        X509V3CertificateGenerator certGen) throws IOException, InvalidKeyException {

    // CertificateExtensions ext = new CertificateExtensions();
    ///*from   w  w w .ja v a2  s  . c om*/
    // ext.set(SubjectKeyIdentifierExtension.NAME,
    // new SubjectKeyIdentifierExtension(new KeyIdentifier(pubKey)
    // .getIdentifier()));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey));
    //
    // ext.set(AuthorityKeyIdentifierExtension.NAME,
    // new AuthorityKeyIdentifierExtension(
    // new KeyIdentifier(caPubKey), null, null));
    //
    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caPubKey));
    // // Basic Constraints
    // ext.set(BasicConstraintsExtension.NAME, new
    // BasicConstraintsExtension(
    // /* isCritical */true, /* isCA */false, /* pathLen */5));
    //
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    // Netscape Cert Type Extension
    // boolean[] ncteOk = new boolean[8];
    // ncteOk[0] = true; // SSL_CLIENT
    // ncteOk[1] = true; // SSL_SERVER
    // NetscapeCertTypeExtension ncte = new
    // NetscapeCertTypeExtension(ncteOk);
    // ncte = new NetscapeCertTypeExtension(false,
    // ncte.getExtensionValue());
    // ext.set(NetscapeCertTypeExtension.NAME, ncte);

    // Key Usage Extension
    // boolean[] kueOk = new boolean[9];
    // kueOk[0] = true;
    // kueOk[2] = true;
    // "digitalSignature", // (0),
    // "nonRepudiation", // (1)
    // "keyEncipherment", // (2),
    // "dataEncipherment", // (3),
    // "keyAgreement", // (4),
    // "keyCertSign", // (5),
    // "cRLSign", // (6),
    // "encipherOnly", // (7),
    // "decipherOnly", // (8)
    // "contentCommitment" // also (1)
    // KeyUsageExtension kue = new KeyUsageExtension(kueOk);
    // ext.set(KeyUsageExtension.NAME, kue);
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new X509KeyUsage(X509KeyUsage.digitalSignature + X509KeyUsage.keyEncipherment));

    // Extended Key Usage Extension
    // int[] serverAuthOidData = { 1, 3, 6, 1, 5, 5, 7, 3, 1 };
    // ObjectIdentifier serverAuthOid = new
    // ObjectIdentifier(serverAuthOidData);
    // int[] clientAuthOidData = { 1, 3, 6, 1, 5, 5, 7, 3, 2 };
    // ObjectIdentifier clientAuthOid = new
    // ObjectIdentifier(clientAuthOidData);
    // Vector<ObjectIdentifier> v = new Vector<ObjectIdentifier>();
    // v.add(serverAuthOid);
    // v.add(clientAuthOid);
    // ExtendedKeyUsageExtension ekue = new ExtendedKeyUsageExtension(false,
    // v);
    // ext.set(ExtendedKeyUsageExtension.NAME, ekue);
    // ExtendedKeyUsage extendedKeyUsage = new
    // ExtendedKeyUsage(KeyPurposeId.anyExtendedKeyUsage);
    Vector<KeyPurposeId> usages = new Vector<KeyPurposeId>();
    usages.add(KeyPurposeId.id_kp_serverAuth);
    usages.add(KeyPurposeId.id_kp_clientAuth);
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(usages));

}

From source file:org.qipki.ca.domain.ca.CAMixin.java

License:Open Source License

@Override
public X509Certificate sign(X509Profile x509profile, PKCS10CertificationRequest pkcs10) {
    LOGGER.debug(/*from ww w . j a  v  a 2s  . co m*/
            "Handling a PKCS#10 Certificate Signing Request using X509Profile " + x509profile.name().get());
    try {

        ensureX509ProfileIsAllowed(x509profile);

        List<X509ExtensionHolder> extensions = x509ExtReader.extractRequestedExtensions(pkcs10);
        ensureNoIllegalRequestedExtensions(extensions);

        // Adding extensions commons to all profiles
        SubjectKeyIdentifier subjectKeyID = x509ExtBuilder.buildSubjectKeyIdentifier(pkcs10.getPublicKey());
        extensions.add(new X509ExtensionHolder(X509Extensions.SubjectKeyIdentifier, false, subjectKeyID));
        AuthorityKeyIdentifier authKeyID = x509ExtBuilder
                .buildAuthorityKeyIdentifier(certificate().getPublicKey());
        extensions.add(new X509ExtensionHolder(X509Extensions.AuthorityKeyIdentifier, false, authKeyID));

        // Applying X509Profile on issued X509Certificate
        if (x509profile.basicConstraints().get().subjectIsCA().get()) {
            BasicConstraints bc = x509ExtBuilder
                    .buildCABasicConstraints(x509profile.basicConstraints().get().pathLengthConstraint().get());
            extensions.add(new X509ExtensionHolder(X509Extensions.BasicConstraints,
                    x509profile.basicConstraints().get().critical().get(), bc));
        } else {
            BasicConstraints bc = x509ExtBuilder.buildNonCABasicConstraints();
            extensions.add(new X509ExtensionHolder(X509Extensions.BasicConstraints,
                    x509profile.basicConstraints().get().critical().get(), bc));
        }
        KeyUsage keyUsages = x509ExtBuilder.buildKeyUsages(x509profile.keyUsages().get().keyUsages().get());
        extensions.add(new X509ExtensionHolder(X509Extensions.KeyUsage,
                x509profile.keyUsages().get().critical().get(), keyUsages));

        ExtendedKeyUsage extendedKeyUsage = x509ExtBuilder
                .buildExtendedKeyUsage(x509profile.extendedKeyUsages().get().extendedKeyUsages().get());
        extensions.add(new X509ExtensionHolder(X509Extensions.ExtendedKeyUsage,
                x509profile.extendedKeyUsages().get().critical().get(), extendedKeyUsage));

        NetscapeCertType netscapeCertType = x509ExtBuilder
                .buildNetscapeCertTypes(x509profile.netscapeCertTypes().get().netscapeCertTypes().get());
        extensions.add(new X509ExtensionHolder(MiscObjectIdentifiers.netscapeCertType,
                x509profile.netscapeCertTypes().get().critical().get(), netscapeCertType));

        String[] crlDistPoints = gatherCRLDistributionPoints();
        if (crlDistPoints.length > 0) {
            CRLDistPoint crlDistPointsExt = x509ExtBuilder
                    .buildCRLDistributionPoints(certificate().getSubjectX500Principal(), crlDistPoints);
            extensions.add(
                    new X509ExtensionHolder(X509Extensions.CRLDistributionPoints, false, crlDistPointsExt));
        }

        DistinguishedName issuerDN = new DistinguishedName(certificate().getSubjectX500Principal());
        DistinguishedName subjectDN = new DistinguishedName(pkcs10.getCertificationRequestInfo().getSubject());
        X509Certificate certificate = x509Generator.generateX509Certificate(privateKey(), issuerDN,
                BigInteger.probablePrime(120, new SecureRandom()), subjectDN, pkcs10.getPublicKey(),
                Duration.standardDays(x509profile.validityDays().get()), extensions);

        return certificate;

    } catch (GeneralSecurityException ex) {
        LOGGER.error(ex.getMessage(), ex);
        throw new QiPkiFailure("Unable to enroll PKCS#10", ex);
    }
}

From source file:org.qipki.crypto.x509.X509ExtensionsReaderImpl.java

License:Open Source License

@Override
public byte[] getSubjectKeyIdentifier(X509Certificate cert) {
    try {/*w  w w .j  a va  2s . c  o  m*/
        byte[] value = cert.getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId());
        if (value == null) {
            return null;
        }
        byte[] octets = ((ASN1OctetString) ASN1Object.fromByteArray(value)).getOctets();
        return SubjectKeyIdentifier.getInstance(ASN1Object.fromByteArray(octets)).getKeyIdentifier();
    } catch (IOException ex) {
        throw new CryptoFailure("Unable to extract SubjectKeyIdentifier from X509Certificate extensions", ex);
    }
}

From source file:org.sufficientlysecure.keychain.pgp.PgpToX509.java

License:Open Source License

/**
 * Creates a self-signed certificate from a public and private key. The (critical) key-usage
 * extension is set up with: digital signature, non-repudiation, key-encipherment, key-agreement
 * and certificate-signing. The (non-critical) Netscape extension is set up with: SSL client and
 * S/MIME. A URI subjectAltName may also be set up.
 *
 * @param pubKey         public key/*  w w  w  .j  a  v a 2s .c  om*/
 * @param privKey        private key
 * @param subject        subject (and issuer) DN for this certificate, RFC 2253 format preferred.
 * @param startDate      date from which the certificate will be valid (defaults to current date and time
 *                       if null)
 * @param endDate        date until which the certificate will be valid (defaults to current date and time
 *                       if null) *
 * @param subjAltNameURI URI to be placed in subjectAltName
 * @return self-signed certificate
 * @throws InvalidKeyException
 * @throws SignatureException
 * @throws NoSuchAlgorithmException
 * @throws IllegalStateException
 * @throws NoSuchProviderException
 * @throws CertificateException
 * @throws Exception
 * @author Bruno Harbulot
 */
public static X509Certificate createSelfSignedCert(PublicKey pubKey, PrivateKey privKey, X509Name subject,
        Date startDate, Date endDate, String subjAltNameURI) throws InvalidKeyException, IllegalStateException,
        NoSuchAlgorithmException, SignatureException, CertificateException, NoSuchProviderException {

    X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();

    certGenerator.reset();
    /*
     * Sets up the subject distinguished name. Since it's a self-signed certificate, issuer and
     * subject are the same.
     */
    certGenerator.setIssuerDN(subject);
    certGenerator.setSubjectDN(subject);

    /*
     * Sets up the validity dates.
     */
    if (startDate == null) {
        startDate = new Date(System.currentTimeMillis());
    }
    certGenerator.setNotBefore(startDate);
    if (endDate == null) {
        endDate = new Date(startDate.getTime() + (365L * 24L * 60L * 60L * 1000L));
        Log.d(Constants.TAG, "end date is=" + DateFormat.getDateInstance().format(endDate));
    }

    certGenerator.setNotAfter(endDate);

    /*
     * The serial-number of this certificate is 1. It makes sense because it's self-signed.
     */
    certGenerator.setSerialNumber(BigInteger.ONE);
    /*
     * Sets the public-key to embed in this certificate.
     */
    certGenerator.setPublicKey(pubKey);
    /*
     * Sets the signature algorithm.
     */
    String pubKeyAlgorithm = pubKey.getAlgorithm();
    if (pubKeyAlgorithm.equals("DSA")) {
        certGenerator.setSignatureAlgorithm("SHA1WithDSA");
    } else if (pubKeyAlgorithm.equals("RSA")) {
        certGenerator.setSignatureAlgorithm("SHA1WithRSAEncryption");
    } else {
        RuntimeException re = new RuntimeException("Algorithm not recognised: " + pubKeyAlgorithm);
        Log.e(Constants.TAG, re.getMessage(), re);
        throw re;
    }

    /*
     * Adds the Basic Constraint (CA: true) extension.
     */
    certGenerator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));

    /*
     * Adds the subject key identifier extension.
     */
    SubjectKeyIdentifier subjectKeyIdentifier = new SubjectKeyIdentifierStructure(pubKey);
    certGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false, subjectKeyIdentifier);

    /*
     * Adds the authority key identifier extension.
     */
    AuthorityKeyIdentifier authorityKeyIdentifier = new AuthorityKeyIdentifierStructure(pubKey);
    certGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyIdentifier);

    /*
     * Adds the subject alternative-name extension.
     */
    if (subjAltNameURI != null) {
        GeneralNames subjectAltNames = new GeneralNames(
                new GeneralName(GeneralName.uniformResourceIdentifier, subjAltNameURI));
        certGenerator.addExtension(X509Extensions.SubjectAlternativeName, false, subjectAltNames);
    }

    /*
     * Creates and sign this certificate with the private key corresponding to the public key of
     * the certificate (hence the name "self-signed certificate").
     */
    X509Certificate cert = certGenerator.generate(privKey);

    /*
     * Checks that this certificate has indeed been correctly signed.
     */
    cert.verify(pubKey);

    return cert;
}