Example usage for org.bouncycastle.jce X509KeyUsage nonRepudiation

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

Introduction

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

Prototype

int nonRepudiation

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

Click Source Link

Usage

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  v  a2 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 ww  .java2  s  .co  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 a2s  . 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.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 .jav 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.keybind.impl.OcspKeyBindingTest.java

License:Open Source License

@Test
public void testOcspSigningCertificateValidationPositives() throws IOException,
        InvalidAlgorithmParameterException, InvalidKeyException, NoSuchAlgorithmException, SignatureException,
        IllegalStateException, NoSuchProviderException, OperatorCreationException, CertificateException {
    assertTrue(/*from w  w w .  j ava2s  .co  m*/
            "KU=digitalSignature and EKU=id_kp_OCSPSigning should be treated as a valid OCSP singing certificate.",
            OcspKeyBinding
                    .isOcspSigningCertificate(getCertificate(X509KeyUsage.digitalSignature, ekuExtensionOnly)));
    assertTrue(
            "KU=digitalSignature and EKU=id_kp_OCSPSigning should be treated as a valid OCSP singing certificate.",
            OcspKeyBinding.isOcspSigningCertificate(
                    getCertificate(X509KeyUsage.digitalSignature + X509KeyUsage.cRLSign, ekuExtensionOnly)));
    assertTrue(
            "KU=nonRepudiation and EKU=id_kp_OCSPSigning should be treated as a valid OCSP singing certificate.",
            OcspKeyBinding.isOcspSigningCertificate(
                    getCertificate(X509KeyUsage.nonRepudiation + X509KeyUsage.cRLSign, ekuExtensionOnly)));
    assertTrue(
            "KU=digitalSignature+nonRepudiation and EKU=id_kp_OCSPSigning should be treated as a valid OCSP singing certificate.",
            OcspKeyBinding.isOcspSigningCertificate(getCertificate(
                    X509KeyUsage.digitalSignature + X509KeyUsage.nonRepudiation, ekuExtensionOnly)));
}

From source file:org.cesecore.keybind.impl.OcspKeyBindingTest.java

License:Open Source License

@Test
public void testOcspSigningCertificateValidationNegatives() throws IOException,
        InvalidAlgorithmParameterException, InvalidKeyException, NoSuchAlgorithmException, SignatureException,
        IllegalStateException, NoSuchProviderException, OperatorCreationException, CertificateException {
    assertFalse(//from w ww . j  a va 2s.c o m
            "KU!=digitalSignature|nonRepudiation and EKU=id_kp_OCSPSigning should be treated as an invalid OCSP singing certificate.",
            OcspKeyBinding.isOcspSigningCertificate(
                    getCertificate(X509KeyUsage.keyAgreement + X509KeyUsage.cRLSign, ekuExtensionOnly)));
    assertFalse(
            "KU=digitalSignature and EKU!=id_kp_OCSPSigning should be treated as an invalid OCSP singing certificate.",
            OcspKeyBinding.isOcspSigningCertificate(getCertificate(X509KeyUsage.digitalSignature, null)));
    assertFalse(
            "KU=nonRepudiation and EKU!=id_kp_OCSPSigning should be treated as an invalid OCSP singing certificate.",
            OcspKeyBinding.isOcspSigningCertificate(getCertificate(X509KeyUsage.nonRepudiation, null)));
}

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 .  j  a va  2 s .c om*/
 * @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.ejbca.core.protocol.cmp.CrmfRequestMessageTest.java

License:Open Source License

private PKIMessage createPKIMessage(final String issuerDN, final String subjectDN)
        throws InvalidAlgorithmParameterException, IOException {
    KeyPair keys = KeyTools.genKeys("1024", "RSA");
    ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(
            new DERGeneralizedTime("20030211002120Z"));
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date());
    optionalValidityV.add(new DERTaggedObject(true, 0, nb));
    optionalValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV));

    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setValidity(myOptionalValidity);
    myCertTemplate.setIssuer(new X500Name(issuerDN));
    myCertTemplate.setSubject(new X500Name(subjectDN));
    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    try {/*from  w w w .j  a  v a  2  s.c  o  m*/
        SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
        myCertTemplate.setPublicKey(keyInfo);
    } finally {
        dIn.close();
    }
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    ExtensionsGenerator extgen = new ExtensionsGenerator();
    int bcku = X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment | X509KeyUsage.nonRepudiation;
    X509KeyUsage ku = new X509KeyUsage(bcku);
    bOut = new ByteArrayOutputStream();
    dOut = new DEROutputStream(bOut);
    dOut.writeObject(ku);
    byte[] value = bOut.toByteArray();
    extgen.addExtension(Extension.keyUsage, false, new DEROctetString(value));
    myCertTemplate.setExtensions(extgen.generate());

    CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null);

    ProofOfPossession myProofOfPossession = new ProofOfPossession();
    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String("foo123"));
    AttributeTypeAndValue[] avs = { av };
    CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs);
    CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(new X500Name("CN=bogusSubject")),
            new GeneralName(new X500Name("CN=bogusIssuer")));
    myPKIHeader.setMessageTime(new DERGeneralizedTime(new Date()));
    myPKIHeader.setSenderNonce(new DEROctetString(CmpMessageHelper.createSenderNonce()));
    myPKIHeader.setTransactionID(new DEROctetString(CmpMessageHelper.createSenderNonce()));

    PKIBody myPKIBody = new PKIBody(0, myCertReqMessages);
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    return myPKIMessage;
}

