Search in sources :

Example 6 with DigestCalculatorProvider

use of org.bouncycastle.operator.DigestCalculatorProvider in project felix by apache.

the class DPSigner method calculateSignatureBlock.

private byte[] calculateSignatureBlock(PrivateKey privKey, X509Certificate cert, byte[] sfRawBytes) throws Exception {
    String signatureAlgorithm = getSignatureAlgorithm(privKey);
    DigestCalculatorProvider digestCalculatorProvider = new JcaDigestCalculatorProviderBuilder().build();
    ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(privKey);
    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(digestCalculatorProvider).build(signer, cert));
    gen.addCertificates(new JcaCertStore(Arrays.asList(cert)));
    CMSSignedData sigData = gen.generate(new CMSProcessableByteArray(sfRawBytes));
    return sigData.getEncoded();
}
Also used : CMSSignedDataGenerator(org.bouncycastle.cms.CMSSignedDataGenerator) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) JcaSignerInfoGeneratorBuilder(org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder) DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) JcaCertStore(org.bouncycastle.cert.jcajce.JcaCertStore) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) CMSSignedData(org.bouncycastle.cms.CMSSignedData)

Example 7 with DigestCalculatorProvider

use of org.bouncycastle.operator.DigestCalculatorProvider 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)

Example 8 with DigestCalculatorProvider

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

the class OCSPBasicResponse method sign.

@JRubyMethod(name = "sign", rest = true)
public IRubyObject sign(final ThreadContext context, IRubyObject[] args) {
    Ruby runtime = context.getRuntime();
    int flag = 0;
    IRubyObject additionalCerts = context.nil;
    IRubyObject flags = context.nil;
    IRubyObject digest = context.nil;
    Digest digestInstance = new Digest(runtime, _Digest(runtime));
    List<X509CertificateHolder> addlCerts = new ArrayList<X509CertificateHolder>();
    switch(Arity.checkArgumentCount(runtime, args, 2, 5)) {
        case 3:
            additionalCerts = args[2];
            break;
        case 4:
            additionalCerts = args[2];
            flags = args[3];
            break;
        case 5:
            additionalCerts = args[2];
            flags = args[3];
            digest = args[4];
            break;
        default:
            break;
    }
    if (digest.isNil())
        digest = digestInstance.initialize(context, new IRubyObject[] { RubyString.newString(runtime, "SHA1") });
    if (!flags.isNil())
        flag = RubyFixnum.fix2int(flags);
    if (additionalCerts.isNil())
        flag |= RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOCERTS));
    X509Cert signer = (X509Cert) args[0];
    PKey signerKey = (PKey) args[1];
    String keyAlg = signerKey.getAlgorithm();
    String digAlg = ((Digest) digest).getShortAlgorithm();
    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(digAlg + "with" + keyAlg);
    signerBuilder.setProvider("BC");
    ContentSigner contentSigner = null;
    try {
        contentSigner = signerBuilder.build(signerKey.getPrivateKey());
    } catch (OperatorCreationException e) {
        throw newOCSPError(runtime, e);
    }
    BasicOCSPRespBuilder respBuilder = null;
    try {
        if ((flag & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_RESPID_KEY))) != 0) {
            JcaDigestCalculatorProviderBuilder dcpb = new JcaDigestCalculatorProviderBuilder();
            dcpb.setProvider("BC");
            DigestCalculatorProvider dcp = dcpb.build();
            DigestCalculator calculator = dcp.get(contentSigner.getAlgorithmIdentifier());
            respBuilder = new BasicOCSPRespBuilder(SubjectPublicKeyInfo.getInstance(signerKey.getPublicKey().getEncoded()), calculator);
        } else {
            respBuilder = new BasicOCSPRespBuilder(new RespID(signer.getSubject().getX500Name()));
        }
    } catch (Exception e) {
        throw newOCSPError(runtime, e);
    }
    X509CertificateHolder[] chain = null;
    try {
        if ((flag & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOCERTS))) == 0) {
            addlCerts.add(new X509CertificateHolder(signer.getAuxCert().getEncoded()));
            if (!additionalCerts.isNil()) {
                Iterator<java.security.cert.Certificate> rubyAddlCerts = ((RubyArray) additionalCerts).iterator();
                while (rubyAddlCerts.hasNext()) {
                    java.security.cert.Certificate cert = rubyAddlCerts.next();
                    addlCerts.add(new X509CertificateHolder(cert.getEncoded()));
                }
            }
            chain = addlCerts.toArray(new X509CertificateHolder[addlCerts.size()]);
        }
    } catch (Exception e) {
        throw newOCSPError(runtime, e);
    }
    Date producedAt = null;
    if ((flag & RubyFixnum.fix2int((RubyFixnum) _OCSP(runtime).getConstant(OCSP_NOTIME))) == 0) {
        producedAt = new Date();
    }
    for (OCSPSingleResponse resp : singleResponses) {
        SingleResp singleResp = new SingleResp(resp.getBCSingleResp());
        respBuilder.addResponse(singleResp.getCertID(), singleResp.getCertStatus(), singleResp.getThisUpdate(), singleResp.getNextUpdate(), resp.getBCSingleResp().getSingleExtensions());
    }
    try {
        Extension[] respExtAry = new Extension[extensions.size()];
        Extensions respExtensions = new Extensions(extensions.toArray(respExtAry));
        BasicOCSPResp bcBasicOCSPResp = respBuilder.setResponseExtensions(respExtensions).build(contentSigner, chain, producedAt);
        asn1BCBasicOCSPResp = BasicOCSPResponse.getInstance(bcBasicOCSPResp.getEncoded());
    } catch (Exception e) {
        throw newOCSPError(runtime, e);
    }
    return this;
}
Also used : RubyArray(org.jruby.RubyArray) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ArrayList(java.util.ArrayList) DigestCalculator(org.bouncycastle.operator.DigestCalculator) RubyString(org.jruby.RubyString) IRubyObject(org.jruby.runtime.builtin.IRubyObject) Extensions(org.bouncycastle.asn1.x509.Extensions) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) Ruby(org.jruby.Ruby) SingleResp(org.bouncycastle.cert.ocsp.SingleResp) Digest._Digest(org.jruby.ext.openssl.Digest._Digest) MessageDigest(java.security.MessageDigest) ContentSigner(org.bouncycastle.operator.ContentSigner) RubyFixnum(org.jruby.RubyFixnum) RaiseException(org.jruby.exceptions.RaiseException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CertificateEncodingException(java.security.cert.CertificateEncodingException) CertificateParsingException(java.security.cert.CertificateParsingException) IOException(java.io.IOException) Date(java.util.Date) Extension(org.bouncycastle.asn1.x509.Extension) BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) RespID(org.bouncycastle.cert.ocsp.RespID) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) X509AuxCertificate(org.jruby.ext.openssl.x509store.X509AuxCertificate) JRubyMethod(org.jruby.anno.JRubyMethod)

