Search in sources :

Example 1 with BouncyCastleProvider

use of org.openecard.bouncycastle.jce.provider.BouncyCastleProvider 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 BouncyCastleProvider

use of org.openecard.bouncycastle.jce.provider.BouncyCastleProvider in project open-ecard by ecsec.

the class GenericCryptographyProtocolTest method testDecipher.

/**
 * Test for the Decipher Step of the Generic Cryptography protocol. After we connected to the ESIGN application
 * of the eGK, we use DIDList to get a List of DIDs that support the Decipher function. We then authenticate with
 * PIN.home and read the contents of the DIDs certificate. With it's public key we encrypt the contents of
 * plaintext.txt and finally let the card decrypt it through a call to Decipher. In the end we match the result with
 * the original plaintext.
 *
 * @throws Exception when something in this test went unexpectedly wrong
 */
@Test(enabled = TESTS_ENABLED)
public void testDecipher() throws Exception {
    CardApplicationPath cardApplicationPath = new CardApplicationPath();
    CardApplicationPathType cardApplicationPathType = new CardApplicationPathType();
    cardApplicationPathType.setCardApplication(cardApplication);
    cardApplicationPath.setCardAppPathRequest(cardApplicationPathType);
    CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath);
    WSHelper.checkResult(cardApplicationPathResponse);
    CardApplicationConnect parameters = new CardApplicationConnect();
    CardAppPathResultSet cardAppPathResultSet = cardApplicationPathResponse.getCardAppPathResultSet();
    parameters.setCardApplicationPath(cardAppPathResultSet.getCardApplicationPathResult().get(0));
    CardApplicationConnectResponse result = instance.cardApplicationConnect(parameters);
    WSHelper.checkResult(result);
    assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor());
    DIDList didList = new DIDList();
    didList.setConnectionHandle(result.getConnectionHandle());
    DIDQualifierType didQualifier = new DIDQualifierType();
    didQualifier.setApplicationIdentifier(cardApplication);
    didQualifier.setObjectIdentifier(ECardConstants.Protocol.GENERIC_CRYPTO);
    didQualifier.setApplicationFunction("Decipher");
    didList.setFilter(didQualifier);
    DIDListResponse didListResponse = instance.didList(didList);
    assertTrue(didListResponse.getDIDNameList().getDIDName().size() > 0);
    WSHelper.checkResult(didListResponse);
    DIDAuthenticate didAthenticate = new DIDAuthenticate();
    didAthenticate.setDIDName("PIN.home");
    PinCompareDIDAuthenticateInputType didAuthenticationData = new PinCompareDIDAuthenticateInputType();
    didAthenticate.setAuthenticationProtocolData(didAuthenticationData);
    didAthenticate.setConnectionHandle(result.getConnectionHandle());
    didAthenticate.getConnectionHandle().setCardApplication(cardApplication_ROOT);
    didAuthenticationData.setProtocol(ECardConstants.Protocol.PIN_COMPARE);
    didAthenticate.setAuthenticationProtocolData(didAuthenticationData);
    DIDAuthenticateResponse didAuthenticateResult = instance.didAuthenticate(didAthenticate);
    WSHelper.checkResult(didAuthenticateResult);
    assertEquals(didAuthenticateResult.getAuthenticationProtocolData().getProtocol(), ECardConstants.Protocol.PIN_COMPARE);
    assertEquals(didAuthenticateResult.getAuthenticationProtocolData().getAny().size(), 0);
    assertEquals(ECardConstants.Major.OK, didAuthenticateResult.getResult().getResultMajor());
    byte[] plaintextBytes = plaintext.getBytes();
    for (int numOfDIDs = 0; numOfDIDs < didListResponse.getDIDNameList().getDIDName().size(); numOfDIDs++) {
        String didName = didListResponse.getDIDNameList().getDIDName().get(numOfDIDs);
        DIDGet didGet = new DIDGet();
        didGet.setDIDName(didName);
        didGet.setDIDScope(DIDScopeType.LOCAL);
        didGet.setConnectionHandle(result.getConnectionHandle());
        didGet.getConnectionHandle().setCardApplication(cardApplication);
        DIDGetResponse didGetResponse = instance.didGet(didGet);
        org.openecard.crypto.common.sal.did.CryptoMarkerType cryptoMarker = new org.openecard.crypto.common.sal.did.CryptoMarkerType((CryptoMarkerType) didGetResponse.getDIDStructure().getDIDMarker());
        ByteArrayOutputStream ciphertext = new ByteArrayOutputStream();
        // read the certificate
        DSIRead dsiRead = new DSIRead();
        dsiRead.setConnectionHandle(result.getConnectionHandle());
        dsiRead.getConnectionHandle().setCardApplication(cardApplication);
        dsiRead.setDSIName(cryptoMarker.getCertificateRefs().get(0).getDataSetName());
        DSIReadResponse dsiReadResponse = instance.dsiRead(dsiRead);
        assertEquals(ECardConstants.Major.OK, dsiReadResponse.getResult().getResultMajor());
        assertTrue(dsiReadResponse.getDSIContent().length > 0);
        // convert the contents to a certificate
        Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(dsiReadResponse.getDSIContent()));
        Cipher cipher;
        int blocksize;
        String algorithmUri = cryptoMarker.getAlgorithmInfo().getAlgorithmIdentifier().getAlgorithm();
        if (algorithmUri.equals(GenericCryptoUris.RSA_ENCRYPTION)) {
            cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, cert);
            // keysize/8-pkcspadding = (2048)/8-11
            blocksize = 245;
        } else if (algorithmUri.equals(GenericCryptoUris.RSAES_OAEP)) {
            cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding", new BouncyCastleProvider());
            cipher.init(Cipher.ENCRYPT_MODE, cert);
            blocksize = cipher.getBlockSize();
        } else {
            LOG.warn("Skipping decipher for the unsupported algorithmOID: {}", algorithmUri);
            continue;
        }
        int rest = plaintextBytes.length % blocksize;
        // encrypt block for block
        for (int offset = 0; offset < plaintextBytes.length; offset += blocksize) {
            if ((offset + blocksize) > plaintextBytes.length) {
                ciphertext.write(cipher.doFinal(plaintextBytes, offset, rest));
            } else {
                ciphertext.write(cipher.doFinal(plaintextBytes, offset, blocksize));
            }
        }
        Decipher decipher = new Decipher();
        decipher.setCipherText(ciphertext.toByteArray());
        decipher.setConnectionHandle(result.getConnectionHandle());
        decipher.getConnectionHandle().setCardApplication(cardApplication);
        decipher.setDIDName(didName);
        decipher.setDIDScope(DIDScopeType.LOCAL);
        DecipherResponse decipherResponse = instance.decipher(decipher);
        assertEquals(decipherResponse.getPlainText(), plaintextBytes);
        // test invalid ciphertext length (not divisible through blocksize without rest)
        decipher = new Decipher();
        decipher.setCipherText(ByteUtils.concatenate((byte) 0x00, ciphertext.toByteArray()));
        decipher.setConnectionHandle(result.getConnectionHandle());
        decipher.getConnectionHandle().setCardApplication(cardApplication);
        decipher.setDIDName(didName);
        decipher.setDIDScope(DIDScopeType.LOCAL);
        decipherResponse = instance.decipher(decipher);
        Result res = decipherResponse.getResult();
        assertEquals(res.getResultMajor(), ECardConstants.Major.ERROR);
        assertEquals(res.getResultMinor(), ECardConstants.Minor.App.INCORRECT_PARM);
    }
}
Also used : DIDList(iso.std.iso_iec._24727.tech.schema.DIDList) PinCompareDIDAuthenticateInputType(iso.std.iso_iec._24727.tech.schema.PinCompareDIDAuthenticateInputType) CardAppPathResultSet(iso.std.iso_iec._24727.tech.schema.CardApplicationPathResponse.CardAppPathResultSet) DIDListResponse(iso.std.iso_iec._24727.tech.schema.DIDListResponse) Result(oasis.names.tc.dss._1_0.core.schema.Result) CardApplicationPathType(iso.std.iso_iec._24727.tech.schema.CardApplicationPathType) CardApplicationConnect(iso.std.iso_iec._24727.tech.schema.CardApplicationConnect) DIDGet(iso.std.iso_iec._24727.tech.schema.DIDGet) BouncyCastleProvider(org.openecard.bouncycastle.jce.provider.BouncyCastleProvider) DIDAuthenticate(iso.std.iso_iec._24727.tech.schema.DIDAuthenticate) CardApplicationPathResponse(iso.std.iso_iec._24727.tech.schema.CardApplicationPathResponse) DSIRead(iso.std.iso_iec._24727.tech.schema.DSIRead) DIDQualifierType(iso.std.iso_iec._24727.tech.schema.DIDQualifierType) DIDGetResponse(iso.std.iso_iec._24727.tech.schema.DIDGetResponse) CryptoMarkerType(iso.std.iso_iec._24727.tech.schema.CryptoMarkerType) CardApplicationConnectResponse(iso.std.iso_iec._24727.tech.schema.CardApplicationConnectResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) X509Certificate(java.security.cert.X509Certificate) CardApplicationPath(iso.std.iso_iec._24727.tech.schema.CardApplicationPath) DIDAuthenticateResponse(iso.std.iso_iec._24727.tech.schema.DIDAuthenticateResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) DecipherResponse(iso.std.iso_iec._24727.tech.schema.DecipherResponse) Cipher(javax.crypto.Cipher) Decipher(iso.std.iso_iec._24727.tech.schema.Decipher) DSIReadResponse(iso.std.iso_iec._24727.tech.schema.DSIReadResponse) X509Certificate(java.security.cert.X509Certificate) VerifyCertificate(iso.std.iso_iec._24727.tech.schema.VerifyCertificate) Certificate(java.security.cert.Certificate) Test(org.testng.annotations.Test)

