Example usage for org.bouncycastle.jce X509KeyUsage digitalSignature

List of usage examples for org.bouncycastle.jce X509KeyUsage digitalSignature

Introduction

In this page you can find the example usage for org.bouncycastle.jce X509KeyUsage digitalSignature.

Prototype

int digitalSignature

To view the source code for org.bouncycastle.jce X509KeyUsage digitalSignature.

Click Source Link

Usage

From source file:com.google.android.gms.common.GooglePlayServicesUtil.java

private static void zzJ(Context context) {
    ApplicationInfo applicationInfo = null;
    try {/* ww w .j av a2 s. co  m*/
        applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(),
                X509KeyUsage.digitalSignature);
    } catch (Throwable e) {
        Log.wtf("GooglePlayServicesUtil", "This should never happen.", e);
    }
    Bundle bundle = applicationInfo.metaData;
    if (bundle != null) {
        int i = bundle.getInt("com.google.android.gms.version");
        if (i != GOOGLE_PLAY_SERVICES_VERSION_CODE) {
            throw new IllegalStateException(
                    "The meta-data tag in your app's AndroidManifest.xml does not have the right value.  Expected 7095000 but found "
                            + i + ".  You must have the"
                            + " following declaration within the <application> element: "
                            + "    <meta-data android:name=\"" + "com.google.android.gms.version"
                            + "\" android:value=\"@integer/google_play_services_version\" />");
        }
        return;
    }
    throw new IllegalStateException(
            "A required meta-data tag in your app's AndroidManifest.xml does not exist.  You must have the following declaration within the <application> element:     <meta-data android:name=\"com.google.android.gms.version\" android:value=\"@integer/google_play_services_version\" />");
}

From source file:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static X509Certificate generateX509Certificate(PKCS10CertificationRequest certReq,
        PrivateKey caPrivateKey, X500Name issuer, int validityTimeout, boolean basicConstraints) {

    // set validity for the given number of minutes from now

    Date notBefore = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(notBefore);//w w  w  .j a v a2 s .c om
    cal.add(Calendar.MINUTE, validityTimeout);
    Date notAfter = cal.getTime();

    // Generate self-signed certificate

    X509Certificate cert = null;
    try {
        JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = new JcaPKCS10CertificationRequest(
                certReq);
        PublicKey publicKey = jcaPKCS10CertificationRequest.getPublicKey();

        X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder(issuer,
                BigInteger.valueOf(System.currentTimeMillis()), notBefore, notAfter, certReq.getSubject(),
                publicKey)
                        .addExtension(Extension.basicConstraints, false, new BasicConstraints(basicConstraints))
                        .addExtension(Extension.keyUsage, true,
                                new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment))
                        .addExtension(Extension.extendedKeyUsage, true,
                                new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth,
                                        KeyPurposeId.id_kp_serverAuth }));

        // see if we have the dns/rfc822/ip address extensions specified in the csr

        ArrayList<GeneralName> altNames = new ArrayList<>();
        Attribute[] certAttributes = jcaPKCS10CertificationRequest
                .getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        if (certAttributes != null && certAttributes.length > 0) {
            for (Attribute attribute : certAttributes) {
                Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
                GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
                if (gns == null) {
                    continue;
                }
                GeneralName[] names = gns.getNames();
                for (int i = 0; i < names.length; i++) {
                    switch (names[i].getTagNo()) {
                    case GeneralName.dNSName:
                    case GeneralName.iPAddress:
                    case GeneralName.rfc822Name:
                        altNames.add(names[i]);
                        break;
                    }
                }
            }
            if (!altNames.isEmpty()) {
                caBuilder.addExtension(Extension.subjectAlternativeName, false,
                        new GeneralNames(altNames.toArray(new GeneralName[altNames.size()])));
            }
        }

        String signatureAlgorithm = getSignatureAlgorithm(caPrivateKey.getAlgorithm(), SHA256);
        ContentSigner caSigner = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC_PROVIDER)
                .build(caPrivateKey);

        JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC_PROVIDER);
        cert = converter.getCertificate(caBuilder.build(caSigner));

    } catch (CertificateException ex) {
        LOG.error("generateX509Certificate: Caught CertificateException when generating certificate: "
                + ex.getMessage());
        throw new CryptoException(ex);
    } catch (OperatorCreationException ex) {
        LOG.error(
                "generateX509Certificate: Caught OperatorCreationException when creating JcaContentSignerBuilder: "
                        + ex.getMessage());
        throw new CryptoException(ex);
    } catch (InvalidKeyException ex) {
        LOG.error("generateX509Certificate: Caught InvalidKeySpecException, invalid key spec is being used: "
                + ex.getMessage());
        throw new CryptoException(ex);
    } catch (NoSuchAlgorithmException ex) {
        LOG.error(
                "generateX509Certificate: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider: "
                        + ex.getMessage());
        throw new CryptoException(ex);
    } catch (Exception ex) {
        LOG.error("generateX509Certificate: unable to generate X509 Certificate: " + ex.getMessage());
        throw new CryptoException("Unable to generate X509 Certificate");
    }

    return cert;
}

