Search in sources :

Example 1 with ContentVerifierProvider

use of org.bouncycastle.operator.ContentVerifierProvider in project Openfire by igniterealtime.

the class CertificateManager method createX509V3Certificate.

/**
     * Creates an X509 version3 certificate.
     *
     * @param kp           KeyPair that keeps the public and private keys for the new certificate.
     * @param days       time to live
     * @param issuerBuilder     IssuerDN builder
     * @param subjectBuilder    SubjectDN builder
     * @param domain       Domain of the server.
     * @param signAlgoritm Signature algorithm. This can be either a name or an OID.
     * @return X509 V3 Certificate
     * @throws GeneralSecurityException
     * @throws IOException
     */
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, X500NameBuilder issuerBuilder, X500NameBuilder subjectBuilder, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
    PublicKey pubKey = kp.getPublic();
    PrivateKey privKey = kp.getPrivate();
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed((new Date().getTime()));
    random.nextBytes(serno);
    BigInteger serial = (new java.math.BigInteger(serno)).abs();
    X500Name issuerDN = issuerBuilder.build();
    X500Name subjectDN = subjectBuilder.build();
    // builder
    JcaX509v3CertificateBuilder certBuilder = new //
    JcaX509v3CertificateBuilder(//
    issuerDN, //
    serial, //
    new Date(), //
    new Date(System.currentTimeMillis() + days * (1000L * 60 * 60 * 24)), //
    subjectDN, //
    pubKey);
    // add subjectAlternativeName extension
    boolean critical = subjectDN.getRDNs().length == 0;
    ASN1Sequence othernameSequence = new DERSequence(new ASN1Encodable[] { new ASN1ObjectIdentifier("1.3.6.1.5.5.7.8.5"), new DERUTF8String(domain) });
    GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence);
    GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN });
    certBuilder.addExtension(Extension.subjectAlternativeName, critical, subjectAltNames);
    // add keyIdentifiers extensions
    JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();
    certBuilder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(pubKey));
    certBuilder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(pubKey));
    try {
        // build the certificate
        ContentSigner signer = new JcaContentSignerBuilder(signAlgoritm).build(privKey);
        X509CertificateHolder cert = certBuilder.build(signer);
        // verify the validity
        if (!cert.isValidOn(new Date())) {
            throw new GeneralSecurityException("Certificate validity not valid");
        }
        // verify the signature (self-signed)
        ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().build(pubKey);
        if (!cert.isSignatureValid(verifierProvider)) {
            throw new GeneralSecurityException("Certificate signature not valid");
        }
        return new JcaX509CertificateConverter().getCertificate(cert);
    } catch (OperatorCreationException | CertException e) {
        throw new GeneralSecurityException(e);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) PrivateKey(java.security.PrivateKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) X500Name(org.bouncycastle.asn1.x500.X500Name) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider) PublicKey(java.security.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) CertException(org.bouncycastle.cert.CertException) Date(java.util.Date) JcaContentVerifierProviderBuilder(org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) GeneralName(org.bouncycastle.asn1.x509.GeneralName)

Example 2 with ContentVerifierProvider

use of org.bouncycastle.operator.ContentVerifierProvider in project keystore-explorer by kaikramer.

the class Pkcs10Util method verifyCsr.

/**
 * Verify a PKCS #10 certificate signing request (CSR).
 *
 * @param csr The certificate signing request
 * @return True if successfully verified
 * @throws CryptoException
 * 				If there was a problem verifying the CSR
 */
public static boolean verifyCsr(PKCS10CertificationRequest csr) throws CryptoException {
    try {
        PublicKey pubKey = new JcaPKCS10CertificationRequest(csr).getPublicKey();
        ContentVerifierProvider contentVerifierProvider = new JcaContentVerifierProviderBuilder().setProvider("BC").build(pubKey);
        return csr.isSignatureValid(contentVerifierProvider);
    } catch (InvalidKeyException e) {
        throw new CryptoException(res.getString("NoVerifyPkcs10Csr.exception.message"), e);
    } catch (OperatorCreationException e) {
        throw new CryptoException(res.getString("NoVerifyPkcs10Csr.exception.message"), e);
    } catch (NoSuchAlgorithmException e) {
        throw new CryptoException(res.getString("NoVerifyPkcs10Csr.exception.message"), e);
    } catch (PKCSException e) {
        throw new CryptoException(res.getString("NoVerifyPkcs10Csr.exception.message"), e);
    }
}
Also used : JcaPKCS10CertificationRequest(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest) JcaContentVerifierProviderBuilder(org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder) PublicKey(java.security.PublicKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CryptoException(org.kse.crypto.CryptoException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) PKCSException(org.bouncycastle.pkcs.PKCSException) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider)

