Search in sources :

Example 46 with SubjectKeyIdentifier

use of com.github.zhenwei.core.asn1.x509.SubjectKeyIdentifier in project zaproxy by zaproxy.

the class SslCertificateServiceImpl method createCertForHost.

@Override
public KeyStore createCertForHost(CertData certData) throws NoSuchAlgorithmException, InvalidKeyException, CertificateException, NoSuchProviderException, SignatureException, KeyStoreException, IOException, UnrecoverableKeyException {
    if (this.caCert == null || this.caPrivKey == null || this.caPubKey == null) {
        throw new MissingRootCertificateException(this.getClass() + " wasn't initialized! Got to options 'Dynamic SSL Certs' and create one.");
    }
    CertData.Name[] certDataNames = certData.getSubjectAlternativeNames();
    GeneralName[] subjectAlternativeNames = new GeneralName[certDataNames.length];
    for (int i = 0; i < certDataNames.length; i++) {
        CertData.Name certDataName = certDataNames[i];
        subjectAlternativeNames[i] = new GeneralName(certDataName.getType(), certDataName.getValue());
    }
    if (certData.getCommonName() == null && subjectAlternativeNames.length == 0) {
        throw new IllegalArgumentException("commonName is null and no subjectAlternativeNames are specified");
    }
    final KeyPair mykp = this.createKeyPair();
    final PrivateKey privKey = mykp.getPrivate();
    final PublicKey pubKey = mykp.getPublic();
    X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
    if (certData.getCommonName() != null) {
        namebld.addRDN(BCStyle.CN, certData.getCommonName());
    }
    namebld.addRDN(BCStyle.OU, "Zed Attack Proxy Project");
    namebld.addRDN(BCStyle.O, "OWASP");
    namebld.addRDN(BCStyle.C, "xx");
    namebld.addRDN(BCStyle.EmailAddress, "zaproxy-develop@googlegroups.com");
    long currentTime = System.currentTimeMillis();
    X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(new X509CertificateHolder(caCert.getEncoded()).getSubject(), BigInteger.valueOf(serial.getAndIncrement()), new Date(currentTime - Duration.ofDays(SITE_CERTIFICATE_START_ADJUSTMENT).toMillis()), new Date(currentTime + Duration.ofDays(SITE_CERTIFICATE_END_VALIDITY_PERIOD).toMillis()), namebld.build(), pubKey);
    certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded()));
    certGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
    certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_serverAuth }));
    if (subjectAlternativeNames.length > 0) {
        certGen.addExtension(Extension.subjectAlternativeName, certData.isSubjectAlternativeNameIsCritical(), new GeneralNames(subjectAlternativeNames));
    }
    ContentSigner sigGen;
    try {
        sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(caPrivKey);
    } catch (OperatorCreationException e) {
        throw new CertificateException(e);
    }
    final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
    cert.checkValidity(new Date());
    cert.verify(caPubKey);
    final KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    final Certificate[] chain = new Certificate[2];
    chain[1] = this.caCert;
    chain[0] = cert;
    ks.setKeyEntry(ZAPROXY_JKS_ALIAS, privKey, PASSPHRASE, chain);
    return ks;
}
Also used : RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) CertificateException(java.security.cert.CertificateException) GeneralName(org.bouncycastle.asn1.x509.GeneralName) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyPair(java.security.KeyPair) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) PublicKey(java.security.PublicKey) ContentSigner(org.bouncycastle.operator.ContentSigner) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) KeyStore(java.security.KeyStore) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 47 with SubjectKeyIdentifier

use of com.github.zhenwei.core.asn1.x509.SubjectKeyIdentifier in project zaproxy by zaproxy.

the class SslCertificateUtils method createRootCA.