From source file:me.it_result.ca.bouncycastle.BouncyCABase.java

License:Open Source License

protected X509V3CertificateGenerator assembleCertificate(PublicKey publicKey, PublicKey caPublicKey,
        String subjectDN, String issuerDN, BigInteger serialNumber, boolean ca, int validityDays)
        throws CertificateParsingException, InvalidKeyException, CertificateEncodingException,
        IllegalStateException, NoSuchAlgorithmException, SignatureException, FileNotFoundException {
    certGen.setIssuerDN(new X509Principal(issuerDN));
    certGen.setNotBefore(new Date());
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(System.currentTimeMillis());
    cal.add(Calendar.DAY_OF_MONTH, validityDays);
    certGen.setNotAfter(cal.getTime());/*w w w  .  j  a  va2  s  . c  o  m*/
    certGen.setPublicKey(publicKey);
    certGen.setSerialNumber(serialNumber);
    certGen.setSignatureAlgorithm(signatureAlgorithm);
    certGen.setSubjectDN(new X509Principal(subjectDN));
    X509KeyUsage keyUsage;
    if (ca)
        keyUsage = new X509KeyUsage(X509KeyUsage.cRLSign | X509KeyUsage.keyCertSign);
    else
        keyUsage = new X509KeyUsage(X509KeyUsage.keyEncipherment | X509KeyUsage.digitalSignature);
    certGen.addExtension(X509Extensions.KeyUsage, true, keyUsage.getDEREncoded());
    BasicConstraints basicConstraints = new BasicConstraints(ca);
    certGen.addExtension(X509Extensions.BasicConstraints, true, basicConstraints.getDEREncoded());
    SubjectKeyIdentifierStructure subjectKeyId = new SubjectKeyIdentifierStructure(publicKey);
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, subjectKeyId.getDEREncoded());
    AuthorityKeyIdentifierStructure authorityKeyId = new AuthorityKeyIdentifierStructure(caPublicKey);
    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyId.getDEREncoded());
    return certGen;
}

From source file:me.it_result.ca.bouncycastle.BouncyCATest.java

License:Open Source License

private void verifyCertificate(X509Certificate cert, String subjectName, BigInteger serialNumber, boolean ca,
        boolean server, Date minBeforeDate, Date maxBeforeDate) throws Exception {
    X509Certificate caCert = this.ca.getCACertificate();
    // See http://citrixblogger.org/2010/09/10/certificate-public-key-usage/ for a good assembly of key usage guideline materials
    int expectedKeyUsage;
    if (ca)/*  w w  w.  jav a2s .  c o m*/
        expectedKeyUsage = X509KeyUsage.cRLSign | X509KeyUsage.keyCertSign;
    else
        expectedKeyUsage = X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment;// | X509KeyUsage.dataEncipherment;
    new X509Assertions(cert).type("X.509").version(3).issuedBy(caCert).subjectName(subjectName)
            .serialNumber(serialNumber).validDuring(VALIDITY_DAYS, minBeforeDate, maxBeforeDate)
            .caCertificate(ca).containsSKI().containsAKI()
            .eku(ca ? null
                    : new KeyPurposeId[] {
                            server ? KeyPurposeId.id_kp_serverAuth : KeyPurposeId.id_kp_clientAuth })
            .keyUsage(expectedKeyUsage).noMoreExtensions().signatureAlgrithm(jdkSignatureAlgorithm);
}

