Example usage for org.bouncycastle.jce X509KeyUsage keyEncipherment

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

Introduction

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

Prototype

int keyEncipherment

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

Click Source Link

Usage

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);//from w w w.  j  a  v  a2s .  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());//from  w  w  w  .j a  v a2  s.  com
    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)/*from   ww  w  .j av a  2  s.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.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  a  va  2 s  .  co  m
 * @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/*from w  w  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:org.cesecore.certificates.ca.X509CATest.java

License:Open Source License

@SuppressWarnings("unchecked")
private void doTestX509CABasicOperations(String algName) throws Exception {
    final CryptoToken cryptoToken = getNewCryptoToken();
    final X509CA x509ca = createTestCA(cryptoToken, CADN);
    Certificate cacert = x509ca.getCACertificate();

    // Start by creating a PKCS7
    byte[] p7 = x509ca.createPKCS7(cryptoToken, cacert, true);
    assertNotNull(p7);//from  w  ww  .  j  av  a 2 s .c  o m
    CMSSignedData s = new CMSSignedData(p7);
    Store certstore = s.getCertificates();
    Collection<X509CertificateHolder> certs = certstore.getMatches(null);
    assertEquals(2, certs.size());
    p7 = x509ca.createPKCS7(cryptoToken, cacert, false);
    assertNotNull(p7);
    s = new CMSSignedData(p7);
    certstore = s.getCertificates();
    certs = certstore.getMatches(null);
    assertEquals(1, certs.size());

    // Create a certificate request (will be pkcs10)
    byte[] req = x509ca.createRequest(cryptoToken, null, algName, cacert,
            CATokenConstants.CAKEYPURPOSE_CERTSIGN);
    PKCS10CertificationRequest p10 = new PKCS10CertificationRequest(req);
    assertNotNull(p10);
    String dn = p10.getSubject().toString();
    assertEquals(CADN, dn);

    // Make a request with some pkcs11 attributes as well
    Collection<ASN1Encodable> attributes = new ArrayList<ASN1Encodable>();
    // Add a subject alternative name
    ASN1EncodableVector altnameattr = new ASN1EncodableVector();
    altnameattr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    GeneralNames san = CertTools.getGeneralNamesFromAltName("dNSName=foobar.bar.com");
    ExtensionsGenerator extgen = new ExtensionsGenerator();
    extgen.addExtension(Extension.subjectAlternativeName, false, san);
    Extensions exts = extgen.generate();
    altnameattr.add(new DERSet(exts));
    // Add a challenge password as well
    ASN1EncodableVector pwdattr = new ASN1EncodableVector();
    pwdattr.add(PKCSObjectIdentifiers.pkcs_9_at_challengePassword);
    ASN1EncodableVector pwdvalues = new ASN1EncodableVector();
    pwdvalues.add(new DERUTF8String("foobar123"));
    pwdattr.add(new DERSet(pwdvalues));
    attributes.add(new DERSequence(altnameattr));
    attributes.add(new DERSequence(pwdattr));
    // create the p10
    req = x509ca.createRequest(cryptoToken, attributes, algName, cacert,
            CATokenConstants.CAKEYPURPOSE_CERTSIGN);
    p10 = new PKCS10CertificationRequest(req);
    assertNotNull(p10);
    dn = p10.getSubject().toString();
    assertEquals(CADN, dn);
    Attribute[] attrs = p10.getAttributes();
    assertEquals(2, attrs.length);
    PKCS10RequestMessage p10msg = new PKCS10RequestMessage(new JcaPKCS10CertificationRequest(p10));
    assertEquals("foobar123", p10msg.getPassword());
    assertEquals("dNSName=foobar.bar.com", p10msg.getRequestAltNames());

    try {
        x509ca.createAuthCertSignRequest(cryptoToken, p10.getEncoded());
    } catch (UnsupportedOperationException e) {
        // Expected for a X509 CA
    }

    // Generate a client certificate and check that it was generated correctly
    EndEntityInformation user = new EndEntityInformation("username", "CN=User", 666, "rfc822Name=user@user.com",
            "user@user.com", new EndEntityType(EndEntityTypes.ENDUSER), 0, 0, EndEntityConstants.TOKEN_USERGEN,
            0, null);
    KeyPair keypair = genTestKeyPair(algName);
    CertificateProfile cp = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    cp.addCertificatePolicy(new CertificatePolicy("1.1.1.2", null, null));
    cp.setUseCertificatePolicies(true);
    Certificate usercert = x509ca.generateCertificate(cryptoToken, user, keypair.getPublic(), 0, null, 10L, cp,
            "00000");
    assertNotNull(usercert);
    assertEquals("CN=User", CertTools.getSubjectDN(usercert));
    assertEquals(CADN, CertTools.getIssuerDN(usercert));
    assertEquals(getTestKeyPairAlgName(algName).toUpperCase(),
            AlgorithmTools.getCertSignatureAlgorithmNameAsString(usercert).toUpperCase());
    assertEquals(new String(CertTools.getSubjectKeyId(cacert)),
            new String(CertTools.getAuthorityKeyId(usercert)));
    assertEquals("user@user.com", CertTools.getEMailAddress(usercert));
    assertEquals("rfc822name=user@user.com", CertTools.getSubjectAlternativeName(usercert));
    assertNull(CertTools.getUPNAltName(usercert));
    assertFalse(CertTools.isSelfSigned(usercert));
    usercert.verify(cryptoToken
            .getPublicKey(x509ca.getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)));
    usercert.verify(x509ca.getCACertificate().getPublicKey());
    assertTrue(CertTools.isCA(x509ca.getCACertificate()));
    assertFalse(CertTools.isCA(usercert));
    assertEquals("1.1.1.2", CertTools.getCertificatePolicyId(usercert, 0));
    X509Certificate cert = (X509Certificate) usercert;
    boolean[] ku = cert.getKeyUsage();
    assertTrue(ku[0]);
    assertTrue(ku[1]);
    assertTrue(ku[2]);
    assertFalse(ku[3]);
    assertFalse(ku[4]);
    assertFalse(ku[5]);
    assertFalse(ku[6]);
    assertFalse(ku[7]);
    int bcku = CertTools.sunKeyUsageToBC(ku);
    assertEquals(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation | X509KeyUsage.keyEncipherment,
            bcku);

    // Create a CRL
    Collection<RevokedCertInfo> revcerts = new ArrayList<RevokedCertInfo>();
    X509CRLHolder crl = x509ca.generateCRL(cryptoToken, revcerts, 1);
    assertNotNull(crl);
    X509CRL xcrl = CertTools.getCRLfromByteArray(crl.getEncoded());
    assertEquals(CADN, CertTools.getIssuerDN(xcrl));
    Set<?> set = xcrl.getRevokedCertificates();
    assertNull(set);
    BigInteger num = CrlExtensions.getCrlNumber(xcrl);
    assertEquals(1, num.intValue());
    BigInteger deltanum = CrlExtensions.getDeltaCRLIndicator(xcrl);
    assertEquals(-1, deltanum.intValue());
    // Revoke some cert
    Date revDate = new Date();
    revcerts.add(new RevokedCertInfo(CertTools.getFingerprintAsString(usercert).getBytes(),
            CertTools.getSerialNumber(usercert).toByteArray(), revDate.getTime(),
            RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD, CertTools.getNotAfter(usercert).getTime()));
    crl = x509ca.generateCRL(cryptoToken, revcerts, 2);
    assertNotNull(crl);
    xcrl = CertTools.getCRLfromByteArray(crl.getEncoded());
    set = xcrl.getRevokedCertificates();
    assertEquals(1, set.size());
    num = CrlExtensions.getCrlNumber(xcrl);
    assertEquals(2, num.intValue());
    X509CRLEntry entry = (X509CRLEntry) set.iterator().next();
    assertEquals(CertTools.getSerialNumber(usercert).toString(), entry.getSerialNumber().toString());
    assertEquals(revDate.toString(), entry.getRevocationDate().toString());
    // Getting the revocation reason is a pita...
    byte[] extval = entry.getExtensionValue(Extension.reasonCode.getId());
    ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(extval));
    ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    ASN1Primitive obj = aIn.readObject();
    CRLReason reason = CRLReason.getInstance((ASN1Enumerated) obj);
    assertEquals("CRLReason: certificateHold", reason.toString());
    //DEROctetString ostr = (DEROctetString)obj;

    // Create a delta CRL
    revcerts = new ArrayList<RevokedCertInfo>();
    crl = x509ca.generateDeltaCRL(cryptoToken, revcerts, 3, 2);
    assertNotNull(crl);
    xcrl = CertTools.getCRLfromByteArray(crl.getEncoded());
    assertEquals(CADN, CertTools.getIssuerDN(xcrl));
    set = xcrl.getRevokedCertificates();
    assertNull(set);
    num = CrlExtensions.getCrlNumber(xcrl);
    assertEquals(3, num.intValue());
    deltanum = CrlExtensions.getDeltaCRLIndicator(xcrl);
    assertEquals(2, deltanum.intValue());
    revcerts.add(new RevokedCertInfo(CertTools.getFingerprintAsString(usercert).getBytes(),
            CertTools.getSerialNumber(usercert).toByteArray(), revDate.getTime(),
            RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD, CertTools.getNotAfter(usercert).getTime()));
    crl = x509ca.generateDeltaCRL(cryptoToken, revcerts, 4, 3);
    assertNotNull(crl);
    xcrl = CertTools.getCRLfromByteArray(crl.getEncoded());
    deltanum = CrlExtensions.getDeltaCRLIndicator(xcrl);
    assertEquals(3, deltanum.intValue());
    set = xcrl.getRevokedCertificates();
    assertEquals(1, set.size());
    entry = (X509CRLEntry) set.iterator().next();
    assertEquals(CertTools.getSerialNumber(usercert).toString(), entry.getSerialNumber().toString());
    assertEquals(revDate.toString(), entry.getRevocationDate().toString());
    // Getting the revocation reason is a pita...
    extval = entry.getExtensionValue(Extension.reasonCode.getId());
    aIn = new ASN1InputStream(new ByteArrayInputStream(extval));
    octs = (ASN1OctetString) aIn.readObject();
    aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
    obj = aIn.readObject();
    reason = CRLReason.getInstance((ASN1Enumerated) obj);
    assertEquals("CRLReason: certificateHold", reason.toString());
}

From source file:org.cesecore.certificates.crl.CrlCreateSessionCRLTest.java

License:Open Source License

private X509Certificate createCertWithValidity(int validity) throws Exception {
    // Make user that we know...
    EndEntityInformation user = new EndEntityInformation(USERNAME, "C=SE,O=AnaTom,CN=crltest",
            testx509ca.getCAId(), null, "crltest@anatom.se", EndEntityConstants.USER_ENDUSER, 0,
            CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, EndEntityConstants.TOKEN_USERGEN, 0, null);
    // user that we know exists...
    CertificateProfile cp = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    int keyusage = X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment;
    X509Certificate cert = (X509Certificate) testx509ca.generateCertificate(user, keys.getPublic(), keyusage,
            validity, cp, "00001");

    certificateStoreSession.storeCertificate(roleMgmgToken, cert, USERNAME, "1234",
            CertificateConstants.CERT_ACTIVE, CertificateConstants.CERTTYPE_ENDENTITY,
            CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, "footag", System.currentTimeMillis());
    assertNotNull("Failed to create certificate", cert);
    return cert;// ww  w  . j a v  a  2s  .c om
}

From source file:org.cesecore.certificates.crl.CrlCreateSessionDeltaCRLTest.java

License:Open Source License

private X509Certificate createCert() throws Exception {
    // Make user that we know...
    EndEntityInformation user = new EndEntityInformation(USERNAME, "C=SE,O=AnaTom,CN=deltacrltest",
            testx509ca.getCAId(), null, "deltacrltest@anatom.se", EndEntityConstants.USER_ENDUSER, 0,
            CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, EndEntityConstants.TOKEN_USERGEN, 0, null);
    // user that we know exists...
    CertificateProfile cp = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
    int keyusage = X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment;
    X509Certificate cert = (X509Certificate) testx509ca.generateCertificate(user, keys.getPublic(), keyusage,
            10, cp, "00001");

    certificateStoreSession.storeCertificate(roleMgmgToken, cert, USERNAME, "1234",
            CertificateConstants.CERT_ACTIVE, CertificateConstants.CERTTYPE_ENDENTITY,
            CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER, "footag", System.currentTimeMillis());
    assertNotNull("Failed to create certificate", cert);
    return cert;/*from   w  ww.j av a  2 s .  co  m*/
}

