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

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

Introduction

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

Prototype

ASN1ObjectIdentifier AuthorityKeyIdentifier

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

Click Source Link

Document

Authority Key Identifier

Usage

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.");
    }/*from   ww  w .  j a  v a  2  s  .  c  o  m*/

    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.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)
 * /*w  w  w  . j a  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.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();
    ///*ww  w.java2 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 w ww. ja  va  2  s  .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 AuthorityKeyIdentifier getAuthorityKeyIdentifier(X509Certificate cert) {
    try {/* ww  w.  j  av a 2  s . co  m*/
        byte[] value = cert.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());
        if (value == null) {
            return null;
        }
        DEROctetString oct = (DEROctetString) (new ASN1InputStream(new ByteArrayInputStream(value))
                .readObject());
        return new AuthorityKeyIdentifier(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())).readObject());
    } catch (IOException ex) {
        throw new CryptoFailure("Unable to extract AuthorityKeyIdentifier from X509Certificate extensions", ex);
    }
}

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

License:Open Source License

@Override
public X509CRL generateX509CRL(X509Certificate caCertificate, PrivateKey caPrivateKey) {
    try {//from   w ww .java  2  s . c  om
        X509V2CRLGenerator crlGen = new X509V2CRLGenerator();
        crlGen.setIssuerDN(caCertificate.getSubjectX500Principal());
        crlGen.setThisUpdate(new DateTime().minus(Time.CLOCK_SKEW).toDate());
        crlGen.setNextUpdate(new DateTime().minus(Time.CLOCK_SKEW).plusHours(12).toDate());
        crlGen.setSignatureAlgorithm(SignatureAlgorithm.SHA256withRSA.jcaString());
        crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(caCertificate));
        crlGen.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(BigInteger.ONE));
        return crlGen.generate(caPrivateKey, BouncyCastleProvider.PROVIDER_NAME);
    } catch (GeneralSecurityException ex) {
        throw new CryptoFailure("Unable to generate CRL", ex);
    }
}

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

License:Open Source License

@Override
public X509CRL updateX509CRL(X509Certificate caCertificate, PrivateKey caPrivateKey,
        X509Certificate revokedCertificate, RevocationReason reason, X509CRL previousCRL,
        BigInteger lastCRLNumber) {
    try {//from w  w  w .  jav a  2  s  .c  o m
        X509V2CRLGenerator crlGen = new X509V2CRLGenerator();
        crlGen.setIssuerDN(caCertificate.getSubjectX500Principal());
        DateTime skewedNow = new DateTime().minus(Time.CLOCK_SKEW);
        crlGen.setThisUpdate(skewedNow.toDate());
        crlGen.setNextUpdate(skewedNow.plusHours(12).toDate());
        crlGen.setSignatureAlgorithm(SignatureAlgorithm.SHA256withRSA.jcaString());
        crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(caCertificate));
        crlGen.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(lastCRLNumber));
        crlGen.addCRL(previousCRL);
        crlGen.addCRLEntry(revokedCertificate.getSerialNumber(), skewedNow.toDate(), reason.reason());
        return crlGen.generate(caPrivateKey, BouncyCastleProvider.PROVIDER_NAME);
    } catch (GeneralSecurityException ex) {
        throw new CryptoFailure("Unable to update CRL", 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  va  2  s  .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;
}

From source file:org.votingsystem.signature.util.CertUtils.java

License:Open Source License

/**
 * Generate V3 certificate for users/*from   w  w w  .j a  v a 2s  .c om*/
 */
public static X509Certificate generateEndEntityCert(PublicKey entityKey, PrivateKey caKey,
        X509Certificate caCert, Date dateBegin, Date dateFinish, String endEntitySubjectDN) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(KeyGeneratorVS.INSTANCE.getSerno());
    certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert));
    certGen.setNotBefore(dateBegin);
    certGen.setNotAfter(dateFinish);
    certGen.setSubjectDN(new X500Principal(endEntitySubjectDN));
    certGen.setPublicKey(entityKey);
    certGen.setSignatureAlgorithm(ContextVS.CERT_GENERATION_SIG_ALGORITHM);
    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(entityKey));
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    return certGen.generate(caKey, ContextVS.PROVIDER);
}

From source file:org.votingsystem.signature.util.CertUtils.java

License:Open Source License

/**
 * Generate V3 certificate for TimeStamp signing
 *//*w w w.ja  v  a 2s .c o m*/
public static X509Certificate generateTimeStampingCert(PublicKey entityKey, PrivateKey caKey,
        X509Certificate caCert, long begin, long period, String endEntitySubjectDN) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert));
    certGen.setNotBefore(new Date(begin));
    certGen.setNotAfter(new Date(begin + period));
    certGen.setSubjectDN(new X500Principal(endEntitySubjectDN));
    certGen.setPublicKey(entityKey);
    certGen.setSignatureAlgorithm(ContextVS.CERT_GENERATION_SIG_ALGORITHM);
    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(entityKey));
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(new DERSequence(KeyPurposeId.id_kp_timeStamping)));
    return certGen.generate(caKey, ContextVS.PROVIDER);
}