From source file:net.java.bd.tools.security.SecurityUtil.java

License:Open Source License

private void generateSelfSignedCertificate(String issuer, String alias, String keyPassword, boolean isRootCert)
        throws Exception {
    Date validFrom, validTo;//from  w  ww .j  a  v a  2 s.co m

    // For forcing GeneralizedTime DER encoding, with Bouncy Castle Provider 
    // make the range before 1950 and after 2050. The BD-J spec recommends
    // using the default validity period used below
    Calendar calendar = Calendar.getInstance();
    calendar.set(0000, 1, 1);
    validFrom = calendar.getTime();
    calendar.clear();
    calendar.set(9999, 1, 1);
    validTo = calendar.getTime();

    // Generate a new keypair for this certificate
    KeyPair keyPair = generateKeyPair();

    X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
    cg.reset();
    X509Name name = new X509Name(issuer, new X509BDJEntryConverter());

    // Generate Serial Number
    SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
    BigInteger serNo = new BigInteger(32, prng);
    cg.setSerialNumber(serNo);
    if (!isRootCert) {
        appCertSerNo = serNo;
    }
    cg.setIssuerDN(name);
    cg.setNotBefore(validFrom);
    cg.setNotAfter(validTo);
    cg.setSubjectDN(name);
    cg.setPublicKey(keyPair.getPublic());
    cg.setSignatureAlgorithm("SHA1WITHRSA");
    if (isRootCert) {
        // Need to add root cert extensions.
        if (isBindingUnitCert) {
            // This certificate is used only for signing
            cg.addExtension(X509Extensions.KeyUsage.getId(), true,
                    new X509KeyUsage(X509KeyUsage.digitalSignature));
        } else {
            int usage = X509KeyUsage.digitalSignature + X509KeyUsage.keyCertSign;
            cg.addExtension(X509Extensions.KeyUsage.getId(), true, new X509KeyUsage(usage));
        }
        cg.addExtension(X509Extensions.IssuerAlternativeName.getId(), false, getRfc822Name(altName));
        cg.addExtension(X509Extensions.BasicConstraints.getId(), true, new BasicConstraints(true));
    }
    // For an app cert, most of the extensions will be added when generating
    // a certificate in response to the certificate request file.
    cg.addExtension(X509Extensions.SubjectAlternativeName.getId(), false, getRfc822Name(altName));

    Certificate cert = cg.generate(keyPair.getPrivate());
    store.setKeyEntry(alias, keyPair.getPrivate(), keyPassword.toCharArray(), new Certificate[] { cert });
    FileOutputStream fos = new FileOutputStream(keystoreFile);
    store.store(fos, keystorePassword.toCharArray());
    fos.close();
}

From source file:net.java.bd.tools.security.SecurityUtil.java

License:Open Source License

