Example usage for org.bouncycastle.cert.jcajce JcaX509CertificateConverter JcaX509CertificateConverter

List of usage examples for org.bouncycastle.cert.jcajce JcaX509CertificateConverter JcaX509CertificateConverter

Introduction

In this page you can find the example usage for org.bouncycastle.cert.jcajce JcaX509CertificateConverter JcaX509CertificateConverter.

Prototype

public JcaX509CertificateConverter() 

Source Link

Document

Base constructor, configure with the default provider.

Usage

From source file:org.computerist.ssltools.zap.ZapSslCertificateUtils.java

License:Apache License

/**
 * Creates a new Root CA certificate and returns private and public key as
 * {@link KeyStore}. The {@link KeyStore#getDefaultType()} is used.
 *
 * @return/*www.  j a  va  2  s  .  c  o  m*/
 * @throws NoSuchAlgorithmException If no providers are found
 * for 'RSA' key pair generator
 * or 'SHA1PRNG' Secure random number generator
 * @throws IllegalStateException in case of errors during assembling {@link KeyStore}
 */
public static final KeyStore createRootCA() throws NoSuchAlgorithmException {
    final Date startDate = Calendar.getInstance().getTime();
    final Date expireDate = new Date(startDate.getTime() + (DEFAULT_VALID_DAYS * 24L * 60L * 60L * 1000L));

    final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA");
    g.initialize(2048, SecureRandom.getInstance("SHA1PRNG"));
    final KeyPair keypair = g.genKeyPair();
    final PrivateKey privKey = keypair.getPrivate();
    final PublicKey pubKey = keypair.getPublic();
    Random rnd = new Random();

    // using the hash code of the user's name and home path, keeps anonymity
    // but also gives user a chance to distinguish between each other
    X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
    namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA");
    namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode())
            + Integer.toHexString(System.getProperty("user.home").hashCode()));
    namebld.addRDN(BCStyle.O, "OWASP Root CA");
    namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA");
    namebld.addRDN(BCStyle.C, "xx");

    X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(),
            BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey);

    KeyStore ks = null;
    try {
        certGen.addExtension(X509Extension.subjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(pubKey));
        certGen.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(true));
        certGen.addExtension(X509Extension.keyUsage, false,
                new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
                        | KeyUsage.dataEncipherment | KeyUsage.cRLSign));

        Vector<DERObject> eku = new Vector<>(3, 1);
        eku.add(KeyPurposeId.id_kp_serverAuth);
        eku.add(KeyPurposeId.id_kp_clientAuth);
        eku.add(KeyPurposeId.anyExtendedKeyUsage);
        certGen.addExtension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku));

        final ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC")
                .build(privKey);
        final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(certGen.build(sigGen));

        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        ks.setKeyEntry(FixedSslCertificateService.ZAPROXY_JKS_ALIAS, privKey,
                FixedSslCertificateService.PASSPHRASE, new Certificate[] { cert });
    } catch (final Exception e) {
        throw new IllegalStateException("Errors during assembling root CA.", e);
    }
    return ks;
}

From source file:org.cryptable.pki.communication.PKICMPMessages.java

License:Open Source License

/**
 * The message to decode a certification response
 *
 * @param message//  w  w w.j ava  2  s.co  m
 * @return response message
 * @throws IOException
 * @throws PKICMPMessageException
 */
