Example usage for org.bouncycastle.cms CMSSignedData CMSSignedData

List of usage examples for org.bouncycastle.cms CMSSignedData CMSSignedData

Introduction

In this page you can find the example usage for org.bouncycastle.cms CMSSignedData CMSSignedData.

Prototype

public CMSSignedData(Map hashes, ContentInfo sigData) throws CMSException 

Source Link

Usage

From source file:dorkbox.util.crypto.CryptoX509.java

License:Apache License

/**
 * Creates a NEW signature block that contains the pkcs7 (minus content, which is the .SF file)
 * signature of the .SF file./*w  w  w  .  j  a va  2 s. c  om*/
 *
 * It contains the hash of the data, and the verification signature.
 */
public static byte[] createSignature(byte[] signatureSourceData, X509CertificateHolder x509CertificateHolder,
        AsymmetricKeyParameter privateKey) {

    try {
        CMSTypedData content = new CMSProcessableByteArray(signatureSourceData);

        ASN1ObjectIdentifier contentTypeOID = new ASN1ObjectIdentifier(content.getContentType().getId());
        ASN1EncodableVector digestAlgs = new ASN1EncodableVector();
        ASN1EncodableVector signerInfos = new ASN1EncodableVector();

        AlgorithmIdentifier sigAlgId = x509CertificateHolder.getSignatureAlgorithm();
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

        // use the bouncy-castle lightweight API to generate a hash of the signature source data (usually the signature file bytes)
        BcContentSignerBuilder contentSignerBuilder;
        AlgorithmIdentifier digEncryptionAlgorithm;

        if (privateKey instanceof ECPrivateKeyParameters) {
            contentSignerBuilder = new BcECDSAContentSignerBuilder(sigAlgId, digAlgId);
            digEncryptionAlgorithm = new AlgorithmIdentifier(DSAUtil.dsaOids[0], null); // 1.2.840.10040.4.1  // DSA hashID
        } else if (privateKey instanceof DSAPrivateKeyParameters) {
            contentSignerBuilder = new BcDSAContentSignerBuilder(sigAlgId, digAlgId);
            digEncryptionAlgorithm = new AlgorithmIdentifier(DSAUtil.dsaOids[0], null); // 1.2.840.10040.4.1  // DSA hashID
        } else if (privateKey instanceof RSAPrivateCrtKeyParameters) {
            contentSignerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
            digEncryptionAlgorithm = new AlgorithmIdentifier(RSAUtil.rsaOids[0], null); // 1.2.840.113549.1.1.1 // RSA hashID
        } else {
            throw new RuntimeException("Invalid signature type. Only ECDSA, DSA, RSA supported.");
        }

        ContentSigner hashSigner = contentSignerBuilder.build(privateKey);
        OutputStream outputStream = hashSigner.getOutputStream();
        outputStream.write(signatureSourceData, 0, signatureSourceData.length);
        outputStream.flush();
        byte[] sigBytes = hashSigner.getSignature();

        SignerIdentifier sigId = new SignerIdentifier(
                new IssuerAndSerialNumber(x509CertificateHolder.toASN1Structure()));

        SignerInfo inf = new SignerInfo(sigId, digAlgId, null, digEncryptionAlgorithm,
                new DEROctetString(sigBytes), (ASN1Set) null);

        digestAlgs.add(inf.getDigestAlgorithm());
        signerInfos.add(inf);

        ASN1EncodableVector certs = new ASN1EncodableVector();
        certs.add(x509CertificateHolder.toASN1Structure());

        ContentInfo encInfo = new ContentInfo(contentTypeOID, null);
        SignedData sd = new SignedData(new DERSet(digestAlgs), encInfo, new BERSet(certs), null,
                new DERSet(signerInfos));

        ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.signedData, sd);
        CMSSignedData cmsSignedData2 = new CMSSignedData(content, contentInfo);

        return cmsSignedData2.getEncoded();
    } catch (Throwable t) {
        logger.error("Error signing data.", t);
        throw new RuntimeException("Error trying to sign data. " + t.getMessage());
    }
}

From source file:eu.betaas.service.securitymanager.capability.utils.CapabilityUtils.java

License:Apache License

/**
 * Method to verify exCap's signature with the issuer certificate stored in
 * the signed data // ww w .j  ava  2 s  . c  o m
 * @param text: the original signed text
 * @param signature: the signature in byte[]
 * @return: true if signature is valid, false otherwise
 * @throws CMSException
 * @throws OperatorException
 */
