Search in sources :

Example 1 with CMSSignedData

use of org.openecard.bouncycastle.cms.CMSSignedData in project open-ecard by ecsec.

the class SignatureVerifier method validate.

public void validate(@Nonnull byte[] signature) throws KeyStoreException, SignatureInvalid {
    try {
        // load BC provider, so that the algorithms are available for the signature verification
        Security.addProvider(new BouncyCastleProvider());
        CMSProcessable wrappedChallenge = new CMSProcessableByteArray(challenge);
        CMSSignedData signedData = new CMSSignedData(wrappedChallenge, signature);
        Store<X509CertificateHolder> certStore = signedData.getCertificates();
        SignerInformationStore signerInfoStore = signedData.getSignerInfos();
        Collection<SignerInformation> signers = signerInfoStore.getSigners();
        Collection<X509Certificate> allCerts = convertCertificates(certStore.getMatches(new AllSelector()));
        for (SignerInformation signer : signers) {
            Collection<X509CertificateHolder> certCollection = certStore.getMatches(signer.getSID());
            X509CertificateHolder cert = certCollection.iterator().next();
            DigestCalculatorProvider dp = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();
            JcaSignerInfoVerifierBuilder verifBuilder = new JcaSignerInfoVerifierBuilder(dp).setProvider("BC");
            verifBuilder.setSignatureAlgorithmFinder(new DefaultSignatureAlgorithmIdentifierFinder() {

                @Override
                public AlgorithmIdentifier find(String sigAlgName) {
                    if (!AllowedSignatureAlgorithms.isKnownJcaAlgorithm(sigAlgName)) {
                        throw new IllegalArgumentException("Unsupported signature algorithm used.");
                    } else {
                        return super.find(sigAlgName);
                    }
                }
            });
            SignerInformationVerifier verif = verifBuilder.build(cert);
            // verify the signature
            if (!signer.verify(verif)) {
                throw new SignatureInvalid("Signer information could not be verified.");
            }
            // verify the path and certificate
            X509Certificate x509Cert = convertCertificate(cert);
            // TODO: verify that the signature is not too old. How old can it be at max? 1 minute?
            validatePath(x509Cert, allCerts, null);
            // check that the end certificate is under the admissable certificates
            if (ChipGatewayProperties.isUseSubjectWhitelist()) {
                X500Principal subj = x509Cert.getSubjectX500Principal();
                if (!AllowedSubjects.instance().isInSubjects(subj)) {
                    String msg = "The certificate used in the signature has an invalid subject: " + subj.getName();
                    throw new InvalidSubjectException(msg);
                }
            }
        }
        // fail if there is no signature in the SignedData structure
        if (signers.isEmpty()) {
            throw new SignatureInvalid("No signatures present in the given SignedData element.");
        }
    } catch (CertificateException ex) {
        throw new SignatureInvalid("Failed to read a certificate form the CMS data structure.", ex);
    } catch (CertPathBuilderException ex) {
        throw new SignatureInvalid("Failed to build certificate path for PKIX validation.", ex);
    } catch (CMSVerifierCertificateNotValidException ex) {
        throw new SignatureInvalid("Signer certificate was not valid when the signature was created.", ex);
    } catch (CMSException ex) {
        throw new SignatureInvalid("Failed to validate CMS data structure.", ex);
    } catch (InvalidSubjectException ex) {
        throw new SignatureInvalid("Certificate with invalid subject used in signature.", ex);
    } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | OperatorCreationException ex) {
        throw new SignatureInvalid("Invalid or unsupported algorithm or algorithm parameter used in signature.", ex);
    } catch (IllegalArgumentException ex) {
        throw new SignatureInvalid("Signature containes an invalid value.", ex);
    }
}
Also used : SignerInformation(org.openecard.bouncycastle.cms.SignerInformation) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AlgorithmIdentifier(org.openecard.bouncycastle.asn1.x509.AlgorithmIdentifier) SignerInformationStore(org.openecard.bouncycastle.cms.SignerInformationStore) CertPathBuilderException(java.security.cert.CertPathBuilderException) JcaSignerInfoVerifierBuilder(org.openecard.bouncycastle.cms.jcajce.JcaSignerInfoVerifierBuilder) SignerInformationVerifier(org.openecard.bouncycastle.cms.SignerInformationVerifier) OperatorCreationException(org.openecard.bouncycastle.operator.OperatorCreationException) BouncyCastleProvider(org.openecard.bouncycastle.jce.provider.BouncyCastleProvider) CMSProcessableByteArray(org.openecard.bouncycastle.cms.CMSProcessableByteArray) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) CMSVerifierCertificateNotValidException(org.openecard.bouncycastle.cms.CMSVerifierCertificateNotValidException) CMSSignedData(org.openecard.bouncycastle.cms.CMSSignedData) CMSProcessable(org.openecard.bouncycastle.cms.CMSProcessable) X509Certificate(java.security.cert.X509Certificate) DefaultSignatureAlgorithmIdentifierFinder(org.openecard.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) InvalidSubjectException(org.openecard.addons.cg.ex.InvalidSubjectException) DigestCalculatorProvider(org.openecard.bouncycastle.operator.DigestCalculatorProvider) X509CertificateHolder(org.openecard.bouncycastle.cert.X509CertificateHolder) X500Principal(javax.security.auth.x500.X500Principal) JcaDigestCalculatorProviderBuilder(org.openecard.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) CMSException(org.openecard.bouncycastle.cms.CMSException)