From source file:org.ejbca.core.protocol.cmp.NestedMessageContentTest.java

License:Open Source License

@Test
public void test06NotNestedMessage()
        throws ObjectNotFoundException, InvalidKeyException, SignatureException, AuthorizationDeniedException,
        EjbcaException, UserDoesntFullfillEndEntityProfile, WaitingForApprovalException, Exception {

    ASN1EncodableVector optionaValidityV = new ASN1EncodableVector();
    org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(
            new DERGeneralizedTime("20030211002120Z"));
    org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date());
    optionaValidityV.add(new DERTaggedObject(true, 0, nb));
    optionaValidityV.add(new DERTaggedObject(true, 1, na));
    OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionaValidityV));

    KeyPair keys = KeyTools.genKeys("1024", "RSA");
    CertTemplateBuilder myCertTemplate = new CertTemplateBuilder();
    myCertTemplate.setValidity(myOptionalValidity);
    myCertTemplate.setIssuer(new X500Name(this.issuerDN));
    myCertTemplate.setSubject(SUBJECT_DN);
    byte[] bytes = keys.getPublic().getEncoded();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
    ASN1InputStream dIn = new ASN1InputStream(bIn);
    try {/*from   ww  w .  j  a v  a  2s.co  m*/
        SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject());
        myCertTemplate.setPublicKey(keyInfo);
        // If we did not pass any extensions as parameter, we will create some of our own, standard ones
    } finally {
        dIn.close();
    }
    final Extensions exts;
    {
        // SubjectAltName
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        ExtensionsGenerator extgen = new ExtensionsGenerator();
        // KeyUsage
        int bcku = 0;
        bcku = X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment | X509KeyUsage.nonRepudiation;
        X509KeyUsage ku = new X509KeyUsage(bcku);
        bOut = new ByteArrayOutputStream();
        dOut = new DEROutputStream(bOut);
        dOut.writeObject(ku);
        byte[] value = bOut.toByteArray();
        extgen.addExtension(Extension.keyUsage, false, new DEROctetString(value));

        // Make the complete extension package
        exts = extgen.generate();
    }
    myCertTemplate.setExtensions(exts);
    CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null);
    ProofOfPossession myProofOfPossession = new ProofOfPossession();
    AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken,
            new DERUTF8String("foo123"));
    AttributeTypeAndValue[] avs = { av };
    CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs);

    CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg);

    PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(SUBJECT_DN),
            new GeneralName(new X500Name(((X509Certificate) this.cacert).getSubjectDN().getName())));
    final byte[] nonce = CmpMessageHelper.createSenderNonce();
    final byte[] transid = CmpMessageHelper.createSenderNonce();
    myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date()));
    // senderNonce
    myPKIHeader.setSenderNonce(new DEROctetString(nonce));
    // TransactionId
    myPKIHeader.setTransactionID(new DEROctetString(transid));
    PKIBody myPKIBody = new PKIBody(20, myCertReqMessages); // nestedMessageContent
    PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody);
    KeyPair raKeys = KeyTools.genKeys("1024", "RSA");
    createRACertificate("raSignerTest06", "foo123", this.raCertsPath, cmpAlias, raKeys, null, null,
            CMPTESTPROFILE, this.caid);
    myPKIMessage = CmpMessageHelper.buildCertBasedPKIProtection(myPKIMessage, null, raKeys.getPrivate(), null,
            "BC");

    assertNotNull("Failed to create PKIHeader", myPKIHeader);
    assertNotNull("Failed to create PKIBody", myPKIBody);
    assertNotNull("Failed to create PKIMessage", myPKIMessage);

    final ByteArrayOutputStream bao = new ByteArrayOutputStream();
    final DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(myPKIMessage);
    final byte[] ba = bao.toByteArray();
    // Send request and receive response
    final byte[] resp = sendCmpHttp(ba, 200, cmpAlias);

    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    PKIBody body = respObject.getBody();
    assertEquals(23, body.getType());
    ErrorMsgContent err = (ErrorMsgContent) body.getContent();
    String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
    assertEquals("unknown object in getInstance: org.bouncycastle.asn1.DERSequence", errMsg);
}