Example 3 with BouncyCastleProvider

use of org.openecard.bouncycastle.jce.provider.BouncyCastleProvider in project open-ecard by ecsec.

the class VerifySignatureStep method perform.

@Override
public VerifySignatureResponse perform(VerifySignature request, Map<String, Object> internalData) {
    VerifySignatureResponse response = WSHelper.makeResponse(VerifySignatureResponse.class, WSHelper.makeResultOK());
    try {
        ConnectionHandleType connectionHandle = SALUtils.getConnectionHandle(request);
        CardStateEntry cardStateEntry = SALUtils.getCardStateEntry(internalData, connectionHandle);
        String didName = SALUtils.getDIDName(request);
        DIDStructureType didStructure = SALUtils.getDIDStructure(request, didName, cardStateEntry, connectionHandle);
        // required
        byte[] signature = request.getSignature();
        // optional
        byte[] message = request.getMessage();
        CryptoMarkerType cryptoMarker = new CryptoMarkerType(didStructure.getDIDMarker());
        String dataSetNameCertificate = cryptoMarker.getCertificateRefs().get(0).getDataSetName();
        String algorithmIdentifier = cryptoMarker.getAlgorithmInfo().getAlgorithmIdentifier().getAlgorithm();
        DSIRead dsiRead = new DSIRead();
        dsiRead.setConnectionHandle(connectionHandle);
        dsiRead.setDSIName(dataSetNameCertificate);
        DSIReadResponse dsiReadResponse = (DSIReadResponse) dispatcher.safeDeliver(dsiRead);
        WSHelper.checkResult(dsiReadResponse);
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        Certificate cert = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(dsiReadResponse.getDSIContent()));
        Signature signatureAlgorithm;
        if (algorithmIdentifier.equals(GenericCryptoUris.RSA_ENCRYPTION)) {
            signatureAlgorithm = Signature.getInstance("RSA", new BouncyCastleProvider());
        } else if (algorithmIdentifier.equals(GenericCryptoUris.RSASSA_PSS_SHA256)) {
            signatureAlgorithm = Signature.getInstance("RAWRSASSA-PSS", new BouncyCastleProvider());
            signatureAlgorithm.setParameter(new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1));
        } else if (algorithmIdentifier.equals(GenericCryptoUris.sigS_ISO9796_2)) {
            return WSHelper.makeResponse(VerifySignatureResponse.class, WSHelper.makeResultUnknownError(algorithmIdentifier + " Not supported yet."));
        } else if (algorithmIdentifier.equals(GenericCryptoUris.sigS_ISO9796_2rnd)) {
            return WSHelper.makeResponse(VerifySignatureResponse.class, WSHelper.makeResultUnknownError(algorithmIdentifier + " Not supported yet."));
        } else {
            throw new IncorrectParameterException("Unknown signature algorithm.");
        }
        signatureAlgorithm.initVerify(cert);
        if (message != null) {
            signatureAlgorithm.update(message);
        }
        if (!signatureAlgorithm.verify(signature)) {
            throw new InvalidSignatureException();
        }
    } catch (ECardException e) {
        LOG.error(e.getMessage(), e);
        response.setResult(e.getResult());
    } catch (Exception e) {
        response.setResult(WSHelper.makeResult(e));
    }
    return response;
}
Also used : ConnectionHandleType(iso.std.iso_iec._24727.tech.schema.ConnectionHandleType) CardStateEntry(org.openecard.common.sal.state.CardStateEntry) InvalidSignatureException(org.openecard.common.sal.exception.InvalidSignatureException) DSIRead(iso.std.iso_iec._24727.tech.schema.DSIRead) CryptoMarkerType(org.openecard.crypto.common.sal.did.CryptoMarkerType) VerifySignatureResponse(iso.std.iso_iec._24727.tech.schema.VerifySignatureResponse) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) ECardException(org.openecard.common.ECardException) IncorrectParameterException(org.openecard.common.sal.exception.IncorrectParameterException) InvalidSignatureException(org.openecard.common.sal.exception.InvalidSignatureException) ECardException(org.openecard.common.ECardException) ByteArrayInputStream(java.io.ByteArrayInputStream) PSSParameterSpec(java.security.spec.PSSParameterSpec) Signature(java.security.Signature) VerifySignature(iso.std.iso_iec._24727.tech.schema.VerifySignature) IncorrectParameterException(org.openecard.common.sal.exception.IncorrectParameterException) DIDStructureType(iso.std.iso_iec._24727.tech.schema.DIDStructureType) DSIReadResponse(iso.std.iso_iec._24727.tech.schema.DSIReadResponse) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) BouncyCastleProvider(org.openecard.bouncycastle.jce.provider.BouncyCastleProvider) MGF1ParameterSpec(java.security.spec.MGF1ParameterSpec)