From source file:org.cesecore.util.CertTools.java

License:Open Source License

/**
 * Converts Sun Key usage bits to Bouncy castle key usage kits
 * // w  w w.  jav a2 s  . co m
 * @param sku key usage bit fields according to java.security.cert.X509Certificate#getKeyUsage, must be a boolean aray of size 9.
 * @return key usage int according to org.bouncycastle.jce.X509KeyUsage#X509KeyUsage, or -1 if input is null.
 * @see java.security.cert.X509Certificate#getKeyUsage
 * @see org.bouncycastle.jce.X509KeyUsage#X509KeyUsage
 */
public static int sunKeyUsageToBC(boolean[] sku) {
    if (sku == null) {
        return -1;
    }
    int bcku = 0;
    if (sku[0]) {
        bcku = bcku | X509KeyUsage.digitalSignature;
    }
    if (sku[1]) {
        bcku = bcku | X509KeyUsage.nonRepudiation;
    }
    if (sku[2]) {
        bcku = bcku | X509KeyUsage.keyEncipherment;
    }
    if (sku[3]) {
        bcku = bcku | X509KeyUsage.dataEncipherment;
    }
    if (sku[4]) {
        bcku = bcku | X509KeyUsage.keyAgreement;
    }
    if (sku[5]) {
        bcku = bcku | X509KeyUsage.keyCertSign;
    }
    if (sku[6]) {
        bcku = bcku | X509KeyUsage.cRLSign;
    }
    if (sku[7]) {
        bcku = bcku | X509KeyUsage.encipherOnly;
    }
    if (sku[8]) {
        bcku = bcku | X509KeyUsage.decipherOnly;
    }
    return bcku;
}

