Search in sources :

Example 91 with OperatorCreationException

use of org.bouncycastle.operator.OperatorCreationException in project platformlayer by platformlayer.

the class Csr method buildCsr.

public static Csr buildCsr(KeyPair keyPair, X500Principal subjectName) {
    X500Name subject = BouncyCastleHelpers.toX500Name(subjectName);
    SubjectPublicKeyInfo publicKeyInfo = BouncyCastleHelpers.toSubjectPublicKeyInfo(keyPair.getPublic());
    PKCS10CertificationRequestBuilder csrBuilder = new PKCS10CertificationRequestBuilder(subject, publicKeyInfo);
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    BcRSAContentSignerBuilder sigBuild = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
    ContentSigner signer;
    try {
        signer = sigBuild.build(BouncyCastleHelpers.toAsymmetricKeyParameter(keyPair.getPrivate()));
    } catch (OperatorCreationException e) {
        throw new IllegalArgumentException("Error building content signer", e);
    }
    PKCS10CertificationRequest csrHolder = csrBuilder.build(signer);
    return new Csr(csrHolder);
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) BcRSAContentSignerBuilder(org.bouncycastle.operator.bc.BcRSAContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) X500Name(org.bouncycastle.asn1.x500.X500Name) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder)

Example 92 with OperatorCreationException

use of org.bouncycastle.operator.OperatorCreationException in project keycloak by keycloak.

the class CertificateValidatorTest method createCertificate.

/**
 * will create a self-signed certificate
 *
 * @param dn the DN of the subject and issuer
 * @param startDate startdate of the validity of the created certificate
 * @param expiryDate expiration date of the created certificate
 * @param keyPair the keypair that is used to create the certificate
 * @param extensions optional list of extensions to include in the certificate
 * @return a X509-Certificate in version 3
 */
public X509Certificate createCertificate(String dn, Date startDate, Date expiryDate, KeyPair keyPair, List<Extension> extensions) {
    // Cert data
    X500Name subjectDN = new X500Name(dn);
    X500Name issuerDN = new X500Name(dn);
    SubjectPublicKeyInfo subjPubKeyInfo = SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()));
    BigInteger serialNumber = new BigInteger(130, new SecureRandom());
    // Build the certificate
    X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(issuerDN, serialNumber, startDate, expiryDate, subjectDN, subjPubKeyInfo);
    if (extensions != null) {
        try {
            for (Extension certExtension : extensions) certGen.addExtension(certExtension);
        } catch (CertIOException e) {
            throw new IllegalStateException(e);
        }
    }
    // Sign the cert with the private key
    try {
        ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA").setProvider(BOUNCY_CASTLE_PROVIDER).build(keyPair.getPrivate());
        X509Certificate x509Certificate = new JcaX509CertificateConverter().setProvider(BOUNCY_CASTLE_PROVIDER).getCertificate(certGen.build(contentSigner));
        return x509Certificate;
    } catch (CertificateException | OperatorCreationException e) {
        throw new IllegalStateException(e);
    }
}
Also used : JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) CertIOException(org.bouncycastle.cert.CertIOException) X509Certificate(java.security.cert.X509Certificate) Extension(org.bouncycastle.asn1.x509.Extension) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) BigInteger(java.math.BigInteger) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Example 93 with OperatorCreationException

use of org.bouncycastle.operator.OperatorCreationException in project keycloak by keycloak.

the class OCSPUtils method check.

/**
 * Requests certificate revocation status using OCSP.
 * @param cert the certificate to be checked
 * @param issuerCertificate the issuer certificate
 * @param responderURIs the OCSP responder URIs
 * @param responderCert the OCSP responder certificate
 * @param date if null, the current time is used.
 * @return a revocation status
 * @throws CertPathValidatorException
 */
