Search in sources :

Example 61 with AlgorithmIdentifier

use of org.openecard.bouncycastle.asn1.x509.AlgorithmIdentifier in project signer by demoiselle.

the class RevocationRefs method makeCrlValidatedID.

/**
 * @param extract
 *            CrlValidatedID from X509CRL
 * @return a CrlValidatedID
 * @throws NoSuchAlgorithmException
 * @throws CRLException
 */
private CrlValidatedID makeCrlValidatedID(X509CRL crl) throws NoSuchAlgorithmException, CRLException {
    Digest digest = DigestFactory.getInstance().factoryDefault();
    digest.setAlgorithm(DigestAlgorithmEnum.SHA_256);
    OtherHashAlgAndValue otherHashAlgAndValue = new OtherHashAlgAndValue(new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256), new DEROctetString(digest.digest(crl.getEncoded())));
    OtherHash hash = new OtherHash(otherHashAlgAndValue);
    BigInteger crlnumber;
    CrlIdentifier crlid;
    if (crl.getExtensionValue("2.5.29.20") != null) {
        ASN1Integer varASN1Integer = new ASN1Integer(crl.getExtensionValue("2.5.29.20"));
        crlnumber = varASN1Integer.getPositiveValue();
        crlid = new CrlIdentifier(new X500Name(crl.getIssuerX500Principal().getName()), new DERUTCTime(crl.getThisUpdate()), crlnumber);
    } else {
        crlid = new CrlIdentifier(new X500Name(crl.getIssuerX500Principal().getName()), new DERUTCTime(crl.getThisUpdate()));
    }
    CrlValidatedID crlvid = new CrlValidatedID(hash, crlid);
    return crlvid;
}
Also used : CrlValidatedID(org.bouncycastle.asn1.esf.CrlValidatedID) Digest(org.demoiselle.signer.cryptography.Digest) DERUTCTime(org.bouncycastle.asn1.DERUTCTime) BigInteger(java.math.BigInteger) CrlIdentifier(org.bouncycastle.asn1.esf.CrlIdentifier) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) X500Name(org.bouncycastle.asn1.x500.X500Name) OtherHashAlgAndValue(org.bouncycastle.asn1.esf.OtherHashAlgAndValue) DEROctetString(org.bouncycastle.asn1.DEROctetString) OtherHash(org.bouncycastle.asn1.esf.OtherHash) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 62 with AlgorithmIdentifier

use of org.openecard.bouncycastle.asn1.x509.AlgorithmIdentifier in project signer by demoiselle.

the class CertificateRefs method getValue.