PKICMPResponse processResponse(byte[] message) throws IOException, PKICMPMessageException, CertificateException,
        OperatorCreationException, CMPException, PKIKeyStoreException, ParseException {
    CertificationResult certificationResult = new CertificationResult();

    ProtectedPKIMessage pkiMessage = new ProtectedPKIMessage(new GeneralPKIMessage(message));

    /* Verify Signature */
    ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder()
            .setProvider(pkiKeyStore.getProvider()).build(pkiKeyStore.getRecipientCertificate());

    if (!pkiMessage.verify(verifierProvider)) {
        throw new PKICMPMessageException("E: Verification failed this is an untrusted Message ["
                + pkiMessage.getHeader().getSender() + "]");
    }

    if (!Arrays.equals(senderNonce, pkiMessage.getHeader().getRecipNonce().getOctets()))
        throw new PKICMPMessageException(
                "E: Recipient Nonce in response does not correspond with Sender Nonce in request!");
    if (pkiMessage.getHeader().getMessageTime() != null) {
        pkiKeyStore.verifyCertificate(pkiKeyStore.getRecipientCertificate(),
                pkiMessage.getHeader().getMessageTime().getDate());
    } else {
        pkiKeyStore.verifyCertificate(pkiKeyStore.getRecipientCertificate(), new Date());
    }
    PKICMPResponse pkicmpResponse = new PKICMPResponse();

    pkicmpResponse.setPkiBody(pkiMessage.getBody());
    pkicmpResponse.setPkiHeader(pkiMessage.getHeader());

    X509CertificateHolder[] x509CertificateHolders = pkiMessage.getCertificates();
    JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
    for (X509CertificateHolder x509CertificateHolder : x509CertificateHolders) {
        pkicmpResponse.getX509CertifificateList()
                .add(jcaX509CertificateConverter.getCertificate(x509CertificateHolder));

    }
    return pkicmpResponse;
}

From source file:org.cryptable.pki.communication.PKICMPMessages.java

License:Open Source License

/**
 * Process the certification in the PKIBody content. This is used by the initialization process
 * certification and keyupdate process//from   w ww  .j  a  v  a 2s .c o m
 *
 * @param pkiBody
 * @return
 * @throws IOException
 * @throws CMSException
 * @throws CRMFException
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 */
CertificationResult processCertification(PKIBody pkiBody) throws IOException, CMSException, CRMFException,
        InvalidKeySpecException, NoSuchAlgorithmException, CertificateException {
    CertificationResult certificationResult = new CertificationResult();
    CertRepMessage certRepMessage = CertRepMessage.getInstance(pkiBody.getContent());
    CertResponse[] certResponses = certRepMessage.getResponse();
    certificationResult.setCertificateId(certResponses[0].getCertReqId().getValue());
    CMPCertificate certificate = certResponses[0].getCertifiedKeyPair().getCertOrEncCert().getCertificate();

    certificationResult.setX509Certificate(new JcaX509CertificateConverter()
            .getCertificate(new X509CertificateHolder(certificate.getX509v3PKCert())));

    EncryptedValue encPrivateKey = certResponses[0].getCertifiedKeyPair().getPrivateKey();
    if (encPrivateKey != null) {
        JceAsymmetricValueDecryptorGenerator jceAsymmetricValueDecryptorGenerator = new JceAsymmetricValueDecryptorGenerator(
                pkiKeyStore.getSenderPrivateKey());
        InputDecryptor decryptor = jceAsymmetricValueDecryptorGenerator.getValueDecryptor(
                encPrivateKey.getKeyAlg(), encPrivateKey.getSymmAlg(),
                encPrivateKey.getEncSymmKey().getBytes());
        InputStream dataIn = decryptor
                .getInputStream(new ByteArrayInputStream(encPrivateKey.getEncValue().getBytes()));
        byte[] data = Streams.readAll(dataIn);
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(data);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        certificationResult.setPrivateKey(keyFactory.generatePrivate(pkcs8EncodedKeySpec));
    }

    CMPCertificate[] caPubs = certRepMessage.getCaPubs();
    for (CMPCertificate cmpCertificate : caPubs) {
        certificationResult.addX509CertificateToChain(new JcaX509CertificateConverter()
                .getCertificate(new X509CertificateHolder(cmpCertificate.getX509v3PKCert())));
    }

    return certificationResult;
}

From source file:org.cryptable.pki.util.GeneratePKI.java

License:Open Source License

/**
 * we generate the CA's certificate//from  w  w  w .  j  ava  2s  .  c  o m
* @throws OperatorCreationException 
* @throws NoSuchAlgorithmException 
* @throws CertIOException 
* @throws CertificateException 
 */