void issueCert(String csrfile, String certfile, String alias, String keypass) throws Exception {
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(convertFromBASE64(csrfile));
    String subject = csr.getCertificationRequestInfo().getSubject().toString();

    // Generate the app certificate
    X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
    cg.reset();/*  ww w  .  j  av a  2s .  c  o  m*/
    X509Certificate rootCert = (X509Certificate) store.getCertificate(alias);
    if (rootCert == null) {
        System.out
                .println("ERROR: Aborting application certificate creation." + " No root certificate to sign.");
        cleanup(); // removes the self signed certificate from the keystore
        System.exit(1);
    }
    cg.setIssuerDN(new X509Name(true, rootCert.getSubjectDN().getName(), new X509BDJEntryConverter()));
    cg.setSubjectDN(new X509Name(subject, new X509BDJEntryConverter()));
    cg.setNotBefore(rootCert.getNotBefore());
    cg.setNotAfter(rootCert.getNotAfter());
    cg.setPublicKey(csr.getPublicKey());
    cg.setSerialNumber(appCertSerNo);

    // BD-J mandates using SHA1WithRSA as a signature Algorithm
    cg.setSignatureAlgorithm("SHA1WITHRSA");
    cg.addExtension(X509Extensions.KeyUsage.getId(), true, new X509KeyUsage(X509KeyUsage.digitalSignature));

    // FIXME: Ideally this should be pulled out from the original app cert's
    // extension. Email on X500Name is not encoded with UTF8String.
    cg.addExtension(X509Extensions.SubjectAlternativeName.getId(), false, getRfc822Name(altName));

    // Assuming that the root certificate was generated using our tool,
    // the certificate should have IssuerAlternativeNames as an extension.
    if (rootCert.getIssuerAlternativeNames() == null) {
        System.out.println("ERROR: the root certificate must have an alternate name");
        System.exit(1);
    }
    List issuerName = (List) rootCert.getIssuerAlternativeNames().iterator().next();
    cg.addExtension(X509Extensions.IssuerAlternativeName.getId(), false,
            getRfc822Name((String) issuerName.get(1)));
    PrivateKey privateKey = (PrivateKey) store.getKey(alias, keypass.toCharArray());
    X509Certificate cert = cg.generate(privateKey);

    // Now, write leaf certificate
    System.out.println("Writing cert to " + certfile + ".");
    FileOutputStream str = new FileOutputStream(certfile);
    str.write(cert.getEncoded());
    str.close();
}

From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java

License:Apache License

/**
 * Builds and signs a certificate. The certificate will be build on the given subject-public-key and signed with
 * the given issuer-private-key. The issuer and subject will be identified in the strings provided.
 *
 * @return A signed X509Certificate//from w  w w.j av  a  2  s  . com
 * @throws Exception
 */
public X509Certificate buildAndSignCert(BigInteger serialNumber, PrivateKey signerPrivateKey,
        PublicKey signerPublicKey, PublicKey subjectPublicKey, X500Name issuer, X500Name subject,
        Map<String, String> customAttrs, String type) throws Exception {
    // Dates are converted to GMT/UTC inside the cert builder 
    Calendar cal = Calendar.getInstance();
    Date now = cal.getTime();
    Date expire = new GregorianCalendar(CERT_EXPIRE_YEAR, 0, 1).getTime();
    X509v3CertificateBuilder certV3Bldr = new JcaX509v3CertificateBuilder(issuer, serialNumber, now, // Valid from now...
            expire, // until CERT_EXPIRE_YEAR
            subject, subjectPublicKey);
    JcaX509ExtensionUtils extensionUtil = new JcaX509ExtensionUtils();
    // Create certificate extensions
    if ("ROOTCA".equals(type)) {
        certV3Bldr = certV3Bldr.addExtension(Extension.basicConstraints, true, new BasicConstraints(true))
                .addExtension(Extension.keyUsage, true,
                        new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation
                                | X509KeyUsage.keyEncipherment | X509KeyUsage.keyCertSign
                                | X509KeyUsage.cRLSign));
    } else if ("INTERMEDIATE".equals(type)) {
        certV3Bldr = certV3Bldr.addExtension(Extension.basicConstraints, true, new BasicConstraints(true))
                .addExtension(Extension.keyUsage, true,
                        new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation
                                | X509KeyUsage.keyEncipherment | X509KeyUsage.keyCertSign
                                | X509KeyUsage.cRLSign));
    } else {
        // Subject Alternative Name
        GeneralName[] genNames = null;
        if (customAttrs != null && !customAttrs.isEmpty()) {
            genNames = new GeneralName[customAttrs.size()];
            Iterator<Map.Entry<String, String>> it = customAttrs.entrySet().iterator();
            int idx = 0;
            while (it.hasNext()) {
                Map.Entry<String, String> pair = it.next();
                //genNames[idx] = new GeneralName(GeneralName.otherName, new DERUTF8String(pair.getKey() + ";" + pair.getValue()));
                DERSequence othernameSequence = new DERSequence(
                        new ASN1Encodable[] { new ASN1ObjectIdentifier(pair.getKey()),
                                new DERTaggedObject(true, 0, new DERUTF8String(pair.getValue())) });
                genNames[idx] = new GeneralName(GeneralName.otherName, othernameSequence);
                idx++;
            }
        }
        if (genNames != null) {
            certV3Bldr = certV3Bldr.addExtension(Extension.subjectAlternativeName, false,
                    new GeneralNames(genNames));
        }
    }
    // Basic extension setup
    certV3Bldr = certV3Bldr
            .addExtension(Extension.authorityKeyIdentifier, false,
                    extensionUtil.createAuthorityKeyIdentifier(signerPublicKey))
            .addExtension(Extension.subjectKeyIdentifier, false,
                    extensionUtil.createSubjectKeyIdentifier(subjectPublicKey));
    // CRL Distribution Points
    DistributionPointName distPointOne = new DistributionPointName(
            new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, CRL_URL)));
    DistributionPoint[] distPoints = new DistributionPoint[1];
    distPoints[0] = new DistributionPoint(distPointOne, null, null);
    certV3Bldr.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(distPoints));
    // OCSP endpoint
    GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, OCSP_URL);
    AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
            X509ObjectIdentifiers.ocspAccessMethod, ocspName);
    certV3Bldr.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    // Create the key signer
    JcaContentSignerBuilder builder = new JcaContentSignerBuilder(SIGNER_ALGORITHM);
    builder.setProvider(BC_PROVIDER_NAME);
    ContentSigner signer = builder.build(signerPrivateKey);
    return new JcaX509CertificateConverter().setProvider(BC_PROVIDER_NAME)
            .getCertificate(certV3Bldr.build(signer));
}

