Search in sources :

Example 21 with X509CertificateHolder

use of org.bouncycastle.cert.X509CertificateHolder in project robovm by robovm.

the class JcaContentVerifierProviderBuilder method build.

public ContentVerifierProvider build(final X509Certificate certificate) throws OperatorCreationException {
    final X509CertificateHolder certHolder;
    try {
        certHolder = new JcaX509CertificateHolder(certificate);
    } catch (CertificateEncodingException e) {
        throw new OperatorCreationException("cannot process certificate: " + e.getMessage(), e);
    }
    return new ContentVerifierProvider() {

        private SignatureOutputStream stream;

        public boolean hasAssociatedCertificate() {
            return true;
        }

        public X509CertificateHolder getAssociatedCertificate() {
            return certHolder;
        }

        public ContentVerifier get(AlgorithmIdentifier algorithm) throws OperatorCreationException {
            try {
                Signature sig = helper.createSignature(algorithm);
                sig.initVerify(certificate.getPublicKey());
                stream = new SignatureOutputStream(sig);
            } catch (GeneralSecurityException e) {
                throw new OperatorCreationException("exception on setup: " + e, e);
            }
            Signature rawSig = createRawSig(algorithm, certificate.getPublicKey());
            if (rawSig != null) {
                return new RawSigVerifier(algorithm, stream, rawSig);
            } else {
                return new SigVerifier(algorithm, stream);
            }
        }
    };
}
Also used : X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) Signature(java.security.Signature) GeneralSecurityException(java.security.GeneralSecurityException) CertificateEncodingException(java.security.cert.CertificateEncodingException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 22 with X509CertificateHolder

use of org.bouncycastle.cert.X509CertificateHolder in project helios by spotify.

the class X509CertificateFactory method generate.

private CertificateAndPrivateKey generate(final AgentProxy agentProxy, final Identity identity, final String username) {
    final UUID uuid = new UUID();
    final Calendar calendar = Calendar.getInstance();
    final X500Name issuerdn = new X500Name("C=US,O=Spotify,CN=helios-client");
    final X500Name subjectdn = new X500NameBuilder().addRDN(BCStyle.UID, username).build();
    calendar.add(Calendar.MILLISECOND, -validBeforeMilliseconds);
    final Date notBefore = calendar.getTime();
    calendar.add(Calendar.MILLISECOND, validBeforeMilliseconds + validAfterMilliseconds);
    final Date notAfter = calendar.getTime();
    // Reuse the UUID time as a SN
    final BigInteger serialNumber = BigInteger.valueOf(uuid.getTime()).abs();
    try {
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
        keyPairGenerator.initialize(KEY_SIZE, new SecureRandom());
        final KeyPair keyPair = keyPairGenerator.generateKeyPair();
        final SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()));
        final X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuerdn, serialNumber, notBefore, notAfter, subjectdn, subjectPublicKeyInfo);
        final DigestCalculator digestCalculator = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
        final X509ExtensionUtils utils = new X509ExtensionUtils(digestCalculator);
        final SubjectKeyIdentifier keyId = utils.createSubjectKeyIdentifier(subjectPublicKeyInfo);
        final String keyIdHex = KEY_ID_ENCODING.encode(keyId.getKeyIdentifier());
        log.info("generating an X509 certificate for {} with key ID={} and identity={}", username, keyIdHex, identity.getComment());
        builder.addExtension(Extension.subjectKeyIdentifier, false, keyId);
        builder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(subjectPublicKeyInfo));
        builder.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign));
        builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));
        final X509CertificateHolder holder = builder.build(new SshAgentContentSigner(agentProxy, identity));
        final X509Certificate certificate = CERTIFICATE_CONVERTER.getCertificate(holder);
        log.debug("generated certificate:\n{}", asPemString(certificate));
        return new CertificateAndPrivateKey(certificate, keyPair.getPrivate());
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}
Also used : BcDigestCalculatorProvider(org.bouncycastle.operator.bc.BcDigestCalculatorProvider) KeyPair(java.security.KeyPair) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) Calendar(java.util.Calendar) DigestCalculator(org.bouncycastle.operator.DigestCalculator) SecureRandom(java.security.SecureRandom) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) KeyPairGenerator(java.security.KeyPairGenerator) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) UUID(com.eaio.uuid.UUID) X509ExtensionUtils(org.bouncycastle.cert.X509ExtensionUtils) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 23 with X509CertificateHolder

use of org.bouncycastle.cert.X509CertificateHolder in project nhin-d by DirectProject.

the class CreateSignedPKCS7 method create.

/**
	 * Creates a pcks7 file from the certificate and key files.
	 * @param anchorDir :The Directory where the .der files are present.
	 * @param createFile : The .p7m File name.
	 * @param metaFile :One XML file as per required specification of TrustBundle metadata schema. 
	 * @param p12certiFile : The .p12 file.
	 * @param passkey :Pass Key for the .p12 file if present or else it should be blank.
	 * @param destDir : The Destination folder where the output .p7m files will be created.
	 * 	 * @return File : Returns the created SignedBundle as a .p7m file.
	 */