From source file:org.cesecore.util.provider.EkuPKIXCertPathCheckerTest.java

License:Open Source License

/** @return true if the extendedKeyUsage was accepted */
private boolean validateCert(KeyPair keyPair, boolean isCa, List<String> actualOids, List<String> requiredOids)
        throws Exception {
    final long now = System.currentTimeMillis();
    final List<Extension> additionalExtensions = new ArrayList<Extension>();
    if (actualOids != null) {
        List<KeyPurposeId> actual = new ArrayList<KeyPurposeId>();
        for (final String oid : actualOids) {
            actual.add(KeyPurposeId.getInstance(new ASN1ObjectIdentifier(oid)));
        }/*from   w w  w  . j  a  v  a 2s .c o  m*/
        final ExtendedKeyUsage extendedKeyUsage = new ExtendedKeyUsage(actual.toArray(new KeyPurposeId[0]));
        final ASN1Sequence seq = ASN1Sequence.getInstance(extendedKeyUsage.toASN1Primitive());
        final Extension extension = new Extension(Extension.extendedKeyUsage, true, seq.getEncoded());
        additionalExtensions.add(extension);
    }
    final int ku;
    if (isCa) {
        ku = X509KeyUsage.cRLSign | X509KeyUsage.keyCertSign;
    } else {
        ku = X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment;
    }
    final X509Certificate cert = CertTools.genSelfCertForPurpose("CN=dummy", new Date(now - 3600000L),
            new Date(now + 3600000L), null, keyPair.getPrivate(), keyPair.getPublic(),
            AlgorithmConstants.SIGALG_SHA1_WITH_RSA, isCa, ku, null, null, BouncyCastleProvider.PROVIDER_NAME,
            true, additionalExtensions);
    final PKIXCertPathChecker pkixCertPathChecker = new EkuPKIXCertPathChecker(requiredOids);
    final Collection<String> unresolvedCritExts = new ArrayList<String>(
            Arrays.asList(new String[] { Extension.extendedKeyUsage.getId() }));
    pkixCertPathChecker.check(cert, unresolvedCritExts);
    return !unresolvedCritExts.contains(Extension.extendedKeyUsage.getId());
}