From source file:net.maritimecloud.pki.CertificateBuilder.java

License:Apache License

/**
 * Builds and signs a certificate. The certificate will be build on the given subject-public-key and signed with
 * the given issuer-private-key. The issuer and subject will be identified in the strings provided.
 *
 * @param serialNumber The serialnumber of the new certificate.
 * @param signerPrivateKey Private key for signing the certificate
 * @param signerPublicKey Public key of the signing certificate
 * @param subjectPublicKey Public key for the new certificate
 * @param issuer DN of the signing certificate
 * @param subject DN of the new certificate
 * @param customAttrs The custom MC attributes to include in the certificate
 * @param type Type of certificate, can be "ROOT", "INTERMEDIATE" or "ENTITY".
 * @param ocspUrl OCSP endpoint//ww  w .  j  a v a2  s .c  o m
 * @param crlUrl CRL endpoint - can be null
 * @return A signed X509Certificate
 * @throws Exception Throws exception on certificate generation errors.
 */
public X509Certificate buildAndSignCert(BigInteger serialNumber, PrivateKey signerPrivateKey,
        PublicKey signerPublicKey, PublicKey subjectPublicKey, X500Name issuer, X500Name subject,
        Map<String, String> customAttrs, String type, String ocspUrl, String crlUrl) throws Exception {
    // Dates are converted to GMT/UTC inside the cert builder
    Calendar cal = Calendar.getInstance();
    Date now = cal.getTime();
    Date expire = new GregorianCalendar(CERT_EXPIRE_YEAR, 0, 1).getTime();
    X509v3CertificateBuilder certV3Bldr = new JcaX509v3CertificateBuilder(issuer, serialNumber, now, // Valid from now...
            expire, // until CERT_EXPIRE_YEAR
            subject, subjectPublicKey);
    JcaX509ExtensionUtils extensionUtil = new JcaX509ExtensionUtils();
    // Create certificate extensions
    if ("ROOTCA".equals(type)) {
        certV3Bldr = certV3Bldr.addExtension(Extension.basicConstraints, true, new BasicConstraints(true))
                .addExtension(Extension.keyUsage, true,
                        new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation
                                | X509KeyUsage.keyEncipherment | X509KeyUsage.keyCertSign
                                | X509KeyUsage.cRLSign));
    } else if ("INTERMEDIATE".equals(type)) {
        certV3Bldr = certV3Bldr.addExtension(Extension.basicConstraints, true, new BasicConstraints(true))
                .addExtension(Extension.keyUsage, true,
                        new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation
                                | X509KeyUsage.keyEncipherment | X509KeyUsage.keyCertSign
                                | X509KeyUsage.cRLSign));
    } else {
        // Subject Alternative Name
        GeneralName[] genNames = null;
        if (customAttrs != null && !customAttrs.isEmpty()) {
            genNames = new GeneralName[customAttrs.size()];
            Iterator<Map.Entry<String, String>> it = customAttrs.entrySet().iterator();
            int idx = 0;
            while (it.hasNext()) {
                Map.Entry<String, String> pair = it.next();
                if (PKIConstants.X509_SAN_DNSNAME.equals(pair.getKey())) {
                    genNames[idx] = new GeneralName(GeneralName.dNSName, pair.getValue());
                } else {
                    //genNames[idx] = new GeneralName(GeneralName.otherName, new DERUTF8String(pair.getKey() + ";" + pair.getValue()));
                    DERSequence othernameSequence = new DERSequence(
                            new ASN1Encodable[] { new ASN1ObjectIdentifier(pair.getKey()),
                                    new DERTaggedObject(true, 0, new DERUTF8String(pair.getValue())) });
                    genNames[idx] = new GeneralName(GeneralName.otherName, othernameSequence);
                }
                idx++;
            }
        }
        if (genNames != null) {
            certV3Bldr = certV3Bldr.addExtension(Extension.subjectAlternativeName, false,
                    new GeneralNames(genNames));
        }
    }
    // Basic extension setup
    certV3Bldr = certV3Bldr
            .addExtension(Extension.authorityKeyIdentifier, false,
                    extensionUtil.createAuthorityKeyIdentifier(signerPublicKey))
            .addExtension(Extension.subjectKeyIdentifier, false,
                    extensionUtil.createSubjectKeyIdentifier(subjectPublicKey));
    // CRL Distribution Points
    DistributionPointName distPointOne = new DistributionPointName(
            new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, crlUrl)));
    DistributionPoint[] distPoints = new DistributionPoint[1];
    distPoints[0] = new DistributionPoint(distPointOne, null, null);
    certV3Bldr.addExtension(Extension.cRLDistributionPoints, false, new CRLDistPoint(distPoints));
    // OCSP endpoint - is not available for the CAs
    if (ocspUrl != null) {
        GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, ocspUrl);
        AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
                X509ObjectIdentifiers.ocspAccessMethod, ocspName);
        certV3Bldr.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    }
    // Create the key signer
    JcaContentSignerBuilder builder = new JcaContentSignerBuilder(SIGNER_ALGORITHM);
    builder.setProvider(BC_PROVIDER_NAME);
    ContentSigner signer = builder.build(signerPrivateKey);
    return new JcaX509CertificateConverter().setProvider(BC_PROVIDER_NAME)
            .getCertificate(certV3Bldr.build(signer));
}