private static Certificate createMasterCert(PublicKey pubKey, PrivateKey privKey)
        throws OperatorCreationException, NoSuchAlgorithmException, CertificateException, CertIOException {
    // Signer of the certificate
    ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC)
            .build(privKey);
    // Builder of the certificate
    X509v3CertificateBuilder v3CertBuilder = new JcaX509v3CertificateBuilder(
            // signers name 
            new X500Name("C=BE, O=Cryptable, OU=PKI Devision, CN=Class 0 CA"),
            // Serial Number
            BigInteger.valueOf(1),
            // Not Before
            new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
            // Not After
            new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)),
            // subjects name - the same as we are self signed.
            new X500Name("C=BE, O=Cryptable, OU=PKI Devision, CN=Class 0 CA"),
            // Public key of the certificate
            pubKey);

    v3CertBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
            (new JcaX509ExtensionUtils()).createAuthorityKeyIdentifier(pubKey));
    v3CertBuilder.addExtension(X509Extension.subjectKeyIdentifier, false,
            (new JcaX509ExtensionUtils()).createSubjectKeyIdentifier(pubKey));
    BasicConstraints extBasicConstraints = new BasicConstraints(1);
    v3CertBuilder.addExtension(X509Extension.basicConstraints, true, extBasicConstraints);

    return new JcaX509CertificateConverter().setProvider(BC).getCertificate(v3CertBuilder.build(sigGen));
}

From source file:org.cryptable.pki.util.GeneratePKI.java

License:Open Source License

/**
 * we generate an intermediate certificate signed by our CA
 * @throws OperatorCreationException /*from  w  w w  .ja  v  a 2s  . c  o  m*/
 * @throws NoSuchAlgorithmException 
 * @throws CertIOException 
 * @throws CertificateException 
 */
private static Certificate createIntermediateCert(PublicKey pubKey, PrivateKey caPrivKey,
        X509Certificate caCert)
        throws OperatorCreationException, CertIOException, NoSuchAlgorithmException, CertificateException {
    // Signer of the certificate
    ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC)
            .build(caPrivKey);
    // Builder of the certificate
    X509v3CertificateBuilder v3CertBuilder = new JcaX509v3CertificateBuilder(
            // signers name 
            JcaX500NameUtil.getSubject(caCert),
            // Serial Number
            BigInteger.valueOf(2),
            // Not Before
            new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
            // Not After
            new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)),
            // subjects name - the same as we are self signed.
            new X500Name("C=BE, O=Cryptable, OU=PKI Devision, CN=Class 0 SubCA"),
            // Public key of the certificate
            pubKey);

    v3CertBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
            (new JcaX509ExtensionUtils()).createAuthorityKeyIdentifier(caCert));
    v3CertBuilder.addExtension(X509Extension.subjectKeyIdentifier, false,
            (new JcaX509ExtensionUtils()).createSubjectKeyIdentifier(pubKey));
    v3CertBuilder.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(0));

    return new JcaX509CertificateConverter().setProvider(BC).getCertificate(v3CertBuilder.build(sigGen));
}

From source file:org.cryptable.pki.util.GeneratePKI.java

License:Open Source License

/**
 * we generate a certificate signed by our CA's intermediate certficate
 * @throws OperatorCreationException //  www . ja  va2s  . co  m
 * @throws NoSuchAlgorithmException 
 * @throws CertIOException 
 * @throws CertificateException 
 */
private static Certificate createRACert(PublicKey pubKey, PrivateKey caPrivKey, X509Certificate caCert)
        throws OperatorCreationException, CertIOException, NoSuchAlgorithmException, CertificateException {
    // Signer of the certificate
    ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC)
            .build(caPrivKey);
    // Builder of the certificate
    X509v3CertificateBuilder v3CertBuilder = new JcaX509v3CertificateBuilder(
            // signers name 
            JcaX500NameUtil.getSubject(caCert),
            // Serial Number
            BigInteger.valueOf(2),
            // Not Before
            new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
            // Not After
            new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)),
            // subjects name - the same as we are self signed.
            new X500Name("C=BE, O=Cryptable, OU=PKI Devision, CN=RA"),
            // Public key of the certificate
            pubKey);

    v3CertBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
            (new JcaX509ExtensionUtils()).createAuthorityKeyIdentifier(caCert));
    v3CertBuilder.addExtension(X509Extension.subjectKeyIdentifier, false,
            (new JcaX509ExtensionUtils()).createSubjectKeyIdentifier(pubKey));

    return new JcaX509CertificateConverter().setProvider(BC).getCertificate(v3CertBuilder.build(sigGen));
}

From source file:org.cryptable.pki.util.GeneratePKI.java

License:Open Source License

/**
 * we generate a certificate signed by our CA's intermediate certficate
 * @throws OperatorCreationException/* ww w .  j  a v  a 2s . c o m*/
 * @throws CertificateException
 */
