Example usage for org.bouncycastle.operator.bc BcDigestCalculatorProvider BcDigestCalculatorProvider

List of usage examples for org.bouncycastle.operator.bc BcDigestCalculatorProvider BcDigestCalculatorProvider

Introduction

In this page you can find the example usage for org.bouncycastle.operator.bc BcDigestCalculatorProvider BcDigestCalculatorProvider.

Prototype

BcDigestCalculatorProvider

Source Link

Usage

From source file:ch.swisscom.mid.verifier.MobileIdCmsVerifier.java

License:Open Source License

/**
 * Verify the signature on the SignerInformation object
 * /*from   w  w  w. ja v  a  2 s  .  c  o  m*/
 * @return true if the signer information is verified, false otherwise.
 * @throws OperatorCreationException
 * @throws CMSException
 */
private boolean isVerified() throws OperatorCreationException, CMSException {
    // Verify that the given verifier can successfully verify the signature on this SignerInformation object
    SignerInformationVerifier verifier = new BcRSASignerInfoVerifierBuilder(
            new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(),
            new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider())
                    .build(x509CertHolder);
    return signerInfo.verify(verifier);
}

From source file:com.enioka.jqm.pki.CertificateRequest.java

License:Open Source License

private void generateX509() throws Exception {
    SecureRandom random = new SecureRandom();
    X500Name dnName = new X500Name(Subject);
    Calendar endValidity = Calendar.getInstance();
    endValidity.add(Calendar.YEAR, validityYear);

    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());

    X509v3CertificateBuilder gen = new X509v3CertificateBuilder(
            authorityCertificate == null ? dnName : authorityCertificate.getSubject(),
            BigIntegers.createRandomInRange(BigInteger.ZERO, BigInteger.valueOf(Long.MAX_VALUE), random),
            new Date(), endValidity.getTime(), dnName, publicKeyInfo);

    // Public key ID
    DigestCalculator digCalc = new BcDigestCalculatorProvider()
            .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
    X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc);
    gen.addExtension(Extension.subjectKeyIdentifier, false,
            x509ExtensionUtils.createSubjectKeyIdentifier(publicKeyInfo));

    // EKU/*from  ww w.ja va 2 s . c o m*/
    gen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU));

    // Basic constraints (is CA?)
    if (authorityCertificate == null) {
        gen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
    }

    // Key usage
    gen.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsage));

    // Subject Alt names ?

    // Authority
    if (authorityCertificate != null) {
        gen.addExtension(Extension.authorityKeyIdentifier, false,
                new AuthorityKeyIdentifier(authorityCertificate.getSubjectPublicKeyInfo()));
    }

    // Signer
    ContentSigner signer = new JcaContentSignerBuilder("SHA512WithRSAEncryption")
            .setProvider(Constants.JCA_PROVIDER).build(authorityKey == null ? privateKey : authorityKey);

    // Go
    holder = gen.build(signer);
}

From source file:com.itextpdf.signatures.SignUtils.java

License:Open Source License

static boolean checkIfIssuersMatch(CertificateID certID, X509Certificate issuerCert)
        throws CertificateEncodingException, IOException, OCSPException {
    return certID.matchesIssuer(new X509CertificateHolder(issuerCert.getEncoded()),
            new BcDigestCalculatorProvider());
}

From source file:com.itextpdf.text.pdf.security.OCSPVerifier.java

License:Open Source License

/**
 * Verifies a certificate against a single OCSP response
 * @param ocspResp   the OCSP response//from   w ww. j a  va  2  s .c o  m
 * @param serialNumber   the serial number of the certificate that needs to be checked
 * @param issuerCert
 * @param signDate
 * @return
 * @throws GeneralSecurityException
 * @throws IOException
 */
