Search in sources :

Example 21 with JcaDigestCalculatorProviderBuilder

use of org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder in project serverless by bluenimble.

the class SignDocument method main.

public static void main(String[] args) throws IOException, CertificateException, UnrecoverableKeyException, KeyStoreException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, CertStoreException, CMSException, OperatorCreationException {
    File toBeSigned = new File("ToBeSigned.txt");
    byte[] buffer = new byte[(int) toBeSigned.length()];
    DataInputStream in = new DataInputStream(new FileInputStream(toBeSigned));
    in.readFully(buffer);
    in.close();
    // Chargement des certificats qui seront stockes dans le fichier .p7
    // Ici, seulement le certificat personnal_nyal.cer sera associe.
    // Par contre, la cha�ne des certificats non.
    X509Certificate cert = ReadX509.read(new FileInputStream("msp.cer"));
    // "2[$0wUOS";
    String password = "msp_pass";
    // "thawte freemail member's thawte consulting (pty) ltd. id";
    String alias = "msp";
    KeyInformation keyInfo = ReadPKCS12.read(new FileInputStream("msp.p12"), password, alias);
    // List<X509Certificate> certList = new ArrayList<X509Certificate> (); Wrong check below
    // certList.add (cert);
    List<X509CertificateHolder> certList = new ArrayList<X509CertificateHolder>();
    certList.add(new X509CertificateHolder(cert.getEncoded()));
    // CertStore certs = CertStore.getInstance ("Collection", new CollectionCertStoreParameters (certList), "BC"); Wrong check below
    JcaCertStore jcaCertStore = new JcaCertStore(certList);
    CMSSignedDataGenerator signGen = new CMSSignedDataGenerator();
    ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(keyInfo.getPrivateKey());
    DigestCalculatorProvider digestCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
    SignerInfoGenerator signInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(digestCalcProv).build(contentSigner, cert);
    signGen.addSignerInfoGenerator(signInfoGeneratorBuilder);
    // privatekey correspond a notre cle privee recuperee du fichier PKCS#12
    // cert correspond au certificat publique personnal_nyal.cer
    // Le dernier argument est l'algorithme de hachage qui sera utilise
    // signGen.addSigner (keyInfo.getPrivateKey (), cert, CMSSignedDataGenerator.DIGEST_SHA1);
    signGen.addCertificates(jcaCertStore);
    // Wrong signGen.addCertificatesAndCRLs (certs);
    CMSProcessableByteArray content = new CMSProcessableByteArray(buffer);
    // Generation du fichier CMS/PKCS#7
    // L'argument deux permet de signifier si le document doit etre attache avec la signature
    // Valeur true: le fichier est attache (c'est le cas ici)
    // Valeur false: le fichier est detache
    // CMSSignedData signedData = signGen.generate (content, true, "BC");
    CMSSignedData signedData = signGen.generate(content, true);
    byte[] signeddata = signedData.getEncoded();
    // Ecriture du buffer dans un fichier.
    FileOutputStream envfos = new FileOutputStream("Signed.pk7");
    envfos.write(signeddata);
    envfos.close();
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ArrayList(java.util.ArrayList) ContentSigner(org.bouncycastle.operator.ContentSigner) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) DataInputStream(java.io.DataInputStream) CMSSignedData(org.bouncycastle.cms.CMSSignedData) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) JcaSignerInfoGeneratorBuilder(org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder) DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) FileOutputStream(java.io.FileOutputStream) SignerInfoGenerator(org.bouncycastle.cms.SignerInfoGenerator) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) File(java.io.File)

Example 22 with JcaDigestCalculatorProviderBuilder

use of org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder in project serverless by bluenimble.

the class DefaultSigner method signWithCerts.