Example 3 with ContentVerifierProvider

use of org.bouncycastle.operator.ContentVerifierProvider in project xipki by xipki.

the class CmpCaClient method verifyProtection.

// method extractGeneralRepContent
private boolean verifyProtection(GeneralPKIMessage pkiMessage) throws CMPException, InvalidKeyException {
    ProtectedPKIMessage protectedMsg = new ProtectedPKIMessage(pkiMessage);
    if (protectedMsg.hasPasswordBasedMacProtection()) {
        LOG.warn("protection is not signature based: " + pkiMessage.getHeader().getProtectionAlg().getAlgorithm().getId());
        return false;
    }
    PKIHeader header = protectedMsg.getHeader();
    if (!header.getSender().equals(responderSubject)) {
        LOG.warn("not authorized responder '{}'", header.getSender());
        return false;
    }
    String algOid = protectedMsg.getHeader().getProtectionAlg().getAlgorithm().getId();
    if (!trustedProtectionAlgOids.contains(algOid)) {
        LOG.warn("PKI protection algorithm is untrusted '{}'", algOid);
        return false;
    }
    ContentVerifierProvider verifierProvider = getContentVerifierProvider(responderCert.getPublicKey());
    if (verifierProvider == null) {
        LOG.warn("not authorized responder '{}'", header.getSender());
        return false;
    }
    return protectedMsg.verify(verifierProvider);
}
Also used : PKIHeader(org.bouncycastle.asn1.cmp.PKIHeader) ProtectedPKIMessage(org.bouncycastle.cert.cmp.ProtectedPKIMessage) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider)

Example 4 with ContentVerifierProvider

use of org.bouncycastle.operator.ContentVerifierProvider in project xipki by xipki.

the class CmpResponder method verifyProtection.

private ProtectionVerificationResult verifyProtection(String tid, GeneralPKIMessage pkiMessage, CmpControl cmpControl) throws CMPException, InvalidKeyException, OperatorCreationException {
    ProtectedPKIMessage protectedMsg = new ProtectedPKIMessage(pkiMessage);
    if (protectedMsg.hasPasswordBasedMacProtection()) {
        LOG.warn("NOT_SIGNAUTRE_BASED: {}", pkiMessage.getHeader().getProtectionAlg().getAlgorithm().getId());
        return new ProtectionVerificationResult(null, ProtectionResult.NOT_SIGNATURE_BASED);
    }
    PKIHeader header = protectedMsg.getHeader();
    AlgorithmIdentifier protectionAlg = header.getProtectionAlg();
    if (!cmpControl.getSigAlgoValidator().isAlgorithmPermitted(protectionAlg)) {
        LOG.warn("SIG_ALGO_FORBIDDEN: {}", pkiMessage.getHeader().getProtectionAlg().getAlgorithm().getId());
        return new ProtectionVerificationResult(null, ProtectionResult.SIGALGO_FORBIDDEN);
    }
    CmpRequestorInfo requestor = getRequestor(header);
    if (requestor == null) {
        LOG.warn("tid={}: not authorized requestor '{}'", tid, header.getSender());
        return new ProtectionVerificationResult(null, ProtectionResult.SENDER_NOT_AUTHORIZED);
    }
    ContentVerifierProvider verifierProvider = securityFactory.getContentVerifierProvider(requestor.getCert().getCert());
    if (verifierProvider == null) {
        LOG.warn("tid={}: not authorized requestor '{}'", tid, header.getSender());
        return new ProtectionVerificationResult(requestor, ProtectionResult.SENDER_NOT_AUTHORIZED);
    }
    boolean signatureValid = protectedMsg.verify(verifierProvider);
    return new ProtectionVerificationResult(requestor, signatureValid ? ProtectionResult.VALID : ProtectionResult.INVALID);
}
Also used : PKIHeader(org.bouncycastle.asn1.cmp.PKIHeader) ProtectedPKIMessage(org.bouncycastle.cert.cmp.ProtectedPKIMessage) ProtectionVerificationResult(org.xipki.cmp.ProtectionVerificationResult) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider)

Example 5 with ContentVerifierProvider

use of org.bouncycastle.operator.ContentVerifierProvider in project jruby-openssl by jruby.

the class SecurityHelper method verify.