From source file:net.solarnetwork.node.setup.test.PKITestUtils.java

License:Open Source License

public static X509Certificate generateNewCACert(PublicKey publicKey, String subject, X509Certificate issuer,
        PrivateKey issuerKey, String caDN) throws Exception {
    final X500Name issuerDn = (issuer == null ? new X500Name(subject) : JcaX500NameUtil.getSubject(issuer));
    final X500Name subjectDn = new X500Name(subject);
    final BigInteger serial = getNextSerialNumber();
    final Date notBefore = new Date();
    final Date notAfter = new Date(System.currentTimeMillis() + 1000L * 60L * 60L);
    JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerDn, serial, notBefore, notAfter,
            subjectDn, publicKey);//from www. j a  v a  2 s. co m

    // add "CA" extension
    BasicConstraints basicConstraints;
    if (issuer == null) {
        basicConstraints = new BasicConstraints(true);
    } else {
        int issuerPathLength = issuer.getBasicConstraints();
        basicConstraints = new BasicConstraints(issuerPathLength - 1);
    }
    builder.addExtension(X509Extension.basicConstraints, true, basicConstraints);

    // add subjectKeyIdentifier
    JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();
    SubjectKeyIdentifier ski = utils.createSubjectKeyIdentifier(publicKey);
    builder.addExtension(X509Extension.subjectKeyIdentifier, false, ski);

    // add authorityKeyIdentifier
    GeneralNames issuerName = new GeneralNames(new GeneralName(GeneralName.directoryName, caDN));
    AuthorityKeyIdentifier aki = utils.createAuthorityKeyIdentifier(publicKey);
    aki = new AuthorityKeyIdentifier(aki.getKeyIdentifier(), issuerName, serial);
    builder.addExtension(X509Extension.authorityKeyIdentifier, false, aki);

    // add keyUsage
    X509KeyUsage keyUsage = new X509KeyUsage(X509KeyUsage.cRLSign | X509KeyUsage.digitalSignature
            | X509KeyUsage.keyCertSign | X509KeyUsage.nonRepudiation);
    builder.addExtension(X509Extension.keyUsage, true, keyUsage);

    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder("SHA256WithRSA");
    ContentSigner signer = signerBuilder.build(issuerKey);

    X509CertificateHolder holder = builder.build(signer);
    JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
    return converter.getCertificate(holder);
}