public boolean verify(BasicOCSPResp ocspResp, X509Certificate signCert, X509Certificate issuerCert,
        Date signDate) throws GeneralSecurityException, IOException {
    if (ocspResp == null)
        return false;
    // Getting the responses
    SingleResp[] resp = ocspResp.getResponses();
    for (int i = 0; i < resp.length; i++) {
        // check if the serial number corresponds
        if (!signCert.getSerialNumber().equals(resp[i].getCertID().getSerialNumber())) {
            continue;
        }
        // check if the issuer matches
        try {
            if (issuerCert == null)
                issuerCert = signCert;
            if (!resp[i].getCertID().matchesIssuer(new X509CertificateHolder(issuerCert.getEncoded()),
                    new BcDigestCalculatorProvider())) {
                LOGGER.info("OCSP: Issuers doesn't match.");
                continue;
            }
        } catch (OCSPException e) {
            continue;
        }
        // check if the OCSP response was valid at the time of signing
        Date nextUpdate = resp[i].getNextUpdate();
        if (nextUpdate == null) {
            nextUpdate = new Date(resp[i].getThisUpdate().getTime() + 180000l);
            LOGGER.info(String.format("No 'next update' for OCSP Response; assuming %s", nextUpdate));
        }
        if (signDate.after(nextUpdate)) {
            LOGGER.info(String.format("OCSP no longer valid: %s after %s", signDate, nextUpdate));
            continue;
        }
        // check the status of the certificate
        Object status = resp[i].getCertStatus();
        if (status == CertificateStatus.GOOD) {
            // check if the OCSP response was genuine
            isValidResponse(ocspResp, issuerCert);
            return true;
        }
    }
    return false;
}

From source file:com.spotify.helios.client.tls.X509CertificateFactory.java

License:Apache License

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 {/* w ww. ja  v  a 2 s  . c  om*/
        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);
    }
}

From source file:com.spotify.sshagenttls.X509CertKeyCreator.java

License:Apache License