static boolean verify(final X509CRL crl, final PublicKey publicKey, final boolean silent) throws NoSuchAlgorithmException, CRLException, InvalidKeyException, SignatureException {
    if (crl instanceof X509CRLObject) {
        final CertificateList crlList = (CertificateList) getCertificateList(crl);
        final AlgorithmIdentifier tbsSignatureId = crlList.getTBSCertList().getSignature();
        if (!crlList.getSignatureAlgorithm().equals(tbsSignatureId)) {
            if (silent)
                return false;
            throw new CRLException("Signature algorithm on CertificateList does not match TBSCertList.");
        }
        final Signature signature = getSignature(crl.getSigAlgName(), securityProvider);
        signature.initVerify(publicKey);
        signature.update(crl.getTBSCertList());
        if (!signature.verify(crl.getSignature())) {
            if (silent)
                return false;
            throw new SignatureException("CRL does not verify with supplied public key.");
        }
        return true;
    } else {
        try {
            final DigestAlgorithmIdentifierFinder digestAlgFinder = new DefaultDigestAlgorithmIdentifierFinder();
            final ContentVerifierProvider verifierProvider;
            if ("DSA".equalsIgnoreCase(publicKey.getAlgorithm())) {
                BigInteger y = ((DSAPublicKey) publicKey).getY();
                DSAParams params = ((DSAPublicKey) publicKey).getParams();
                DSAParameters parameters = new DSAParameters(params.getP(), params.getQ(), params.getG());
                AsymmetricKeyParameter dsaKey = new DSAPublicKeyParameters(y, parameters);
                verifierProvider = new BcDSAContentVerifierProviderBuilder(digestAlgFinder).build(dsaKey);
            } else {
                BigInteger mod = ((RSAPublicKey) publicKey).getModulus();
                BigInteger exp = ((RSAPublicKey) publicKey).getPublicExponent();
                AsymmetricKeyParameter rsaKey = new RSAKeyParameters(false, mod, exp);
                verifierProvider = new BcRSAContentVerifierProviderBuilder(digestAlgFinder).build(rsaKey);
            }
            return new X509CRLHolder(crl.getEncoded()).isSignatureValid(verifierProvider);
        } catch (OperatorException e) {
            throw new SignatureException(e);
        } catch (CertException e) {
            throw new SignatureException(e);
        }// can happen if the input is DER but does not match expected strucure
         catch (ClassCastException e) {
            throw new SignatureException(e);
        } catch (IOException e) {
            throw new SignatureException(e);
        }
    }
}
Also used : DSAPublicKeyParameters(org.bouncycastle.crypto.params.DSAPublicKeyParameters) X509CRLObject(org.bouncycastle.jce.provider.X509CRLObject) BcRSAContentVerifierProviderBuilder(org.bouncycastle.operator.bc.BcRSAContentVerifierProviderBuilder) CertificateList(org.bouncycastle.asn1.x509.CertificateList) CertException(org.bouncycastle.cert.CertException) SignatureException(java.security.SignatureException) DSAParams(java.security.interfaces.DSAParams) IOException(java.io.IOException) DigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DigestAlgorithmIdentifierFinder) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) DefaultDigestAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder) RSAKeyParameters(org.bouncycastle.crypto.params.RSAKeyParameters) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DSAPublicKey(java.security.interfaces.DSAPublicKey) AsymmetricKeyParameter(org.bouncycastle.crypto.params.AsymmetricKeyParameter) RSAPublicKey(java.security.interfaces.RSAPublicKey) Signature(java.security.Signature) X509CRLHolder(org.bouncycastle.cert.X509CRLHolder) BigInteger(java.math.BigInteger) BcDSAContentVerifierProviderBuilder(org.bouncycastle.operator.bc.BcDSAContentVerifierProviderBuilder) CRLException(java.security.cert.CRLException) DSAParameters(org.bouncycastle.crypto.params.DSAParameters) OperatorException(org.bouncycastle.operator.OperatorException) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider)

Aggregations

ContentVerifierProvider (org.bouncycastle.operator.ContentVerifierProvider)18 PublicKey (java.security.PublicKey)9 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)9 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)7 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)6 X500Name (org.bouncycastle.asn1.x500.X500Name)6 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)6 BigInteger (java.math.BigInteger)5 InvalidKeyException (java.security.InvalidKeyException)5 IOException (java.io.IOException)4 X509Certificate (java.security.cert.X509Certificate)4 Date (java.util.Date)4 JcaContentVerifierProviderBuilder (org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder)4 Signature (java.security.Signature)3 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)3 PKIHeader (org.bouncycastle.asn1.cmp.PKIHeader)3 CertException (org.bouncycastle.cert.CertException)3 ProtectedPKIMessage (org.bouncycastle.cert.cmp.ProtectedPKIMessage)3 BasicOCSPResp (org.bouncycastle.cert.ocsp.BasicOCSPResp)3 GeneralSecurityException (java.security.GeneralSecurityException)2