/**
 * Creates a new Root CA certificate and returns private and public key as {@link KeyStore}. The
 * {@link KeyStore#getDefaultType()} is used.
 *
 * @return
 * @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_VALIDITY_IN_MS);
    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();
    Security.addProvider(new BouncyCastleProvider());
    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(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded()));
        certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
        certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign));
        KeyPurposeId[] eku = { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth, KeyPurposeId.anyExtendedKeyUsage };
        certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku));
        final ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").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(org.parosproxy.paros.security.SslCertificateService.ZAPROXY_JKS_ALIAS, privKey, org.parosproxy.paros.security.SslCertificateService.PASSPHRASE, new Certificate[] { cert });
    } catch (final Exception e) {
        throw new IllegalStateException("Errors during assembling root CA.", e);
    }
    return ks;
}
Also used : KeyPair(java.security.KeyPair) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) PublicKey(java.security.PublicKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) KeyPairGenerator(java.security.KeyPairGenerator) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) KeyStore(java.security.KeyStore) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Random(java.util.Random) SecureRandom(java.security.SecureRandom) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 48 with SubjectKeyIdentifier

use of com.github.zhenwei.core.asn1.x509.SubjectKeyIdentifier in project keycloak by keycloak.

the class OCSPUtils method verifyResponse.

private static void verifyResponse(BasicOCSPResp basicOcspResponse, X509Certificate issuerCertificate, X509Certificate responderCertificate, byte[] requestNonce, Date date) throws NoSuchProviderException, NoSuchAlgorithmException, CertificateNotYetValidException, CertificateExpiredException, CertPathValidatorException {
    List<X509CertificateHolder> certs = new ArrayList<>(Arrays.asList(basicOcspResponse.getCerts()));
    X509Certificate signingCert = null;
    try {
        certs.add(new JcaX509CertificateHolder(issuerCertificate));
        if (responderCertificate != null) {
            certs.add(new JcaX509CertificateHolder(responderCertificate));
        }
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
    }
    if (certs.size() > 0) {
        X500Name responderName = basicOcspResponse.getResponderId().toASN1Primitive().getName();
        byte[] responderKey = basicOcspResponse.getResponderId().toASN1Primitive().getKeyHash();
        if (responderName != null) {
            logger.log(Level.INFO, "Responder Name: {0}", responderName.toString());
            for (X509CertificateHolder certHolder : certs) {
                try {
                    X509Certificate tempCert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
                    X500Name respName = new X500Name(tempCert.getSubjectX500Principal().getName());
                    if (responderName.equals(respName)) {
                        signingCert = tempCert;
                        logger.log(Level.INFO, "Found a certificate whose principal \"{0}\" matches the responder name \"{1}\"", new Object[] { tempCert.getSubjectDN().getName(), responderName.toString() });
                        break;
                    }
                } catch (CertificateException e) {
                    logger.log(Level.FINE, e.getMessage());
                }
            }
        } else if (responderKey != null) {
            SubjectKeyIdentifier responderSubjectKey = new SubjectKeyIdentifier(responderKey);
            logger.log(Level.INFO, "Responder Key: {0}", Arrays.toString(responderKey));
            for (X509CertificateHolder certHolder : certs) {
                try {
                    X509Certificate tempCert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
                    SubjectKeyIdentifier subjectKeyIdentifier = null;
                    if (certHolder.getExtensions() != null) {
                        subjectKeyIdentifier = SubjectKeyIdentifier.fromExtensions(certHolder.getExtensions());
                    }
                    if (subjectKeyIdentifier != null) {
                        logger.log(Level.INFO, "Certificate: {0}\nSubject Key Id: {1}", new Object[] { tempCert.getSubjectDN().getName(), Arrays.toString(subjectKeyIdentifier.getKeyIdentifier()) });
                    }
                    if (subjectKeyIdentifier != null && responderSubjectKey.equals(subjectKeyIdentifier)) {
                        signingCert = tempCert;
                        logger.log(Level.INFO, "Found a signer certificate \"{0}\" with the subject key extension value matching the responder key", signingCert.getSubjectDN().getName());
                        break;
                    }
                    subjectKeyIdentifier = new JcaX509ExtensionUtils().createSubjectKeyIdentifier(tempCert.getPublicKey());
                    if (responderSubjectKey.equals(subjectKeyIdentifier)) {
                        signingCert = tempCert;
                        logger.log(Level.INFO, "Found a certificate \"{0}\" with the subject key matching the OCSP responder key", signingCert.getSubjectDN().getName());
                        break;
                    }
                } catch (CertificateException e) {
                    logger.log(Level.FINE, e.getMessage());
                }
            }
        }
    }
    if (signingCert != null) {
        if (signingCert.equals(issuerCertificate)) {
            logger.log(Level.INFO, "OCSP response is signed by the target''s Issuing CA");
        } else if (responderCertificate != null && signingCert.equals(responderCertificate)) {
            // https://www.ietf.org/rfc/rfc2560.txt
            // 2.6  OCSP Signature Authority Delegation
            // - The responder certificate is issued to the responder by CA
            logger.log(Level.INFO, "OCSP response is signed by an authorized responder certificate");
        } else {
            // question."
            if (!signingCert.getIssuerX500Principal().equals(issuerCertificate.getSubjectX500Principal())) {
                logger.log(Level.INFO, "Signer certificate''s Issuer: {0}\nIssuer certificate''s Subject: {1}", new Object[] { signingCert.getIssuerX500Principal().getName(), issuerCertificate.getSubjectX500Principal().getName() });
                throw new CertPathValidatorException("Responder\'s certificate is not authorized to sign OCSP responses");
            }
            try {
                List<String> purposes = signingCert.getExtendedKeyUsage();
                if (purposes == null || !purposes.contains(KeyPurposeId.id_kp_OCSPSigning.getId())) {
                    logger.log(Level.INFO, "OCSPSigning extended usage is not set");
                    throw new CertPathValidatorException("Responder\'s certificate not valid for signing OCSP responses");
                }
            } catch (CertificateParsingException e) {
                logger.log(Level.FINE, "Failed to get certificate''s extended key usage extension\n{0}", e.getMessage());
            }
            if (date == null) {
                signingCert.checkValidity();
            } else {
                signingCert.checkValidity(date);
            }
            try {
                Extension noOCSPCheck = new JcaX509CertificateHolder(signingCert).getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck);
                // TODO If the extension is present, the OCSP client can trust the
                // responder's certificate for the lifetime of the certificate.
                logger.log(Level.INFO, "OCSP no-check extension is {0} present", noOCSPCheck == null ? "not" : "");
            } catch (CertificateEncodingException e) {
                logger.log(Level.FINE, "Certificate encoding exception: {0}", e.getMessage());
            }
            try {
                signingCert.verify(issuerCertificate.getPublicKey());
                logger.log(Level.INFO, "OCSP response is signed by an Authorized Responder");
            } catch (GeneralSecurityException ex) {
                signingCert = null;
            }
        }
    }
    if (signingCert == null) {
        throw new CertPathValidatorException("Unable to verify OCSP Response\'s signature");
    } else {
        if (!verifySignature(basicOcspResponse, signingCert)) {
            throw new CertPathValidatorException("Error verifying OCSP Response\'s signature");
        } else {
            Extension responseNonce = basicOcspResponse.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
            if (responseNonce != null && requestNonce != null && !Arrays.equals(requestNonce, responseNonce.getExtnValue().getOctets())) {
                throw new CertPathValidatorException("Nonces do not match.");
            } else {
                // See Sun's OCSP implementation.
                // https://www.ietf.org/rfc/rfc2560.txt, if nextUpdate is not set,
                // the responder is indicating that newer update is avilable all the time
                long current = date == null ? System.currentTimeMillis() : date.getTime();
                Date stop = new Date(current + (long) TIME_SKEW);
                Date start = new Date(current - (long) TIME_SKEW);
                Iterator<SingleResp> iter = Arrays.asList(basicOcspResponse.getResponses()).iterator();
                SingleResp singleRes = null;
                do {
                    if (!iter.hasNext()) {
                        return;
                    }
                    singleRes = iter.next();
                } while (!stop.before(singleRes.getThisUpdate()) && !start.after(singleRes.getNextUpdate() != null ? singleRes.getNextUpdate() : singleRes.getThisUpdate()));
                throw new CertPathValidatorException("Response is unreliable: its validity interval is out-of-date");
            }
        }
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) GeneralSecurityException(java.security.GeneralSecurityException) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) Extension(org.bouncycastle.asn1.x509.Extension) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder)

Example 49 with SubjectKeyIdentifier

use of com.github.zhenwei.core.asn1.x509.SubjectKeyIdentifier in project LinLong-Java by zhenwei1108.

the class KeyAgreeRecipientInformation method getSenderPublicKeyInfo.

private SubjectPublicKeyInfo getSenderPublicKeyInfo(AlgorithmIdentifier recKeyAlgId, OriginatorIdentifierOrKey originator) throws CMSException, IOException {
    OriginatorPublicKey opk = originator.getOriginatorKey();
    if (opk != null) {
        return getPublicKeyInfoFromOriginatorPublicKey(recKeyAlgId, opk);
    }
    OriginatorId origID;
    IssuerAndSerialNumber iAndSN = originator.getIssuerAndSerialNumber();
    if (iAndSN != null) {
        origID = new OriginatorId(iAndSN.getName(), iAndSN.getSerialNumber().getValue());
    } else {
        SubjectKeyIdentifier ski = originator.getSubjectKeyIdentifier();
        origID = new OriginatorId(ski.getKeyIdentifier());
    }
    return getPublicKeyInfoFromOriginatorId(origID);
}
Also used : IssuerAndSerialNumber(com.github.zhenwei.pkix.util.asn1.cms.IssuerAndSerialNumber) SubjectKeyIdentifier(com.github.zhenwei.core.asn1.x509.SubjectKeyIdentifier) OriginatorPublicKey(com.github.zhenwei.pkix.util.asn1.cms.OriginatorPublicKey)

Example 50 with SubjectKeyIdentifier

use of com.github.zhenwei.core.asn1.x509.SubjectKeyIdentifier in project LinLong-Java by zhenwei1108.

the class KeyTransRecipientInfoGenerator method generate.

public final RecipientInfo generate(GenericKey contentEncryptionKey) throws CMSException {
    byte[] encryptedKeyBytes;
    try {
        encryptedKeyBytes = wrapper.generateWrappedKey(contentEncryptionKey);
    } catch (OperatorException e) {
        throw new CMSException("exception wrapping content key: " + e.getMessage(), e);
    }
    RecipientIdentifier recipId;
    if (issuerAndSerial != null) {
        recipId = new RecipientIdentifier(issuerAndSerial);
    } else {
        recipId = new RecipientIdentifier(new DEROctetString(subjectKeyIdentifier));
    }
    return new RecipientInfo(new KeyTransRecipientInfo(recipId, wrapper.getAlgorithmIdentifier(), new DEROctetString(encryptedKeyBytes)));
}
Also used : KeyTransRecipientInfo(com.github.zhenwei.pkix.util.asn1.cms.KeyTransRecipientInfo) RecipientIdentifier(com.github.zhenwei.pkix.util.asn1.cms.RecipientIdentifier) KeyTransRecipientInfo(com.github.zhenwei.pkix.util.asn1.cms.KeyTransRecipientInfo) RecipientInfo(com.github.zhenwei.pkix.util.asn1.cms.RecipientInfo) OperatorException(com.github.zhenwei.pkix.operator.OperatorException) DEROctetString(com.github.zhenwei.core.asn1.DEROctetString)

Aggregations

SubjectKeyIdentifier (org.bouncycastle.asn1.x509.SubjectKeyIdentifier)34 AuthorityKeyIdentifier (org.bouncycastle.asn1.x509.AuthorityKeyIdentifier)17 X509Certificate (java.security.cert.X509Certificate)14 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)14 IOException (java.io.IOException)12 X500Name (org.bouncycastle.asn1.x500.X500Name)10 GeneralName (org.bouncycastle.asn1.x509.GeneralName)10 ContentSigner (org.bouncycastle.operator.ContentSigner)10 BigInteger (java.math.BigInteger)9 Date (java.util.Date)9 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)9 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)9 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)8 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)8 JcaX509ExtensionUtils (org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils)8 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)7 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 CertificateException (java.security.cert.CertificateException)6