public static boolean validateCapSignature(String text, byte[] signature)
        throws CMSException, OperatorException {
    CMSSignedData signedData = new CMSSignedData(new CMSProcessableByteArray(text.getBytes()), signature);
    Store certs = signedData.getCertificates();
    SignerInformationStore signers = signedData.getSignerInfos();
    Iterator it = signers.getSigners().iterator();

    if (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        X509CertificateHolder cert = (X509CertificateHolder) certs.getMatches(signer.getSID()).iterator()
                .next();

        SignerInformationVerifier verifier = new BcECDSASignerInfoVerifierBuilder(
                new DefaultCMSSignatureAlgorithmNameGenerator(),
                new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(),
                new BcDigestCalculatorProvider()).build(cert);

        return signer.verify(verifier);
    }
    return false;
}

From source file:eu.betaas.service.securitymanager.capability.utils.CapabilityUtils.java

License:Apache License

/**
 * Method to verify exCap's signature for the detached signature or the issuer
 * certificate is not stored in the signed data 
 * @param text: the original signed text
 * @param signature: the signature in byte[]
 * @param cert: issuer certificate//from  w  ww  .  ja  va 2  s .c  om
 * @return: true if signature is valid, false otherwise
 * @throws CMSException
 * @throws OperatorException
 */
public static boolean validateCapSignature(String text, byte[] signature, X509CertificateHolder cert)
        throws CMSException, OperatorException {
    CMSSignedData signedData = new CMSSignedData(new CMSProcessableByteArray(text.getBytes()), signature);
    //      Store certs = signedData.getCertificates();
    SignerInformationStore signers = signedData.getSignerInfos();
    Iterator it = signers.getSigners().iterator();

    if (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        //      X509CertificateHolder cert = (X509CertificateHolder)certs.
        //            getMatches(signer.getSID()).iterator().next();

        SignerInformationVerifier verifier = new BcECDSASignerInfoVerifierBuilder(
                new DefaultCMSSignatureAlgorithmNameGenerator(),
                new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(),
                new BcDigestCalculatorProvider()).build(cert);

        return signer.verify(verifier);
    }

    return false;
}

From source file:eu.betaas.service.securitymanager.capability.utils.CapabilityUtils.java

License:Apache License

/**
 * Method to verify exCap's signature for the detached signature but the
 * signature is verified by the public key instead of the certificate
 * @param text: the original signed text
 * @param signature: the signature in byte[]
 * @param cert: issuer public key//from   w  w w . j a  v  a 2  s  .com
 * @return: true if signature is valid, false otherwise
 * @throws CMSException
 * @throws OperatorCreationException
 */
public static boolean validateCapSignature(String text, byte[] signature, AsymmetricKeyParameter pubKey)
        throws CMSException, OperatorCreationException {
    boolean ver = false;

    CMSSignedData signedData = new CMSSignedData(new CMSProcessableByteArray(text.getBytes()), signature);
    //      Store certs = signedData.getCertificates();
    SignerInformationStore signers = signedData.getSignerInfos();
    Iterator it = signers.getSigners().iterator();

    if (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        //     X509CertificateHolder cert = (X509CertificateHolder)certs.
        //           getMatches(signer.getSID()).iterator().next();

        SignerInformationVerifier verifier = new BcECDSASignerInfoVerifierBuilder(
                new DefaultCMSSignatureAlgorithmNameGenerator(),
                new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(),
                new BcDigestCalculatorProvider()).build(pubKey);

        log.debug("will now verify the signature...");

        ver = signer.verify(verifier);
    }

    log.debug("Signature verification result: " + ver);

    return ver;
}

From source file:io.aos.crypto.spl09.SignedDataExample.java

License:Apache License

public static void main(String... args) throws Exception {
    KeyStore credentials = Utils.createCredentials();
    PrivateKey key = (PrivateKey) credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD);
    Certificate[] chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS);
    CertStore certsAndCRLs = CertStore.getInstance("Collection",
            new CollectionCertStoreParameters(Arrays.asList(chain)), "BC");
    X509Certificate cert = (X509Certificate) chain[0];

    // set up the generator
    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

    gen.addSigner(key, cert, CMSSignedDataGenerator.DIGEST_SHA224);

    gen.addCertificatesAndCRLs(certsAndCRLs);

    // create the signed-data object
    CMSProcessable data = new CMSProcessableByteArray("Hello World!".getBytes());

    CMSSignedData signed = gen.generate(data, "BC");

    // recreate/*from  w  w w. j  a  v  a  2 s. com*/
    signed = new CMSSignedData(data, signed.getEncoded());

    // verification step
    X509Certificate rootCert = (X509Certificate) credentials.getCertificate(Utils.ROOT_ALIAS);

    if (isValid(signed, rootCert)) {
        System.out.println("verification succeeded");
    } else {
        System.out.println("verification failed");
    }
}