// Updated
private void signWithCerts(SecureDocument doc, PrivateKey key, X509Certificate[] certs) throws SignerException {
    if (certs == null || certs.length == 0) {
        throw new SignerException("A valid X509 Certificate is required");
    }
    String signAlg = "DSA".equals(key.getAlgorithm()) ? CMSSignedDataGenerator.DIGEST_SHA1 : CMSSignedDataGenerator.DIGEST_MD5;
    CMSSignedDataGenerator signGen = new CMSSignedDataGenerator();
    List<X509CertificateHolder> certList = new ArrayList<X509CertificateHolder>();
    try {
        ContentSigner contentSigner = new JcaContentSignerBuilder(signAlg).setProvider("BC").build(key);
        DigestCalculatorProvider digestCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
        for (X509Certificate cert : certs) {
            X509CertificateHolder certHolder = new X509CertificateHolder(cert.getEncoded());
            certList.add(certHolder);
            SignerInfoGenerator signInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(digestCalcProv).build(contentSigner, cert);
            signGen.addSignerInfoGenerator(signInfoGeneratorBuilder);
        }
        JcaCertStore jcaCertStore = new JcaCertStore(certList);
        signGen.addCertificates(jcaCertStore);
        // signGen.addCRLs (jcaCertStore); TODO : not sure
        CMSProcessableByteArray content = new CMSProcessableByteArray(doc.getBytes());
        CMSSignedData signedData = signGen.generate(content, true);
        doc.setBytes(signedData.getEncoded());
    } catch (Throwable th) {
        throw new SignerException(th, th.getMessage());
    }
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ArrayList(java.util.ArrayList) ContentSigner(org.bouncycastle.operator.ContentSigner) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) JcaSignerInfoGeneratorBuilder(org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder) DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) SignerInfoGenerator(org.bouncycastle.cms.SignerInfoGenerator) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) SignerException(com.bluenimble.platform.crypto.signer.SignerException)

Example 23 with JcaDigestCalculatorProviderBuilder

use of org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder in project keycloak by keycloak.

the class OcspHandler method handleRequest.

@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }
    final byte[] buffy = new byte[16384];
    try (InputStream requestStream = exchange.getInputStream()) {
        requestStream.read(buffy);
    }
    final OCSPReq request = new OCSPReq(buffy);
    final Req[] requested = request.getRequestList();
    final Extension nonce = request.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
    final DigestCalculator sha1Calculator = new JcaDigestCalculatorProviderBuilder().build().get(AlgorithmIdentifier.getInstance(RespID.HASH_SHA1));
    final BasicOCSPRespBuilder responseBuilder = new BasicOCSPRespBuilder(subjectPublicKeyInfo, sha1Calculator);
    if (nonce != null) {
        responseBuilder.setResponseExtensions(new Extensions(nonce));
    }
    for (final Req req : requested) {
        final CertificateID certId = req.getCertID();
        final BigInteger certificateSerialNumber = certId.getSerialNumber();
        responseBuilder.addResponse(certId, REVOKED_CERTIFICATES_STATUS.get(certificateSerialNumber));
    }
    final ContentSigner contentSigner = new BcRSAContentSignerBuilder(new AlgorithmIdentifier(PKCSObjectIdentifiers.sha256WithRSAEncryption), new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256)).build(privateKey);
    final OCSPResp response = new OCSPRespBuilder().build(OCSPResp.SUCCESSFUL, responseBuilder.build(contentSigner, chain, new Date()));
    final byte[] responseBytes = response.getEncoded();
    final HeaderMap responseHeaders = exchange.getResponseHeaders();
    responseHeaders.put(Headers.CONTENT_TYPE, "application/ocsp-response");
    final Sender responseSender = exchange.getResponseSender();
    responseSender.send(ByteBuffer.wrap(responseBytes));
    exchange.endExchange();
}
Also used : BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) OCSPRespBuilder(org.bouncycastle.cert.ocsp.OCSPRespBuilder) InputStream(java.io.InputStream) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) DigestCalculator(org.bouncycastle.operator.DigestCalculator) ContentSigner(org.bouncycastle.operator.ContentSigner) Extensions(org.bouncycastle.asn1.x509.Extensions) Date(java.util.Date) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) Extension(org.bouncycastle.asn1.x509.Extension) Sender(io.undertow.io.Sender) BcRSAContentSignerBuilder(org.bouncycastle.operator.bc.BcRSAContentSignerBuilder) BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) HeaderMap(io.undertow.util.HeaderMap) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) Req(org.bouncycastle.cert.ocsp.Req) OCSPReq(org.bouncycastle.cert.ocsp.OCSPReq)

Example 24 with JcaDigestCalculatorProviderBuilder

use of org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder in project fdroidclient by f-droid.

the class SignatureBlockGenerator method generate.

/**
 * Sign the given content using the private and public keys from the keySet, and return the encoded CMS (PKCS#7) data.
 * Use of direct signature and DER encoding produces a block that is verifiable by Android recovery programs.
 */