From source file:org.cesecore.certificates.ca.internal.CertificateValidityTest.java

License:Open Source License

@Test
public void test03TestCheckPrivateKeyUsagePeriod()
        throws InvalidAlgorithmParameterException, InvalidKeyException, NoSuchAlgorithmException,
        SignatureException, IllegalStateException, NoSuchProviderException, OperatorCreationException,
        CertificateException, IOException, CAOfflineException, ParseException {
    final KeyPair pair = KeyTools.genKeys("512", "RSA");
    /// A certificate without private key usage period
    X509Certificate cert = CertTools.genSelfCertForPurpose("CN=CheckPK", 365, null, pair.getPrivate(),
            pair.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true, X509KeyUsage.digitalSignature,
            null, null, "BC");
    // No private key usage period, should pass fine 
    CertificateValidity.checkPrivateKeyUsagePeriod(cert);
    // A certificate with private key usage period notBefore == "now"
    cert = CertTools.genSelfCertForPurpose("CN=CheckPK", 365, null, pair.getPrivate(), pair.getPublic(),
            AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true, X509KeyUsage.digitalSignature, new Date(), null,
            "BC");
    // should pass fine 
    CertificateValidity.checkPrivateKeyUsagePeriod(cert);
    // A certificate with private key usage period notAfter == "now+1h"
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR_OF_DAY, 1);
    cert = CertTools.genSelfCertForPurpose("CN=CheckPK", 365, null, pair.getPrivate(), pair.getPublic(),
            AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true, X509KeyUsage.digitalSignature, null, cal.getTime(),
            "BC");
    // should pass fine 
    CertificateValidity.checkPrivateKeyUsagePeriod(cert);
    // A certificate with private key usage period notBefore == "now" and notAfter == "now+1h"
    cal = Calendar.getInstance();
    cal.add(Calendar.HOUR_OF_DAY, 1);
    cert = CertTools.genSelfCertForPurpose("CN=CheckPK", 365, null, pair.getPrivate(), pair.getPublic(),
            AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true, X509KeyUsage.digitalSignature, new Date(),
            cal.getTime(), "BC");
    // should pass fine 
    CertificateValidity.checkPrivateKeyUsagePeriod(cert);
    // A certificate with private key usage period notBefore == "now+1h"
    cal = Calendar.getInstance();
    cal.add(Calendar.HOUR_OF_DAY, 1);
    cert = CertTools.genSelfCertForPurpose("CN=CheckPK", 365, null, pair.getPrivate(), pair.getPublic(),
            AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true, X509KeyUsage.digitalSignature, cal.getTime(), null,
            "BC");
    try {//  w  ww. j  a v a 2  s.  c om
        CertificateValidity.checkPrivateKeyUsagePeriod(cert);
        fail("A certificate with private key usage period notBefore == now+1h should not be useful.");
    } catch (CAOfflineException e) {
        // NOPMD: should throw
    }
    // A certificate with private key usage period notAfter == "now-1h"
    cal = Calendar.getInstance();
    cal.add(Calendar.HOUR_OF_DAY, -1);
    cert = CertTools.genSelfCertForPurpose("CN=CheckPK", 365, null, pair.getPrivate(), pair.getPublic(),
            AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true, X509KeyUsage.digitalSignature, null, cal.getTime(),
            "BC");
    try {
        CertificateValidity.checkPrivateKeyUsagePeriod(cert);
        fail("A certificate with private key usage period notAfter == now-1h should not be useful.");
    } catch (CAOfflineException e) {
        // NOPMD: should throw
    }
    // A certificate with private key usage period notBefore == "now+1h" and notAfter == "now-1h"
    cal = Calendar.getInstance();
    cal.add(Calendar.HOUR_OF_DAY, -1);
    Calendar cal2 = Calendar.getInstance();
    cal2.add(Calendar.HOUR_OF_DAY, 1);
    cert = CertTools.genSelfCertForPurpose("CN=CheckPK", 365, null, pair.getPrivate(), pair.getPublic(),
            AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true, X509KeyUsage.digitalSignature, cal2.getTime(),
            cal.getTime(), "BC");
    try {
        CertificateValidity.checkPrivateKeyUsagePeriod(cert);
        fail("A certificate with private key usage period notBefore == now+1h and notAfter == now-1h should not be useful.");
    } catch (CAOfflineException e) {
        // NOPMD: should throw
    }
    // A certificate with private key usage period notBefore == "now-1h" and notAfter == "now-1h"
    cal = Calendar.getInstance();
    cal.add(Calendar.HOUR_OF_DAY, -1);
    cal2 = Calendar.getInstance();
    cal2.add(Calendar.HOUR_OF_DAY, -1);
    cert = CertTools.genSelfCertForPurpose("CN=CheckPK", 365, null, pair.getPrivate(), pair.getPublic(),
            AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true, X509KeyUsage.digitalSignature, cal2.getTime(),
            cal.getTime(), "BC");
    try {
        CertificateValidity.checkPrivateKeyUsagePeriod(cert);
        fail("A certificate with private key usage period notBefore == now-1h and notAfter == now-1h should not be useful.");
    } catch (CAOfflineException e) {
        // NOPMD: should throw
    }
    // A certificate with private key usage period notBefore == "now+1h" and notAfter == "now+1h"
    cal = Calendar.getInstance();
    cal.add(Calendar.HOUR_OF_DAY, 1);
    cal2 = Calendar.getInstance();
    cal2.add(Calendar.HOUR_OF_DAY, 1);
    cert = CertTools.genSelfCertForPurpose("CN=CheckPK", 365, null, pair.getPrivate(), pair.getPublic(),
            AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true, X509KeyUsage.digitalSignature, cal2.getTime(),
            cal.getTime(), "BC");
    try {
        CertificateValidity.checkPrivateKeyUsagePeriod(cert);
        fail("A certificate with private key usage period notBefore == now+1h and notAfter == now+1h should not be useful.");
    } catch (CAOfflineException e) {
        // NOPMD: should throw
    }
    // A certificate with private key usage period notBefore == "now-1h" and notAfter == "now+1h"
    cal = Calendar.getInstance();
    cal.add(Calendar.HOUR_OF_DAY, 1);
    cal2 = Calendar.getInstance();
    cal2.add(Calendar.HOUR_OF_DAY, -1);
    cert = CertTools.genSelfCertForPurpose("CN=CheckPK", 365, null, pair.getPrivate(), pair.getPublic(),
            AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true, X509KeyUsage.digitalSignature, cal2.getTime(),
            cal.getTime(), "BC");
    // Should work
    CertificateValidity.checkPrivateKeyUsagePeriod(cert);
}