From source file:it.trento.comune.j4sign.cms.ExternalSignatureCMSSignedDataGenerator.java

License:Open Source License

/**
 * generate a CMS Signed Data object using the previously passed {@link ExternalSignatureSignerInfoGenerator}
 * objects; if encapsulate is true a copy of the message will be
 * included in the signature.//from  ww w.  j av a2 s  .co  m
 */
public CMSSignedData generate(CMSProcessable content, boolean encapsulate)

        throws NoSuchAlgorithmException, NoSuchProviderException, CMSException,
        InvalidAlgorithmParameterException, CertStoreException {

    //DEREncodableVector signerInfos = new DEREncodableVector();
    //DEREncodableVector digestAlgs = new DEREncodableVector();

    ASN1EncodableVector digestAlgs = new ASN1EncodableVector();
    ASN1EncodableVector signerInfos = new ASN1EncodableVector();

    ASN1ObjectIdentifier contentTypeOID = new ASN1ObjectIdentifier(CMSSignedDataGenerator.DATA);

    //
    // add the SignerInfo objects
    //
    Iterator it = signerInfs.iterator();

    //raccoglier i certificati dei firmatari
    //ArrayList certList = new ArrayList();

    while (it.hasNext()) {
        AlgorithmIdentifier digAlgId, encAlgId;
        ExternalSignatureSignerInfoGenerator externalSigner = (ExternalSignatureSignerInfoGenerator) it.next();
        try {
            digAlgId = makeAlgId(externalSigner.getDigestAlgOID(), externalSigner.getDigestAlgParams());

            digestAlgs.add(digAlgId);

            signerInfos.add(externalSigner.generate());

            //certList.add(externalSigner.getCertificate());
        } catch (IOException e) {
            throw new CMSException("encoding error.", e);
        } catch (CertificateEncodingException e) {
            throw new CMSException("error creating sid.", e);
        }
    }

    ASN1Set certificates = null;

    if (certs.size() != 0) {
        certificates = createBerSetFromList(certs);
    }
    /*
            if (certs.size() != 0) {
    DEREncodableVector v = new DEREncodableVector();
            
    it = certs.iterator();
    while (it.hasNext()) {
        v.add((DEREncodable) it.next());
    }
            
    certificates = new DERSet(v);
            }
    */
    ASN1Set certrevlist = null;

    if (crls.size() != 0) {
        certrevlist = createBerSetFromList(crls);
    }
    /*        
            if (crls.size() != 0) {
    DEREncodableVector v = new DEREncodableVector();
            
    it = crls.iterator();
    while (it.hasNext()) {
        v.add((DEREncodable) it.next());
    }
            
    certrevlist = new DERSet(v);
            }
    */

    ASN1OctetString octs = null;
    if (encapsulate) {

        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        try {
            content.write(bOut);
        } catch (IOException e) {
            throw new CMSException("encapsulation error.", e);
        }

        octs = new BERConstructedOctetString(bOut.toByteArray());

    }

    ContentInfo encInfo = new ContentInfo(contentTypeOID, octs);

    SignedData sd = new SignedData(new DERSet(digestAlgs), encInfo, certificates, certrevlist,
            new DERSet(signerInfos));

    ContentInfo contentInfo = new ContentInfo(PKCSObjectIdentifiers.signedData, sd);

    return new CMSSignedData(content, contentInfo);
}

From source file:net.jsign.asn1.authenticode.AuthenticodeSignedDataGenerator.java

License:Apache License

public CMSSignedData generate(ASN1ObjectIdentifier contentTypeOID, ASN1Encodable content)
        throws CMSException, IOException {
    digests.clear();/*from   w w  w  .j  a v a  2 s.c  om*/

    SignerInfo signerInfo;

    if (!_signers.isEmpty()) {
        signerInfo = ((SignerInformation) _signers.get(0)).toASN1Structure();
    } else {
        SignerInfoGenerator signerInfoGenerator = (SignerInfoGenerator) signerGens.get(0);

        byte[] signedContent = content.toASN1Primitive().getEncoded("DER");

        OutputStream out = signerInfoGenerator.getCalculatingOutputStream();
        out.write(signedContent, 2, signedContent.length - 2); // skip the first 2 bytes as specified
        out.flush();
        out.close();

        signerInfo = signerInfoGenerator.generate(contentTypeOID);

        byte[] calculatedDigest = signerInfoGenerator.getCalculatedDigest();
        digests.put(signerInfoGenerator.getDigestAlgorithm().getAlgorithm().getId(), calculatedDigest);
    }

    ContentInfo encInfo = new ContentInfo(contentTypeOID, content);
    ASN1Set certificates = new DERSet((ASN1Encodable[]) certs.toArray(new ASN1Encodable[0]));

    ASN1Encodable signedData = new AuthenticodeSignedData(signerInfo.getDigestAlgorithm(), encInfo,
            certificates, signerInfo);

    ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.signedData, signedData);

    return new CMSSignedData(
            new CMSProcessableByteArray(contentTypeOID, content.toASN1Primitive().getEncoded("DER")),
            contentInfo);
}