@Override
public Attribute getValue() throws SignerException {
    try {
        int chainSize = certificates.length - 1;
        OtherCertID[] arrayOtherCertID = new OtherCertID[chainSize];
        for (int i = 1; i <= chainSize; i++) {
            X509Certificate issuerCert = null;
            X509Certificate cert = (X509Certificate) certificates[i];
            if (i < chainSize) {
                issuerCert = (X509Certificate) certificates[i + 1];
            } else {
                // raiz
                issuerCert = (X509Certificate) certificates[i];
            }
            Digest digest = DigestFactory.getInstance().factoryDefault();
            digest.setAlgorithm(DigestAlgorithmEnum.SHA_256);
            byte[] certHash = digest.digest(cert.getEncoded());
            X500Name dirName = new X500Name(issuerCert.getSubjectX500Principal().getName());
            GeneralName name = new GeneralName(dirName);
            GeneralNames issuer = new GeneralNames(name);
            ASN1Integer serialNumber = new ASN1Integer(cert.getSerialNumber());
            IssuerSerial issuerSerial = new IssuerSerial(issuer, serialNumber);
            AlgorithmIdentifier algId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256);
            OtherCertID otherCertID = new OtherCertID(algId, certHash, issuerSerial);
            arrayOtherCertID[i - 1] = otherCertID;
        }
        return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new ASN1Encodable[] { new DERSequence(arrayOtherCertID) }));
    } catch (CertificateEncodingException e) {
        throw new SignerException(e.getMessage());
    }
}
Also used : IssuerSerial(org.bouncycastle.asn1.x509.IssuerSerial) Digest(org.demoiselle.signer.cryptography.Digest) UnsignedAttribute(org.demoiselle.signer.policy.impl.cades.pkcs7.attribute.UnsignedAttribute) Attribute(org.bouncycastle.asn1.cms.Attribute) CertificateEncodingException(java.security.cert.CertificateEncodingException) X500Name(org.bouncycastle.asn1.x500.X500Name) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) DERSet(org.bouncycastle.asn1.DERSet) X509Certificate(java.security.cert.X509Certificate) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) OtherCertID(org.bouncycastle.asn1.ess.OtherCertID) DERSequence(org.bouncycastle.asn1.DERSequence) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) SignerException(org.demoiselle.signer.policy.impl.cades.SignerException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 63 with AlgorithmIdentifier

use of org.openecard.bouncycastle.asn1.x509.AlgorithmIdentifier 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 64 with AlgorithmIdentifier

use of org.openecard.bouncycastle.asn1.x509.AlgorithmIdentifier in project open-ecard by ecsec.

the class Signer method sign.

public byte[] sign(byte[] data) throws NoSuchDid, WSHelper.WSException, SecurityConditionUnsatisfiable, ParameterInvalid, SlotHandleInvalid, PinBlocked {
    Semaphore s = getLock(handle.getIFDName());
    boolean acquired = false;
    try {
        s.acquire();
        acquired = true;
        // get crypto dids
        DidInfos didInfos = tokenCache.getInfo(pin, handle);
        DidInfo didInfo = didInfos.getDidInfo(didName);
        didInfo.connectApplication();
        didInfo.authenticateMissing();
        CryptoMarkerType cryptoMarker = didInfo.getGenericCryptoMarker();
        String algUri = cryptoMarker.getAlgorithmInfo().getAlgorithmIdentifier().getAlgorithm();
        try {
            SignatureAlgorithms alg = SignatureAlgorithms.fromAlgId(algUri);
            // calculate hash if needed
            byte[] digest = data;
            if (alg.getHashAlg() != null && (cryptoMarker.getHashGenerationInfo() == null || cryptoMarker.getHashGenerationInfo() == HashGenerationInfoType.NOT_ON_CARD)) {
                digest = didInfo.hash(digest);
            }
            // wrap hash in DigestInfo if needed
            if (alg == SignatureAlgorithms.CKM_RSA_PKCS) {
                try {
                    ASN1ObjectIdentifier digestOid = getHashAlgOid(data);
                    DigestInfo di = new DigestInfo(new AlgorithmIdentifier(digestOid, DERNull.INSTANCE), digest);
                    byte[] sigMsg = di.getEncoded(ASN1Encoding.DER);
                    digest = sigMsg;
                } catch (IOException ex) {
                    String msg = "Error encoding DigestInfo object.";
                    Result r = WSHelper.makeResultError(ECardConstants.Minor.App.INT_ERROR, msg);
                    throw WSHelper.createException(r);
                } catch (InvalidParameterException ex) {
                    String msg = "Hash algorithm could not be determined for the given hash.";
                    Result r = WSHelper.makeResultError(ECardConstants.Minor.App.INCORRECT_PARM, msg);
                    throw WSHelper.createException(r);
                }
            }
            byte[] signature = didInfo.sign(digest);
            return signature;
        } catch (UnsupportedAlgorithmException ex) {
            String msg = String.format("DID uses unsupported algorithm %s.", algUri);
            throw WSHelper.createException(WSHelper.makeResultError(ECardConstants.Minor.App.INT_ERROR, msg));
        }
    } catch (WSHelper.WSException ex) {
        String minor = StringUtils.nullToEmpty(ex.getResultMinor());
        switch(minor) {
            case ECardConstants.Minor.App.INCORRECT_PARM:
                throw new ParameterInvalid(ex.getMessage(), ex);
            case ECardConstants.Minor.IFD.INVALID_SLOT_HANDLE:
                throw new SlotHandleInvalid(ex.getMessage(), ex);
            case ECardConstants.Minor.IFD.PASSWORD_BLOCKED:
            case ECardConstants.Minor.IFD.PASSWORD_SUSPENDED:
            case ECardConstants.Minor.IFD.PASSWORD_DEACTIVATED:
                throw new PinBlocked(ex.getMessage(), ex);
            case ECardConstants.Minor.SAL.SECURITY_CONDITION_NOT_SATISFIED:
                throw new SecurityConditionUnsatisfiable(ex.getMessage(), ex);
            case ECardConstants.Minor.IFD.CANCELLATION_BY_USER:
            case ECardConstants.Minor.SAL.CANCELLATION_BY_USER:
                throw new ThreadTerminateException("Signature generation cancelled.", ex);
            default:
                throw ex;
        }
    } catch (InvocationTargetExceptionUnchecked ex) {
        if (ex.getCause() instanceof InterruptedException || ex.getCause() instanceof ThreadTerminateException) {
            throw new ThreadTerminateException("Signature creation interrupted.");
        } else {
            String msg = ex.getCause().getMessage();
            throw WSHelper.createException(WSHelper.makeResultError(ECardConstants.Minor.App.INT_ERROR, msg));
        }
    } catch (InterruptedException ex) {
        throw new ThreadTerminateException("Signature creation interrupted.");
    } finally {
        tokenCache.clearPins();
        if (acquired) {
            s.release();
        }
    }
}
Also used : WSHelper(org.openecard.common.WSHelper) PinBlocked(org.openecard.addons.cg.ex.PinBlocked) InvocationTargetExceptionUnchecked(org.openecard.common.interfaces.InvocationTargetExceptionUnchecked) SecurityConditionUnsatisfiable(org.openecard.common.SecurityConditionUnsatisfiable) CryptoMarkerType(org.openecard.crypto.common.sal.did.CryptoMarkerType) SlotHandleInvalid(org.openecard.addons.cg.ex.SlotHandleInvalid) Semaphore(java.util.concurrent.Semaphore) IOException(java.io.IOException) AlgorithmIdentifier(org.openecard.bouncycastle.asn1.x509.AlgorithmIdentifier) Result(oasis.names.tc.dss._1_0.core.schema.Result) InvalidParameterException(java.security.InvalidParameterException) DidInfo(org.openecard.crypto.common.sal.did.DidInfo) DigestInfo(org.openecard.bouncycastle.asn1.x509.DigestInfo) SignatureAlgorithms(org.openecard.crypto.common.SignatureAlgorithms) UnsupportedAlgorithmException(org.openecard.crypto.common.UnsupportedAlgorithmException) ParameterInvalid(org.openecard.addons.cg.ex.ParameterInvalid) ThreadTerminateException(org.openecard.common.ThreadTerminateException) DidInfos(org.openecard.crypto.common.sal.did.DidInfos) ASN1ObjectIdentifier(org.openecard.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 65 with AlgorithmIdentifier

use of org.openecard.bouncycastle.asn1.x509.AlgorithmIdentifier in project open-ecard by ecsec.

the class SmartCardSignerCredential method genSig.

private byte[] genSig(SignatureAndHashAlgorithm algorithm, byte[] sigData, boolean isRaw) throws IOException {
    SignatureAlgorithms didAlg = getDidAlgorithm();
    LOG.debug("Using DID with algorithm={}.", didAlg.getJcaAlg());
    if (algorithm != null) {
        String reqAlgStr = String.format("%s-%s", SignatureAlgorithm.getText(algorithm.getSignature()), HashAlgorithm.getText(algorithm.getHash()));
        LOG.debug("Performing TLS 1.2 signature for algorithm={}.", reqAlgStr);
        if (isRaw && isRawRSA(didAlg)) {
            // TLS >= 1.2 needs a PKCS#1 v1.5 signature and no raw RSA signature
            ASN1ObjectIdentifier hashAlgId = TlsUtils.getOIDForHashAlgorithm(algorithm.getHash());
            DigestInfo digestInfo = new DigestInfo(new AlgorithmIdentifier(hashAlgId, DERNull.INSTANCE), sigData);
            sigData = digestInfo.getEncoded(ASN1Encoding.DER);
            LOG.debug("Signing DigestInfo with algorithm={}.", hashAlgId);
        }
    } else {
        LOG.debug("Performing pre-TLS 1.2 signature.");
    }
    try {
        if (isRaw) {
            LOG.debug("Raw Signature of data={}.", ByteUtils.toHexString(sigData));
        } else {
            LOG.debug("Hashed Signature of data blob.");
            CryptoMarkerType cryptoMarker = did.getGenericCryptoMarker();
            if (didAlg.getHashAlg() != null && (cryptoMarker.getHashGenerationInfo() == null || cryptoMarker.getHashGenerationInfo() == HashGenerationInfoType.NOT_ON_CARD)) {
                sigData = did.hash(sigData);
            }
        }
        did.authenticateMissing();
        byte[] signature = did.sign(sigData);
        return signature;
    } catch (WSHelper.WSException ex) {
        String msg = "Failed to create signature because of an unknown error.";
        LOG.warn(msg, ex);
        throw new IOException(msg, ex);
    } catch (SecurityConditionUnsatisfiable ex) {
        String msg = "Access to the signature DID could not be obtained.";
        LOG.warn(msg, ex);
        throw new IOException(msg, ex);
    } catch (NoSuchDid ex) {
        String msg = "Signing DID not available anymore.";
        LOG.warn(msg, ex);
        throw new IOException(msg, ex);
    }
}
Also used : WSHelper(org.openecard.common.WSHelper) DigestInfo(org.openecard.bouncycastle.asn1.x509.DigestInfo) SignatureAlgorithms(org.openecard.crypto.common.SignatureAlgorithms) SecurityConditionUnsatisfiable(org.openecard.common.SecurityConditionUnsatisfiable) CryptoMarkerType(org.openecard.crypto.common.sal.did.CryptoMarkerType) IOException(java.io.IOException) NoSuchDid(org.openecard.crypto.common.sal.did.NoSuchDid) ASN1ObjectIdentifier(org.openecard.bouncycastle.asn1.ASN1ObjectIdentifier) AlgorithmIdentifier(org.openecard.bouncycastle.asn1.x509.AlgorithmIdentifier)

Aggregations

AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)111 IOException (java.io.IOException)47 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)35 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)35 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)32 BigInteger (java.math.BigInteger)29 X509Certificate (java.security.cert.X509Certificate)27 X500Name (org.bouncycastle.asn1.x500.X500Name)27 DEROctetString (org.bouncycastle.asn1.DEROctetString)21 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)20 KeyPair (java.security.KeyPair)19 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)19 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)19 Date (java.util.Date)18 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)18 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)17 DERSequence (org.bouncycastle.asn1.DERSequence)16 KeyPairGenerator (java.security.KeyPairGenerator)15 PublicKey (java.security.PublicKey)14 InvalidKeyException (java.security.InvalidKeyException)13