Search in sources :

Example 26 with CMSSignedData

use of org.bouncycastle.cms.CMSSignedData in project signer by demoiselle.

the class CAdESSigner method validateTimestamp.

/**
 *  validade a timestampo on signature
 * @param attributeTimeStamp
 * @param varSignature
 * @return
 */
@Deprecated
private Timestamp validateTimestamp(Attribute attributeTimeStamp, byte[] varSignature) {
    try {
        TimeStampOperator timeStampOperator = new TimeStampOperator();
        byte[] varTimeStamp = attributeTimeStamp.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded();
        TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp));
        Timestamp timeStampSigner = new Timestamp(timeStampToken);
        timeStampOperator.validate(varSignature, varTimeStamp, null);
        return timeStampSigner;
    } catch (CertificateCoreException | IOException | TSPException | CMSException e) {
        throw new SignerException(e);
    }
}
Also used : TimeStampOperator(org.demoiselle.signer.timestamp.connector.TimeStampOperator) IOException(java.io.IOException) TSPException(org.bouncycastle.tsp.TSPException) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) CMSSignedData(org.bouncycastle.cms.CMSSignedData) Timestamp(org.demoiselle.signer.timestamp.Timestamp) SignerException(org.demoiselle.signer.policy.impl.cades.SignerException) CertificateCoreException(org.demoiselle.signer.core.exception.CertificateCoreException) CMSException(org.bouncycastle.cms.CMSException)

Example 27 with CMSSignedData

use of org.bouncycastle.cms.CMSSignedData in project signer by demoiselle.

the class TimeStampOperator method validate.

/**
 * Validate a time stamp
 *
 * @param content if it is assigned, the parameter hash must to be null
 * @param timeStamp timestamp to be validated
 * @param hash if it is assigned, the parameter content must to be null
 * @throws CertificateCoreException validate exception
 */
@SuppressWarnings("unchecked")
public void validate(byte[] content, byte[] timeStamp, byte[] hash) throws CertificateCoreException {
    try {
        TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(timeStamp));
        CMSSignedData s = timeStampToken.toCMSSignedData();
        int verified = 0;
        Store<?> certStore = s.getCertificates();
        SignerInformationStore signers = s.getSignerInfos();
        Collection<SignerInformation> c = signers.getSigners();
        Iterator<SignerInformation> it = c.iterator();
        while (it.hasNext()) {
            SignerInformation signer = it.next();
            Collection<?> certCollection = certStore.getMatches(signer.getSID());
            Iterator<?> certIt = certCollection.iterator();
            X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
            if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) {
                verified++;
            }
            cert.getExtension(new ASN1ObjectIdentifier("2.5.29.31")).getExtnValue();
        }
        logger.info(timeStampMessagesBundle.getString("info.signature.verified", verified));
        // Valida o hash  incluso no carimbo de tempo com hash do arquivo carimbado
        byte[] calculatedHash = null;
        if (content != null) {
            Digest digest = DigestFactory.getInstance().factoryDefault();
            digest.setAlgorithm(DigestAlgorithmEnum.SHA_256);
            calculatedHash = digest.digest(content);
        } else {
            calculatedHash = hash;
        }
        if (Arrays.equals(calculatedHash, timeStampToken.getTimeStampInfo().getMessageImprintDigest())) {
            logger.info(timeStampMessagesBundle.getString("info.timestamp.hash.ok"));
        } else {
            throw new CertificateCoreException(timeStampMessagesBundle.getString("info.timestamp.hash.nok"));
        }
    } catch (TSPException | IOException | CMSException | OperatorCreationException | CertificateException ex) {
        throw new CertificateCoreException(ex.getMessage());
    }
}
Also used : Digest(org.demoiselle.signer.cryptography.Digest) SignerInformation(org.bouncycastle.cms.SignerInformation) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CertificateCoreException(org.demoiselle.signer.core.exception.CertificateCoreException) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) TSPException(org.bouncycastle.tsp.TSPException) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) CMSException(org.bouncycastle.cms.CMSException)

Example 28 with CMSSignedData

use of org.bouncycastle.cms.CMSSignedData in project serverless by bluenimble.

the class VerifyDocument method main.

public static void main(String[] args) throws IOException, CertificateException, UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException, CertStoreException, CMSException, OperatorCreationException {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    File f = new File("Signed.pk7");
    byte[] buffer = new byte[(int) f.length()];
    DataInputStream in = new DataInputStream(new FileInputStream(f));
    in.readFully(buffer);
    in.close();
    CMSSignedData signature = new CMSSignedData(buffer);
    SignerInformation signer = (SignerInformation) signature.getSignerInfos().getSigners().iterator().next();
    // Added below
    Store<?> cs = signature.getCertificates();
    Collection<?> matches = cs.getMatches(signer.getSID());
    Iterator<?> iter = matches.iterator();
    // CertStore cs = signature.getCertificatesAndCRLs ("Collection", "BC");
    // Iterator<? extends Certificate> iter = cs.getCertificates (signer.getSID ()).iterator ();
    JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
    converter.setProvider("BC");
    X509Certificate certificate = converter.getCertificate((X509CertificateHolder) iter.next());
    CMSProcessable sc = signature.getSignedContent();
    byte[] data = (byte[]) sc.getContent();
    // Verify the signature
    // System.out.println (signer.verify (certificate, "BC"));
    System.out.println(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificate));
    FileOutputStream envfos = new FileOutputStream("Verified.txt");
    envfos.write(data);
    envfos.close();
}
Also used : SignerInformation(org.bouncycastle.cms.SignerInformation) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) DataInputStream(java.io.DataInputStream) CMSSignedData(org.bouncycastle.cms.CMSSignedData) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) CMSProcessable(org.bouncycastle.cms.CMSProcessable) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 29 with CMSSignedData