From source file:net.jsign.pe.CertificateTableEntry.java

License:Apache License

public CMSSignedData getSignature() throws CMSException {
    if (type != CertificateType.PKCS_SIGNED_DATA.getValue()) {
        throw new UnsupportedOperationException("Unsupported certificate type: " + type);
    }/*from  w  w w .j  a  v  a2 s. c o m*/

    if (revision != 0x0200) {
        throw new UnsupportedOperationException("Unsupported certificate revision: " + revision);
    }

    if (signature == null) {
        signature = new CMSSignedData((CMSProcessable) null, ContentInfo.getInstance(content));
    }

    return signature;
}

From source file:no.difi.oxalis.as2.util.SMimeBC.java

License:EUPL

/**
 * http://stackoverflow.com/a/31557473/135001
 *//*www .  j av a2  s  .c  o m*/
public static X509Certificate verifySignature(Map hashes, byte[] signature)
        throws OxalisSecurityException, OxalisAs2InboundException {
    try {
        CMSSignedData signedData = new CMSSignedData(hashes, signature);

        Store store = signedData.getCertificates();
        SignerInformationStore signerInformationStore = signedData.getSignerInfos();

        for (SignerInformation signerInformation : signerInformationStore.getSigners()) {
            Collection<X509CertificateHolder> certCollection = store.getMatches(signerInformation.getSID());

            Iterator<X509CertificateHolder> certificateIterator = certCollection.iterator();

            if (!certificateIterator.hasNext())
                throw new OxalisAs2InboundException(Disposition.AUTHENTICATION_FAILED,
                        "Unable to find certificate in signature.", null);

            X509CertificateHolder certificateHolder = certificateIterator.next();
            X509Certificate certificate = x509CertificateConverter.getCertificate(certificateHolder);

            SignerInformationVerifier verifier = getSignerInfoVerifierBuilder().build(certificate);

            if (signerInformation.verify(verifier))
                return certificate;
        }

        throw new OxalisSecurityException("Unable to verify signature.");
    } catch (CMSSignerDigestMismatchException e) {
        throw new OxalisSecurityException("Invalid message digest.", e);
    } catch (CMSException | CertificateException | OperatorCreationException e) {
        throw new OxalisSecurityException(e.getMessage(), e);
    }
}

From source file:org.apache.pdfbox.examples.pdmodel.TestCreateSignature.java

License:Apache License

private void checkSignature(File file)
        throws IOException, CMSException, OperatorCreationException, GeneralSecurityException {
    PDDocument document = PDDocument.load(file);
    List<PDSignature> signatureDictionaries = document.getSignatureDictionaries();
    if (signatureDictionaries.isEmpty()) {
        Assert.fail("no signature found");
    }// w ww  . j  ava2  s  .c o m
    for (PDSignature sig : document.getSignatureDictionaries()) {
        COSString contents = (COSString) sig.getCOSObject().getDictionaryObject(COSName.CONTENTS);

        FileInputStream fis = new FileInputStream(file);
        byte[] buf = sig.getSignedContent(fis);
        fis.close();

        // inspiration:
        // http://stackoverflow.com/a/26702631/535646
        // http://stackoverflow.com/a/9261365/535646
        CMSSignedData signedData = new CMSSignedData(new CMSProcessableByteArray(buf), contents.getBytes());
        Store certificatesStore = signedData.getCertificates();
        Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners();
        SignerInformation signerInformation = signers.iterator().next();
        Collection matches = certificatesStore.getMatches(signerInformation.getSID());
        X509CertificateHolder certificateHolder = (X509CertificateHolder) matches.iterator().next();
        X509Certificate certFromSignedData = new JcaX509CertificateConverter()
                .getCertificate(certificateHolder);

        Assert.assertEquals(certificate, certFromSignedData);

        // CMSVerifierCertificateNotValidException means that the keystore wasn't valid at signing time
        if (!signerInformation.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certFromSignedData))) {
            Assert.fail("Signature verification failed");
        }
        break;
    }
    document.close();
}