private static Certificate createSelfSignedCert(String distinguishedNmae, PublicKey pubKey, PrivateKey privKey)
        throws OperatorCreationException, CertificateException {
    // Signer of the certificate
    ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC)
            .build(privKey);
    // Builder of the certificate
    X509v3CertificateBuilder v3CertBuilder = new JcaX509v3CertificateBuilder(
            // signers name
            new X500Name(distinguishedNmae),
            // Serial Number
            BigInteger.valueOf(new Random(100).nextLong()),
            // Not Before
            new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
            // Not After
            new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)),
            // subjects name - the same as we are self signed.
            new X500Name(distinguishedNmae),
            // Public key of the certificate
            pubKey);

    return new JcaX509CertificateConverter().setProvider(BC).getCertificate(v3CertBuilder.build(sigGen));
}

From source file:org.cryptable.pki.util.GeneratePKI.java

License:Open Source License

/**
 * we generate a certificate signed by our CA's intermediate certficate
 * @throws OperatorCreationException/*  w w  w .j  av  a 2s  .c  om*/
 * @throws CertificateException
 */
private static Certificate createCert(String distinguishedNmae, PublicKey pubKey, PrivateKey privKey,
        X509Certificate caCert, BigInteger serNum) throws OperatorCreationException, CertificateException {
    // Signer of the certificate
    ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC)
            .build(privKey);
    // Builder of the certificate
    X509v3CertificateBuilder v3CertBuilder = new JcaX509v3CertificateBuilder(
            // signers name
            JcaX500NameUtil.getIssuer(caCert),
            // Serial Number
            serNum,
            // Not Before
            new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
            // Not After
            new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)),
            // subjects name - the same as we are self signed.
            new X500Name(distinguishedNmae),
            // Public key of the certificate
            pubKey);

    return new JcaX509CertificateConverter().setProvider(BC).getCertificate(v3CertBuilder.build(sigGen));
}

From source file:org.cryptable.pki.util.GeneratePKI.java

License:Open Source License

/**
 * we generate an expired certificate signed by our CA's intermediate certficate
 * @throws OperatorCreationException//from  w ww.j  a  va2 s  .  c  o m
 * @throws CertificateException
 */
private static Certificate createExpiredCert(String distinguishedNmae, PublicKey pubKey, PrivateKey privKey,
        X509Certificate caCert, BigInteger serNum) throws OperatorCreationException, CertificateException {
    // Signer of the certificate
    ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC)
            .build(privKey);
    // Builder of the certificate
    X509v3CertificateBuilder v3CertBuilder = new JcaX509v3CertificateBuilder(
            // signers name
            JcaX500NameUtil.getIssuer(caCert),
            // Serial Number
            serNum,
            // Not Before
            new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
            // Not After
            new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24)),
            // subjects name - the same as we are self signed.
            new X500Name(distinguishedNmae),
            // Public key of the certificate
            pubKey);

    return new JcaX509CertificateConverter().setProvider(BC).getCertificate(v3CertBuilder.build(sigGen));
}

From source file:org.cryptable.pki.util.GeneratePKI.java

License:Open Source License

/**
 * we generate a not yet valid certificate signed by our CA's intermediate certficate
 * @throws OperatorCreationException// www .  j a v  a 2 s  . co  m
 * @throws CertificateException
 */
private static Certificate createNotYetValidCert(String distinguishedNmae, PublicKey pubKey, PrivateKey privKey,
        X509Certificate caCert, BigInteger serNum) throws OperatorCreationException, CertificateException {
    // Signer of the certificate
    ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC)
            .build(privKey);
    // Builder of the certificate
    X509v3CertificateBuilder v3CertBuilder = new JcaX509v3CertificateBuilder(
            // signers name
            JcaX500NameUtil.getIssuer(caCert),
            // Serial Number
            serNum,
            // Not Before
            new Date(System.currentTimeMillis() + 1000L * 60 * 60 * 24),
            // Not After
            new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)),
            // subjects name - the same as we are self signed.
            new X500Name(distinguishedNmae),
            // Public key of the certificate
            pubKey);

    return new JcaX509CertificateConverter().setProvider(BC).getCertificate(v3CertBuilder.build(sigGen));
}