public static byte[] generate(KeySet keySet, byte[] content) {
    try {
        List certList = new ArrayList();
        CMSTypedData msg = new CMSProcessableByteArray(content);
        certList.add(keySet.getPublicKey());
        Store certs = new JcaCertStore(certList);
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        JcaContentSignerBuilder jcaContentSignerBuilder = new JcaContentSignerBuilder(keySet.getSignatureAlgorithm()).setProvider("BC");
        ContentSigner sha1Signer = jcaContentSignerBuilder.build(keySet.getPrivateKey());
        JcaDigestCalculatorProviderBuilder jcaDigestCalculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder().setProvider("BC");
        DigestCalculatorProvider digestCalculatorProvider = jcaDigestCalculatorProviderBuilder.build();
        JcaSignerInfoGeneratorBuilder jcaSignerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(digestCalculatorProvider);
        jcaSignerInfoGeneratorBuilder.setDirectSignature(true);
        SignerInfoGenerator signerInfoGenerator = jcaSignerInfoGeneratorBuilder.build(sha1Signer, keySet.getPublicKey());
        gen.addSignerInfoGenerator(signerInfoGenerator);
        gen.addCertificates(certs);
        CMSSignedData sigData = gen.generate(msg, false);
        return sigData.toASN1Structure().getEncoded("DER");
    } catch (Exception x) {
        throw new RuntimeException(x.getMessage(), x);
    }
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) CMSTypedData(org.bouncycastle.cms.CMSTypedData) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ArrayList(java.util.ArrayList) ContentSigner(org.bouncycastle.operator.ContentSigner) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) Store(org.bouncycastle.util.Store) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) CMSSignedData(org.bouncycastle.cms.CMSSignedData) JcaSignerInfoGeneratorBuilder(org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder) DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) SignerInfoGenerator(org.bouncycastle.cms.SignerInfoGenerator) ArrayList(java.util.ArrayList) List(java.util.List) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder)

Example 25 with JcaDigestCalculatorProviderBuilder

use of org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder in project wso2-synapse by wso2.

the class OCSPVerifier method generateOCSPRequest.

/**
 * This method generates an OCSP Request to be sent to an OCSP endpoint.
 *
 * @param issuerCert   is the Certificate of the Issuer of the peer certificate we are interested in.
 * @param serialNumber of the peer certificate.
 * @return generated OCSP request.
 * @throws CertificateVerificationException
 */
private OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber) throws CertificateVerificationException {
    // TODO: Have to check if this is OK with synapse implementation.
    // Add provider BC
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    try {
        byte[] issuerCertEnc = issuerCert.getEncoded();
        X509CertificateHolder certificateHolder = new X509CertificateHolder(issuerCertEnc);
        DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().setProvider(BC).build();
        // CertID structure is used to uniquely identify certificates that are the subject of
        // an OCSP request or response and has an ASN.1 definition. CertID structure is defined in RFC 2560
        CertificateID id = new CertificateID(digCalcProv.get(CertificateID.HASH_SHA1), certificateHolder, serialNumber);
        // basic request generation with nonce
        OCSPReqBuilder builder = new OCSPReqBuilder();
        builder.addRequest(id);
        // create details for nonce extension. The nonce extension is used to bind
        // a request to a response to prevent replay attacks. As the name implies,
        // the nonce value is something that the client should only use once within a reasonably small period.
        BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
        // to create the request Extension
        builder.setRequestExtensions(new Extensions(new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(nonce.toByteArray()))));
        return builder.build();
    } catch (Exception e) {
        throw new CertificateVerificationException("Cannot generate OSCP Request with the given certificate", e);
    }
}
Also used : DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder)

Aggregations

JcaDigestCalculatorProviderBuilder (org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder)25 X509Certificate (java.security.cert.X509Certificate)16 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)16 ContentSigner (org.bouncycastle.operator.ContentSigner)15 JcaCertStore (org.bouncycastle.cert.jcajce.JcaCertStore)13 CMSSignedData (org.bouncycastle.cms.CMSSignedData)13 CMSSignedDataGenerator (org.bouncycastle.cms.CMSSignedDataGenerator)13 ArrayList (java.util.ArrayList)12 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)12 JcaSignerInfoGeneratorBuilder (org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder)12 DigestCalculatorProvider (org.bouncycastle.operator.DigestCalculatorProvider)11 IOException (java.io.IOException)9 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)9 CertificateID (org.bouncycastle.cert.ocsp.CertificateID)8 CMSProcessableByteArray (org.bouncycastle.cms.CMSProcessableByteArray)8 BigInteger (java.math.BigInteger)7 BasicOCSPResp (org.bouncycastle.cert.ocsp.BasicOCSPResp)7 OCSPReq (org.bouncycastle.cert.ocsp.OCSPReq)7 OCSPResp (org.bouncycastle.cert.ocsp.OCSPResp)7 DigestCalculator (org.bouncycastle.operator.DigestCalculator)7