Example 2 with CMSSignedData

use of org.openecard.bouncycastle.cms.CMSSignedData in project open-ecard by ecsec.

the class SignatureTest method createSignature.

private CMSSignedData createSignature(String alias, byte[] challenge) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, InvalidKeyException, SignatureException, OperatorCreationException, CertificateEncodingException, CMSException {
    PrivateKey privKey = (PrivateKey) signStore.getKey(alias, pass.toCharArray());
    X509Certificate cert = (X509Certificate) signStore.getCertificate(alias);
    Certificate[] certChain = (Certificate[]) signStore.getCertificateChain(alias);
    Store certs = new JcaCertStore(Arrays.asList(certChain));
    // Signature signature = Signature.getInstance("SHA256WithRSA");
    // signature.initSign(privKey);
    // signature.update(challenge);
    // byte[] signedBytes = signature.sign();
    CMSTypedData msg = new CMSProcessableByteArray(challenge);
    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(privKey);
    DigestCalculatorProvider dgProv = new JcaDigestCalculatorProviderBuilder().build();
    gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(dgProv).build(signer, cert));
    gen.addCertificates(certs);
    CMSSignedData sigData = gen.generate(msg, false);
    return sigData;
}
Also used : CMSSignedDataGenerator(org.openecard.bouncycastle.cms.CMSSignedDataGenerator) CMSProcessableByteArray(org.openecard.bouncycastle.cms.CMSProcessableByteArray) PrivateKey(java.security.PrivateKey) CMSTypedData(org.openecard.bouncycastle.cms.CMSTypedData) JcaContentSignerBuilder(org.openecard.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.openecard.bouncycastle.operator.ContentSigner) KeyStore(java.security.KeyStore) Store(org.openecard.bouncycastle.util.Store) JcaCertStore(org.openecard.bouncycastle.cert.jcajce.JcaCertStore) JcaCertStore(org.openecard.bouncycastle.cert.jcajce.JcaCertStore) CMSSignedData(org.openecard.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) JcaSignerInfoGeneratorBuilder(org.openecard.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder) DigestCalculatorProvider(org.openecard.bouncycastle.operator.DigestCalculatorProvider) JcaDigestCalculatorProviderBuilder(org.openecard.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 3 with CMSSignedData

use of org.openecard.bouncycastle.cms.CMSSignedData in project open-ecard by ecsec.

the class SignatureTest method testInvalidPath.

@Test
public void testInvalidPath() throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, InvalidKeyException, SignatureException, OperatorCreationException, CertificateEncodingException, CMSException, IOException, CertificateException, CMSSignerDigestMismatchException, InvalidAlgorithmParameterException {
    byte[] challenge = "Hello World!".getBytes(StandardCharsets.UTF_8);
    CMSSignedData sigData = createSignature(selfSignedAlias, challenge);
    byte[] sigBytes = sigData.getEncoded();
    SignatureVerifier validator = new SignatureVerifier(trustStore, challenge);
    try {
        validator.validate(sigBytes);
        Assert.fail("Invalid signature found, expecte a valid one.");
    } catch (SignatureInvalid ex) {
    }
}
Also used : CMSSignedData(org.openecard.bouncycastle.cms.CMSSignedData) Test(org.testng.annotations.Test)

Example 4 with CMSSignedData

use of org.openecard.bouncycastle.cms.CMSSignedData in project open-ecard by ecsec.

the class SignatureTest method testValidSignature.

@Test
public void testValidSignature() throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, InvalidKeyException, SignatureException, OperatorCreationException, CertificateEncodingException, CMSException, IOException, CertificateException {
    byte[] challenge = "Hello World!".getBytes(StandardCharsets.UTF_8);
    CMSSignedData sigData = createSignature(caSignedAlias, challenge);
    byte[] sigBytes = sigData.getEncoded();
    SignatureVerifier validator = new SignatureVerifier(trustStore, challenge);
    try {
        validator.validate(sigBytes);
    } catch (SignatureInvalid ex) {
        Assert.fail("Invalid signature found, expected a valid one.");
    }
}
Also used : CMSSignedData(org.openecard.bouncycastle.cms.CMSSignedData) Test(org.testng.annotations.Test)

Example 5 with CMSSignedData

use of org.openecard.bouncycastle.cms.CMSSignedData in project open-ecard by ecsec.

the class SignatureTest method testInvalidSignature.

@Test
public void testInvalidSignature() throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, InvalidKeyException, SignatureException, OperatorCreationException, CertificateEncodingException, CMSException, IOException, CertificateException {
    byte[] challenge = "Hello World!".getBytes(StandardCharsets.UTF_8);
    CMSSignedData sigData = createSignature(caSignedAlias, challenge);
    byte[] sigBytes = sigData.getEncoded();
    // flip a bit in the challenge and see if it still verifies
    challenge[0] = 1;
    SignatureVerifier validator = new SignatureVerifier(trustStore, challenge);
    try {
        validator.validate(sigBytes);
        Assert.fail("Invalid signature found, expecte a valid one.");
    } catch (SignatureInvalid ex) {
    }
}
Also used : CMSSignedData(org.openecard.bouncycastle.cms.CMSSignedData) Test(org.testng.annotations.Test)

Aggregations

CMSSignedData (org.openecard.bouncycastle.cms.CMSSignedData)5 Test (org.testng.annotations.Test)3 X509Certificate (java.security.cert.X509Certificate)2 CMSProcessableByteArray (org.openecard.bouncycastle.cms.CMSProcessableByteArray)2 DigestCalculatorProvider (org.openecard.bouncycastle.operator.DigestCalculatorProvider)2 JcaDigestCalculatorProviderBuilder (org.openecard.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder)2 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)1 KeyStore (java.security.KeyStore)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 PrivateKey (java.security.PrivateKey)1 CertPathBuilderException (java.security.cert.CertPathBuilderException)1 Certificate (java.security.cert.Certificate)1 CertificateException (java.security.cert.CertificateException)1 X500Principal (javax.security.auth.x500.X500Principal)1 InvalidSubjectException (org.openecard.addons.cg.ex.InvalidSubjectException)1 AlgorithmIdentifier (org.openecard.bouncycastle.asn1.x509.AlgorithmIdentifier)1 X509CertificateHolder (org.openecard.bouncycastle.cert.X509CertificateHolder)1 JcaCertStore (org.openecard.bouncycastle.cert.jcajce.JcaCertStore)1 CMSException (org.openecard.bouncycastle.cms.CMSException)1 CMSProcessable (org.openecard.bouncycastle.cms.CMSProcessable)1