public File create(String anchorDir, File createFile, File metaFile, boolean metaExists, File p12certiFile, String passKey) {
    File pkcs7File = null;
    FileOutputStream outStr = null;
    InputStream inStr = null;
    try {
        // Create the unsigned Trust Bundle
        CreateUnSignedPKCS7 unSignedPKCS7 = new CreateUnSignedPKCS7();
        File unsigned = unSignedPKCS7.create(anchorDir, createFile, metaFile, metaExists);
        byte[] unsignedByte = loadFileData(unsigned);
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        CMSSignedData unsignedData = new CMSSignedData(unsignedByte);
        // Create the certificate array
        KeyStore ks = java.security.KeyStore.getInstance("PKCS12", "BC");
        ks.load(new FileInputStream(p12certiFile), defaultPwd.toCharArray());
        ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
        Enumeration<String> aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            String alias = (String) aliases.nextElement();
            if (ks.getKey(alias, defaultPwd.toCharArray()) != null && ks.getKey(alias, defaultPwd.toCharArray()) instanceof PrivateKey) {
                ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build((PrivateKey) ks.getKey(alias, defaultPwd.toCharArray()));
                X509CertificateHolder holder = new X509CertificateHolder(ks.getCertificate(alias).getEncoded());
                certList.add((X509Certificate) ks.getCertificate(alias));
                gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, holder));
            }
        }
        Store certStores = new JcaCertStore(certList);
        gen.addCertificates(certStores);
        CMSSignedData sigData = gen.generate(new CMSProcessableByteArray(unsignedData.getEncoded()), true);
        //SignedData encapInfo = SignedData.getInstance(sigData.getContentInfo().getContent());
        pkcs7File = getPKCS7OutFile(createFile);
        outStr = new FileOutputStream(pkcs7File);
        outStr.write(sigData.getEncoded());
    } catch (CMSException e) {
        // e.printStackTrace(System.err);
        return null;
    } catch (IOException e) {
        // e.printStackTrace(System.err);
        return null;
    } catch (KeyStoreException e) {
        // e.printStackTrace(System.err);
        return null;
    } catch (NoSuchProviderException e) {
        // e.printStackTrace(System.err);
        return null;
    } catch (NoSuchAlgorithmException e) {
        // e.printStackTrace(System.err);
        return null;
    } catch (CertificateException e) {
        // e.printStackTrace(System.err);
        return null;
    } catch (UnrecoverableKeyException e) {
        // e.printStackTrace(System.err);
        return null;
    } catch (OperatorCreationException e) {
        // e.printStackTrace(System.err);
        return null;
    } catch (Exception e) {
        // e.printStackTrace(System.err);
        return null;
    } finally {
        IOUtils.closeQuietly(outStr);
        IOUtils.closeQuietly(inStr);
    }
    return pkcs7File;
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) PrivateKey(java.security.PrivateKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ArrayList(java.util.ArrayList) Store(org.bouncycastle.util.Store) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) KeyStore(java.security.KeyStore) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ContentSigner(org.bouncycastle.operator.ContentSigner) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) CMSException(org.bouncycastle.cms.CMSException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException) JcaSignerInfoGeneratorBuilder(org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder) FileOutputStream(java.io.FileOutputStream) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) NoSuchProviderException(java.security.NoSuchProviderException) File(java.io.File) CMSException(org.bouncycastle.cms.CMSException)

Example 24 with X509CertificateHolder

use of org.bouncycastle.cert.X509CertificateHolder in project oxAuth by GluuFederation.

the class CertificateParser method parsePem.

public static X509Certificate parsePem(String pemEncodedCert) throws CertificateException {
    StringReader sr = new StringReader(pemEncodedCert);
    PEMParser pemReader = new PEMParser(sr);
    try {
        X509CertificateHolder certificateHolder = ((X509CertificateHolder) pemReader.readObject());
        if (certificateHolder == null) {
            return null;
        }
        X509Certificate cert = new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);
        return cert;
    } catch (IOException ex) {
        throw new CertificateException(ex);
    } finally {
        IOUtils.closeQuietly(pemReader);
    }
}
Also used : PEMParser(org.bouncycastle.openssl.PEMParser) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) StringReader(java.io.StringReader) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate)

Example 25 with X509CertificateHolder

use of org.bouncycastle.cert.X509CertificateHolder in project jmeter by apache.

the class SMIMEAssertion method verifySignature.