private static OCSPRevocationStatus check(KeycloakSession session, X509Certificate cert, X509Certificate issuerCertificate, List<URI> responderURIs, X509Certificate responderCert, Date date) throws CertPathValidatorException {
    if (responderURIs == null || responderURIs.size() == 0)
        throw new IllegalArgumentException("Need at least one responder");
    try {
        DigestCalculator digCalc = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
        JcaCertificateID certificateID = new JcaCertificateID(digCalc, issuerCertificate, cert.getSerialNumber());
        // Create a nounce extension to protect against replay attacks
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        BigInteger nounce = BigInteger.valueOf(Math.abs(random.nextInt()));
        DEROctetString derString = new DEROctetString(nounce.toByteArray());
        Extension nounceExtension = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, derString);
        Extensions extensions = new Extensions(nounceExtension);
        OCSPReq ocspReq = new OCSPReqBuilder().addRequest(certificateID, extensions).build();
        URI responderURI = responderURIs.get(0);
        logger.log(Level.INFO, "OCSP Responder {0}", responderURI);
        try {
            OCSPResp resp = getResponse(session, ocspReq, responderURI);
            logger.log(Level.FINE, "Received a response from OCSP responder {0}, the response status is {1}", new Object[] { responderURI, resp.getStatus() });
            switch(resp.getStatus()) {
                case OCSPResp.SUCCESSFUL:
                    if (resp.getResponseObject() instanceof BasicOCSPResp) {
                        return processBasicOCSPResponse(issuerCertificate, responderCert, date, certificateID, nounce, (BasicOCSPResp) resp.getResponseObject());
                    } else {
                        throw new CertPathValidatorException("OCSP responder returned an invalid or unknown OCSP response.");
                    }
                case OCSPResp.INTERNAL_ERROR:
                case OCSPResp.TRY_LATER:
                    throw new CertPathValidatorException("Internal error/try later. OCSP response error: " + resp.getStatus(), (Throwable) null, (CertPath) null, -1, CertPathValidatorException.BasicReason.UNDETERMINED_REVOCATION_STATUS);
                case OCSPResp.SIG_REQUIRED:
                    throw new CertPathValidatorException("Invalid or missing signature. OCSP response error: " + resp.getStatus(), (Throwable) null, (CertPath) null, -1, CertPathValidatorException.BasicReason.INVALID_SIGNATURE);
                case OCSPResp.UNAUTHORIZED:
                    throw new CertPathValidatorException("Unauthorized request. OCSP response error: " + resp.getStatus(), (Throwable) null, (CertPath) null, -1, CertPathValidatorException.BasicReason.UNSPECIFIED);
                case OCSPResp.MALFORMED_REQUEST:
                default:
                    throw new CertPathValidatorException("OCSP request is malformed. OCSP response error: " + resp.getStatus(), (Throwable) null, (CertPath) null, -1, CertPathValidatorException.BasicReason.UNSPECIFIED);
            }
        } catch (IOException e) {
            logger.log(Level.FINE, "OCSP Responder \"{0}\" failed to return a valid OCSP response\n{1}", new Object[] { responderURI, e.getMessage() });
            throw new CertPathValidatorException("OCSP check failed", e);
        }
    } catch (CertificateNotYetValidException | CertificateExpiredException | OperatorCreationException | OCSPException | CertificateEncodingException | NoSuchAlgorithmException | NoSuchProviderException e) {
        logger.log(Level.FINE, e.getMessage());
        throw new CertPathValidatorException(e.getMessage(), e);
    }
}
Also used : DigestCalculator(org.bouncycastle.operator.DigestCalculator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Extensions(org.bouncycastle.asn1.x509.Extensions) URI(java.net.URI) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) BcDigestCalculatorProvider(org.bouncycastle.operator.bc.BcDigestCalculatorProvider) JcaCertificateID(org.bouncycastle.cert.ocsp.jcajce.JcaCertificateID) SecureRandom(java.security.SecureRandom) IOException(java.io.IOException) Extension(org.bouncycastle.asn1.x509.Extension) BigInteger(java.math.BigInteger) NoSuchProviderException(java.security.NoSuchProviderException)

Aggregations

OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)93 IOException (java.io.IOException)52 ContentSigner (org.bouncycastle.operator.ContentSigner)40 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)38 CertificateException (java.security.cert.CertificateException)32 X509Certificate (java.security.cert.X509Certificate)31 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)23 Date (java.util.Date)21 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)20 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)17 CMSException (org.bouncycastle.cms.CMSException)17 X500Name (org.bouncycastle.asn1.x500.X500Name)16 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)16 GeneralName (org.bouncycastle.asn1.x509.GeneralName)15 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)14 CMSSignedData (org.bouncycastle.cms.CMSSignedData)12 GeneralSecurityException (java.security.GeneralSecurityException)11 BigInteger (java.math.BigInteger)10 NoSuchProviderException (java.security.NoSuchProviderException)10 CertificateEncodingException (java.security.cert.CertificateEncodingException)10