use of org.bouncycastle.cms.CMSSignedData in project serverless by bluenimble.

the class DefaultSigner method verify.

// Updated
@Override
public void verify(SecureDocument doc, CertificateAcceptor acceptor) throws SignerException {
    try {
        if (SignatureAware.class.isAssignableFrom(doc.getClass())) {
            SignatureAware signed = (SignatureAware) doc;
            byte[] signature = signed.getSignature();
            if (signature == null) {
                throw new SignerException("Signature not found in document");
            }
            Key key = signed.getKey();
            if (key == null) {
                throw new SignerException("Secret key not found in document");
            }
            sign(doc, key, null);
            byte[] expected = ((SignatureAware) doc).getSignature();
            if (!equals(signature, expected)) {
                throw new SignerException("Invalid signature");
            }
        } else {
            CMSSignedData signature = new CMSSignedData(doc.getBytes());
            SignerInformation signer = (SignerInformation) signature.getSignerInfos().getSigners().iterator().next();
            // CertStore cs = signature.getCertificatesAndCRLs ("Collection", "BC"); //TODO : base Store returning method
            Store<?> cs = signature.getCertificates();
            Collection<?> matches = cs.getMatches(signer.getSID());
            Iterator<?> iter = matches.iterator();
            while (iter.hasNext()) {
                JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
                converter.setProvider("BC");
                X509Certificate cert = converter.getCertificate((X509CertificateHolder) iter.next());
                if (acceptor != null && !acceptor.accept(cert)) {
                    throw new SignerException("Invalid Signing Certificate, Not Accepted");
                }
                if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) {
                    throw new SignerException("Invalid signature");
                }
            }
            CMSProcessable sc = signature.getSignedContent();
            doc.setBytes((byte[]) sc.getContent());
        }
    } catch (Throwable th) {
        throw new SignerException(th, th.getMessage());
    }
}
Also used : SignatureAware(com.bluenimble.platform.crypto.SignatureAware) SignerInformation(org.bouncycastle.cms.SignerInformation) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) CMSProcessable(org.bouncycastle.cms.CMSProcessable) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) SignerException(com.bluenimble.platform.crypto.signer.SignerException) StringKey(com.bluenimble.platform.crypto.signer.StringKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey)

Example 30 with CMSSignedData

use of org.bouncycastle.cms.CMSSignedData in project zm-mailbox by Zimbra.

the class DataSignerTest method testSignData.

@Test
public void testSignData() {
    try {
        String serverdir = MailboxTestUtil.getZimbraServerDir("");
        FileInputStream p12Stream = new FileInputStream(serverdir + "data/unittest/certificate/sign1_digitalid.p12");
        char[] expPass = "test123export".toCharArray();
        byte[] certBytes = ByteStreams.toByteArray(p12Stream);
        byte[] signedData = DataSigner.signData("hello world".getBytes(), certBytes, expPass);
        // validate signed data
        ByteArrayInputStream inputStream = new ByteArrayInputStream(signedData);
        try (ASN1InputStream asnInputStream = new ASN1InputStream(inputStream)) {
            CMSSignedData cmsSignedData = new CMSSignedData(ContentInfo.getInstance(asnInputStream.readObject()));
            Store certs = cmsSignedData.getCertificates();
            SignerInformationStore signers = cmsSignedData.getSignerInfos();
            Collection<SignerInformation> c = signers.getSigners();
            Iterator<SignerInformation> it = c.iterator();
            SignerInformation signer = it.next();
            Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID());
            X509CertificateHolder certHolder = certCollection.iterator().next();
            boolean verify = signer.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certHolder));
            Assert.assertTrue(verify);
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail("data sign test failed");
    }
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) Store(org.bouncycastle.util.Store) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) SignerInformation(org.bouncycastle.cms.SignerInformation) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) CMSSignedData(org.bouncycastle.cms.CMSSignedData) FileInputStream(java.io.FileInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) Test(org.junit.Test)

Aggregations

CMSSignedData (org.bouncycastle.cms.CMSSignedData)68 X509Certificate (java.security.cert.X509Certificate)32 IOException (java.io.IOException)31 CMSException (org.bouncycastle.cms.CMSException)31 CMSSignedDataGenerator (org.bouncycastle.cms.CMSSignedDataGenerator)22 CMSProcessableByteArray (org.bouncycastle.cms.CMSProcessableByteArray)20 SignerInformation (org.bouncycastle.cms.SignerInformation)19 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)17 ArrayList (java.util.ArrayList)16 JcaCertStore (org.bouncycastle.cert.jcajce.JcaCertStore)15 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)15 ByteArrayInputStream (java.io.ByteArrayInputStream)13 SignerInformationStore (org.bouncycastle.cms.SignerInformationStore)12 JcaSignerInfoGeneratorBuilder (org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder)12 CertificateException (java.security.cert.CertificateException)9 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)9 AttributeTable (org.bouncycastle.asn1.cms.AttributeTable)9 ContentInfo (org.bouncycastle.asn1.cms.ContentInfo)9 ContentSigner (org.bouncycastle.operator.ContentSigner)9 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)9