From source file:org.signserver.validationservice.server.CRLValidatorTest.java

License:Open Source License

@Test
public void test00SetupDatabase() throws Exception {
    // Setup keys, certificates and CRLs: RootCA1
    File cdpFile1 = new File(signServerHome, "tmp" + File.separator + "rootca1.crl");
    URL cdpUrl1 = cdpFile1.toURI().toURL();
    CRLDistPoint crlDistPointCA1WithUrl = ValidationTestUtils.generateDistPointWithUrl(cdpUrl1);
    ArrayList<X509Certificate> chain1 = new ArrayList<X509Certificate>();

    KeyPair keysRootCA1 = KeyTools.genKeys("1024", "RSA");
    certRootCA1 = ValidationTestUtils.genCert("CN=RootCA1", "CN=RootCA1", keysRootCA1.getPrivate(),
            keysRootCA1.getPublic(), new Date(0), new Date(System.currentTimeMillis() + 1000000), true);

    KeyPair keysEndEntity1 = KeyTools.genKeys("1024", "RSA");
    certEndEntity1 = ValidationTestUtils.genCert("CN=EndEntity1", "CN=RootCA1", keysRootCA1.getPrivate(),
            keysEndEntity1.getPublic(), new Date(0), new Date(System.currentTimeMillis() + 1000000), false, 0,
            crlDistPointCA1WithUrl);// w  ww  .j a  va 2s .c o  m

    KeyPair keysEndEntity2 = KeyTools.genKeys("1024", "RSA");
    certEndEntity2 = ValidationTestUtils.genCert("CN=EndEntity2", "CN=RootCA1", keysRootCA1.getPrivate(),
            keysEndEntity2.getPublic(), new Date(0), new Date(System.currentTimeMillis() + 1000000), false, 0,
            crlDistPointCA1WithUrl);

    KeyPair keysEndEntity5 = KeyTools.genKeys("1024", "RSA");
    certEndEntity5Expired = ValidationTestUtils.genCert("CN=EndEntity5", "CN=RootCA1", keysRootCA1.getPrivate(),
            keysEndEntity5.getPublic(), new Date(0), new Date(System.currentTimeMillis() - 2000000), false, 0,
            crlDistPointCA1WithUrl);

    KeyPair keysEndEntity6 = KeyTools.genKeys("1024", "RSA");
    certEndEntity6NotYetValid = ValidationTestUtils.genCert("CN=EndEntity6", "CN=RootCA1",
            keysRootCA1.getPrivate(), keysEndEntity6.getPublic(),
            new Date(System.currentTimeMillis() + 1000000), new Date(System.currentTimeMillis() + 3000000),
            false, 0, crlDistPointCA1WithUrl);

    KeyPair keysEndEntity7 = KeyTools.genKeys("1024", "RSA");
    PrivateKey notKeyOfRootCA1 = keysEndEntity1.getPrivate();
    certEndEntity7WrongIssuer = ValidationTestUtils.genCert("CN=EndEntity7", "CN=RootCA1", notKeyOfRootCA1,
            keysEndEntity7.getPublic(), new Date(0), new Date(System.currentTimeMillis() + 1000000), false, 0,
            crlDistPointCA1WithUrl);

    KeyPair keysEndEntity8 = KeyTools.genKeys("1024", "RSA");
    certEndEntity8KeyUsageSig = ValidationTestUtils.genCert("CN=EndEntity8", "CN=RootCA1",
            keysRootCA1.getPrivate(), keysEndEntity8.getPublic(), new Date(0),
            new Date(System.currentTimeMillis() + 1000000), false,
            X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation, crlDistPointCA1WithUrl);

    ArrayList<RevokedCertInfo> revoked = new ArrayList<RevokedCertInfo>();
    revoked.add(new RevokedCertInfo("fingerprint", certEndEntity2.getSerialNumber(), new Date(),
            RevokedCertInfo.REVOKATION_REASON_UNSPECIFIED, new Date(System.currentTimeMillis() + 1000000)));

    crlRootCA1 = ValidationTestUtils.genCRL(certRootCA1, keysRootCA1.getPrivate(),
            crlDistPointCA1WithUrl.getDistributionPoints()[0], revoked, 24, 1);

    // Write CRL to file
    OutputStream out = null;
    try {
        out = new FileOutputStream(cdpFile1);
        out.write(crlRootCA1.getEncoded());
    } finally {
        if (out != null) {
            out.close();
        }
    }
    assertTrue(cdpFile1.exists());
    assertTrue(cdpFile1.canRead());
    chain1.add(certRootCA1);

    // Setup keys, certificates and CRLs: RootCA2
    File cdpFile2 = new File(signServerHome, "tmp" + File.separator + "rootca2.crl");
    URL cdpUrl2 = cdpFile2.toURI().toURL();
    CRLDistPoint crlDistPointCA2WithIssuer = ValidationTestUtils.generateDistPointWithIssuer("CN=RootCA2");
    ArrayList<X509Certificate> chain2 = new ArrayList<X509Certificate>();

    KeyPair keysRootCA2 = KeyTools.genKeys("1024", "RSA");
    certRootCA2 = ValidationTestUtils.genCert("CN=RootCA2", "CN=RootCA2", keysRootCA2.getPrivate(),
            keysRootCA2.getPublic(), new Date(0), new Date(System.currentTimeMillis() + 1000000), true);

    KeyPair keysEndEntity3 = KeyTools.genKeys("1024", "RSA");
    certEndEntity3 = ValidationTestUtils.genCert("CN=EndEntity3", "CN=RootCA2", keysRootCA2.getPrivate(),
            keysEndEntity3.getPublic(), new Date(0), new Date(System.currentTimeMillis() + 1000000), false, 0,
            crlDistPointCA2WithIssuer);

    KeyPair keysEndEntity4 = KeyTools.genKeys("1024", "RSA");
    certEndEntity4 = ValidationTestUtils.genCert("CN=EndEntity4", "CN=RootCA2", keysRootCA2.getPrivate(),
            keysEndEntity4.getPublic(), new Date(0), new Date(System.currentTimeMillis() + 1000000), false, 0,
            crlDistPointCA2WithIssuer);

    ArrayList<RevokedCertInfo> revoked2 = new ArrayList<RevokedCertInfo>();
    revoked2.add(new RevokedCertInfo("fingerprint2", certEndEntity4.getSerialNumber(), new Date(),
            RevokedCertInfo.REVOKATION_REASON_UNSPECIFIED, new Date(System.currentTimeMillis() + 1000000)));

    crlRootCA2 = ValidationTestUtils.genCRL(certRootCA2, keysRootCA2.getPrivate(),
            crlDistPointCA2WithIssuer.getDistributionPoints()[0], revoked2, 24, 1);

    // Write CRL to file
    OutputStream out2 = null;
    try {
        out2 = new FileOutputStream(cdpFile2);
        out2.write(crlRootCA2.getEncoded());
    } finally {
        if (out2 != null) {
            out2.close();
        }
    }
    assertTrue(cdpFile2.exists());
    assertTrue(cdpFile2.canRead());
    chain2.add(certRootCA2);

    // Setup worker
    gCSession.setProperty(GlobalConfiguration.SCOPE_GLOBAL, "WORKER15.CLASSPATH",
            "org.signserver.validationservice.server.ValidationServiceWorker");
    gCSession.setProperty(GlobalConfiguration.SCOPE_GLOBAL, "WORKER15.SIGNERTOKEN.CLASSPATH",
            "org.signserver.server.cryptotokens.HardCodedCryptoToken");
    sSSession.setWorkerProperty(15, "AUTHTYPE", "NOAUTH");
    sSSession.setWorkerProperty(15, "VAL1.CLASSPATH", "org.signserver.validationservice.server.CRLValidator");
    sSSession.setWorkerProperty(15, "VAL1.ISSUER1.CERTCHAIN",
            ValidationTestUtils.genPEMStringFromChain(chain1));
    sSSession.setWorkerProperty(15, "VAL1.ISSUER2.CERTCHAIN",
            ValidationTestUtils.genPEMStringFromChain(chain2));
    sSSession.setWorkerProperty(15, "VAL1.ISSUER2.CRLPATHS", cdpUrl2.toExternalForm());
    sSSession.reloadConfiguration(15);
}