Example 9 with DigestCalculatorProvider

use of org.bouncycastle.operator.DigestCalculatorProvider 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 10 with DigestCalculatorProvider

use of org.bouncycastle.operator.DigestCalculatorProvider 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)

Aggregations

DigestCalculatorProvider (org.bouncycastle.operator.DigestCalculatorProvider)11 JcaDigestCalculatorProviderBuilder (org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder)10 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)7 X509Certificate (java.security.cert.X509Certificate)5 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)5 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)5 ArrayList (java.util.ArrayList)4 JcaCertStore (org.bouncycastle.cert.jcajce.JcaCertStore)4 CMSProcessableByteArray (org.bouncycastle.cms.CMSProcessableByteArray)4 CMSSignedData (org.bouncycastle.cms.CMSSignedData)4 CMSSignedDataGenerator (org.bouncycastle.cms.CMSSignedDataGenerator)4 JcaSignerInfoGeneratorBuilder (org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder)4 ContentSigner (org.bouncycastle.operator.ContentSigner)4 IOException (java.io.IOException)3 BigInteger (java.math.BigInteger)3 SignerInfoGenerator (org.bouncycastle.cms.SignerInfoGenerator)3 DigestCalculator (org.bouncycastle.operator.DigestCalculator)3 FileInputStream (java.io.FileInputStream)2 InputStream (java.io.InputStream)2 MessageDigest (java.security.MessageDigest)2