@Override
public CertKey createCertKey(final String username, final X500Principal x500Principal) {
    final Calendar calendar = Calendar.getInstance();
    final BigInteger serialNumber = BigInteger.valueOf(calendar.getTimeInMillis()).abs();
    final X500Name issuerDn = new X500Name(x500Principal.getName(X500Principal.RFC1779));
    final X500Name subjectDn = new X500NameBuilder().addRDN(BCStyle.UID, username).build();

    calendar.add(Calendar.MILLISECOND, -validBeforeMillis);
    final Date notBefore = calendar.getTime();

    calendar.add(Calendar.MILLISECOND, validBeforeMillis + validAfterMillis);
    final Date notAfter = calendar.getTime();

    try {//from   ww w  .j a va  2s. c  o m
        final KeyPair keyPair = generateRandomKeyPair();
        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 X.509 certificate for {} with key ID={}", username, keyIdHex);

        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(contentSigner);

        final X509Certificate cert = CERT_CONVERTER.getCertificate(holder);
        LOG.debug("generated certificate:\n{}", Utils.asPemString(cert));

        return CertKey.create(cert, keyPair.getPrivate());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.spotify.sshtlsclient.X509CertificateFactory.java

License:Apache License

static Certificate get(final SshAgentContentSigner signer, 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();
    final SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo
            .getInstance(ASN1Sequence.getInstance(identity.getPublicKey().getEncoded()));

    calendar.add(Calendar.HOUR, -HOURS_BEFORE);
    final Date notBefore = calendar.getTime();

    calendar.add(Calendar.HOUR, HOURS_BEFORE + HOURS_AFTER);
    final Date notAfter = calendar.getTime();

    // Reuse the UUID time as a SN
    final BigInteger serialNumber = BigInteger.valueOf(uuid.getTime()).abs();

    final X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuerDN, serialNumber, notBefore,
            notAfter, subjectDN, subjectPublicKeyInfo);

    try {/*from  ww w  .  ja va2s .  c o m*/
        final DigestCalculator digestCalculator = new BcDigestCalculatorProvider()
                .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
        final X509ExtensionUtils utils = new X509ExtensionUtils(digestCalculator);

        builder.addExtension(Extension.subjectKeyIdentifier, false,
                utils.createSubjectKeyIdentifier(subjectPublicKeyInfo));
        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(signer);

        return new Certificate(new org.bouncycastle.asn1.x509.Certificate[] { holder.toASN1Structure(), });
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.tremolosecurity.proxy.auth.ssl.OCSP.java

License:Apache License

private OCSPReq generateOcspRequest(X509Certificate issuerCert, BigInteger serialNumber)
        throws OCSPException, CertificateEncodingException, OperatorCreationException, IOException {

    BcDigestCalculatorProvider util = new BcDigestCalculatorProvider();

    // Generate the id for the certificate we are looking for
    CertificateID id = new CertificateID(util.get(CertificateID.HASH_SHA1),
            new X509CertificateHolder(issuerCert.getEncoded()), serialNumber);
    OCSPReqBuilder ocspGen = new OCSPReqBuilder();

    ocspGen.addRequest(id);//from   w  w  w .  j a v a2s.  com

    BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
    Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true,
            new DEROctetString(nonce.toByteArray()));
    ocspGen.setRequestExtensions(new Extensions(new Extension[] { ext }));

    return ocspGen.build();
}

From source file:com.wewebu.ow.server.util.jar.OwJarVerifier.java

License:Open Source License

/**
 * Get Signature Certificates/*from   w  w w.  ja  va  2 s.  c o  m*/
 * @return {@link X509Certificate}[]
 * @throws IOException
 * @throws CMSException 
 */
@SuppressWarnings("rawtypes")
public X509CertificateHolder[] getSignatureCertificates() throws IOException, CMSException {
    JarEntry signatureBlockEntry = getSignatureBlockEntry();
    if (null != signatureBlockEntry) {
        InputStream inputStream = null;
        try {
            inputStream = jarFile.getInputStream(signatureBlockEntry);
            CMSSignedDataParser sp = new CMSSignedDataParser(new BcDigestCalculatorProvider(),
                    new BufferedInputStream(inputStream, 1024));
            Store certStore = sp.getCertificates();
            SignerInformationStore signers = sp.getSignerInfos();

            Collection c = signers.getSigners();
            Iterator it = c.iterator();

            List<X509CertificateHolder> certificates = new ArrayList<X509CertificateHolder>();
            while (it.hasNext()) {
                SignerInformation signer = (SignerInformation) it.next();
                Collection certCollection = certStore.getMatches(signer.getSID());

                Iterator certIt = certCollection.iterator();
                X509CertificateHolder cert = (X509CertificateHolder) certIt.next();

                certificates.add(cert);
            }

            return certificates.toArray(new X509CertificateHolder[certificates.size()]);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ex) {
                }
            }
            inputStream = null;
        }
    }
    return new X509CertificateHolder[] {};
}

From source file:de.mendelson.util.security.BCCryptoHelper.java

/**
 * Verifies a signature of a passed content against the passed certificate
 *///from ww  w .  j a  v a  2  s .c  o  m
public boolean verify(byte[] content, byte[] signature, Certificate cert) throws Exception {
    if (content == null) {
        throw new GeneralSecurityException("verify: Content is absent");
    }
    if (signature == null) {
        throw new GeneralSecurityException("verify: Signature is absent");
    }
    if (signature.length == 0) {
        throw new Exception("verify: Signature length is 0");
    }
    CMSTypedStream signedContent = new CMSTypedStream(new ByteArrayInputStream(content));
    CMSSignedDataParser dataParser = new CMSSignedDataParser(new BcDigestCalculatorProvider(), signedContent,
            new ByteArrayInputStream(signature));
    dataParser.getSignedContent().drain();
    SignerInformationStore signers = dataParser.getSignerInfos();
    Collection signerCollection = signers.getSigners();
    Iterator it = signerCollection.iterator();
    X509CertificateHolder certHolder = new X509CertificateHolder(cert.getEncoded());
    SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC")
            .build(certHolder);
    boolean verified = false;
    while (it.hasNext()) {
        SignerInformation signerInformation = (SignerInformation) it.next();
        if (!verified) {
            verified = signerInformation.verify(verifier);
        }
        if (verified) {
            break;
        }
    }
    return (verified);
}