Aggregations

X509Certificate (java.security.cert.X509Certificate)3 BouncyCastleProvider (org.openecard.bouncycastle.jce.provider.BouncyCastleProvider)3 DSIRead (iso.std.iso_iec._24727.tech.schema.DSIRead)2 DSIReadResponse (iso.std.iso_iec._24727.tech.schema.DSIReadResponse)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 Certificate (java.security.cert.Certificate)2 CardApplicationConnect (iso.std.iso_iec._24727.tech.schema.CardApplicationConnect)1 CardApplicationConnectResponse (iso.std.iso_iec._24727.tech.schema.CardApplicationConnectResponse)1 CardApplicationPath (iso.std.iso_iec._24727.tech.schema.CardApplicationPath)1 CardApplicationPathResponse (iso.std.iso_iec._24727.tech.schema.CardApplicationPathResponse)1 CardAppPathResultSet (iso.std.iso_iec._24727.tech.schema.CardApplicationPathResponse.CardAppPathResultSet)1 CardApplicationPathType (iso.std.iso_iec._24727.tech.schema.CardApplicationPathType)1 ConnectionHandleType (iso.std.iso_iec._24727.tech.schema.ConnectionHandleType)1 CryptoMarkerType (iso.std.iso_iec._24727.tech.schema.CryptoMarkerType)1 DIDAuthenticate (iso.std.iso_iec._24727.tech.schema.DIDAuthenticate)1 DIDAuthenticateResponse (iso.std.iso_iec._24727.tech.schema.DIDAuthenticateResponse)1 DIDGet (iso.std.iso_iec._24727.tech.schema.DIDGet)1 DIDGetResponse (iso.std.iso_iec._24727.tech.schema.DIDGetResponse)1 DIDList (iso.std.iso_iec._24727.tech.schema.DIDList)1 DIDListResponse (iso.std.iso_iec._24727.tech.schema.DIDListResponse)1