private static AssertionResult verifySignature(SMIMEAssertionTestElement testElement, SMIMESignedParser s, String name) throws CMSException {
    AssertionResult res = new AssertionResult(name);
    try {
        Store certs = s.getCertificates();
        SignerInformationStore signers = s.getSignerInfos();
        Iterator<?> signerIt = signers.getSigners().iterator();
        if (signerIt.hasNext()) {
            SignerInformation signer = (SignerInformation) signerIt.next();
            Iterator<?> certIt = certs.getMatches(signer.getSID()).iterator();
            if (certIt.hasNext()) {
                // the signer certificate
                X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
                if (testElement.isVerifySignature()) {
                    SignerInformationVerifier verifier = null;
                    try {
                        verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert);
                    } catch (OperatorCreationException e) {
                        log.error("Can't create a provider.", e);
                    }
                    if (verifier == null || !signer.verify(verifier)) {
                        res.setFailure(true);
                        res.setFailureMessage("Signature is invalid");
                    }
                }
                if (testElement.isSignerCheckConstraints()) {
                    StringBuilder failureMessage = new StringBuilder();
                    String serial = testElement.getSignerSerial();
                    if (!JOrphanUtils.isBlank(serial)) {
                        BigInteger serialNbr = readSerialNumber(serial);
                        if (!serialNbr.equals(cert.getSerialNumber())) {
                            res.setFailure(true);
                            failureMessage.append("Serial number ").append(serialNbr).append(" does not match serial from signer certificate: ").append(cert.getSerialNumber()).append("\n");
                        }
                    }
                    String email = testElement.getSignerEmail();
                    if (!JOrphanUtils.isBlank(email)) {
                        List<String> emailFromCert = getEmailFromCert(cert);
                        if (!emailFromCert.contains(email)) {
                            res.setFailure(true);
                            failureMessage.append("Email address \"").append(email).append("\" not present in signer certificate\n");
                        }
                    }
                    String subject = testElement.getSignerDn();
                    if (subject.length() > 0) {
                        final X500Name certPrincipal = cert.getSubject();
                        log.debug("DN from cert: {}", certPrincipal);
                        X500Name principal = new X500Name(subject);
                        log.debug("DN from assertion: {}", principal);
                        if (!principal.equals(certPrincipal)) {
                            res.setFailure(true);
                            failureMessage.append("Distinguished name of signer certificate does not match \"").append(subject).append("\"\n");
                        }
                    }
                    String issuer = testElement.getIssuerDn();
                    if (issuer.length() > 0) {
                        final X500Name issuerX500Name = cert.getIssuer();
                        log.debug("IssuerDN from cert: {}", issuerX500Name);
                        X500Name principal = new X500Name(issuer);
                        log.debug("IssuerDN from assertion: {}", principal);
                        if (!principal.equals(issuerX500Name)) {
                            res.setFailure(true);
                            failureMessage.append("Issuer distinguished name of signer certificate does not match \"").append(subject).append("\"\n");
                        }
                    }
                    if (failureMessage.length() > 0) {
                        res.setFailureMessage(failureMessage.toString());
                    }
                }
                if (testElement.isSignerCheckByFile()) {
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    try (InputStream fis = new FileInputStream(testElement.getSignerCertFile());
                        InputStream bis = new BufferedInputStream(fis)) {
                        X509CertificateHolder certFromFile = new JcaX509CertificateHolder((X509Certificate) cf.generateCertificate(bis));
                        if (!certFromFile.equals(cert)) {
                            res.setFailure(true);
                            res.setFailureMessage("Signer certificate does not match certificate " + testElement.getSignerCertFile());
                        }
                    } catch (IOException e) {
                        if (log.isDebugEnabled()) {
                            log.debug("Could not read cert file {}", testElement.getSignerCertFile(), e);
                        }
                        res.setFailure(true);
                        res.setFailureMessage("Could not read certificate file " + testElement.getSignerCertFile());
                    }
                }
            } else {
                res.setFailure(true);
                res.setFailureMessage("No signer certificate found in signature");
            }
        }
        // TODO support multiple signers
        if (signerIt.hasNext()) {
            log.warn("SMIME message contains multiple signers! Checking multiple signers is not supported.");
        }
    } catch (GeneralSecurityException e) {
        log.error(e.getMessage(), e);
        res.setError(true);
        res.setFailureMessage(e.getMessage());
    }
    return res;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) GeneralSecurityException(java.security.GeneralSecurityException) Store(org.bouncycastle.util.Store) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) SignerInformation(org.bouncycastle.cms.SignerInformation) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) X500Name(org.bouncycastle.asn1.x500.X500Name) IOException(java.io.IOException) CertificateFactory(java.security.cert.CertificateFactory) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) FileInputStream(java.io.FileInputStream) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) BufferedInputStream(java.io.BufferedInputStream) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) BigInteger(java.math.BigInteger) SignerInformationVerifier(org.bouncycastle.cms.SignerInformationVerifier) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException)

Aggregations

X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)29 X509Certificate (java.security.cert.X509Certificate)19 X500Name (org.bouncycastle.asn1.x500.X500Name)18 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)18 Date (java.util.Date)16 BigInteger (java.math.BigInteger)14 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)12 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)12 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)12 IOException (java.io.IOException)11 SecureRandom (java.security.SecureRandom)11 ContentSigner (org.bouncycastle.operator.ContentSigner)10 GeneralName (org.bouncycastle.asn1.x509.GeneralName)7 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)7 GeneralSecurityException (java.security.GeneralSecurityException)6 KeyPair (java.security.KeyPair)6 PrivateKey (java.security.PrivateKey)6 CertificateException (java.security.cert.CertificateException)6 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)6 Test (org.junit.Test)6