Search in sources :

Example 6 with DigestInfo

use of com.github.zhenwei.core.asn1.x509.DigestInfo in project jmulticard by ctt-gob-es.

the class TestAsn1SimpleTypes method testDigestInfoCreation.

/**
 * Prueba de creaci&oacute;n de <code>DigestInfo</code> de PKCS#1.
 * @throws Exception En cualquier error.
 */
@SuppressWarnings("static-method")
@Test
public void testDigestInfoCreation() throws Exception {
    final DigestInfo di = new DigestInfo();
    di.setDerValue(SAMPLE_DIGEST_INFO);
    System.out.println(di);
}
Also used : DigestInfo(es.gob.jmulticard.asn1.der.pkcs1.DigestInfo) Test(org.junit.Test)

Example 7 with DigestInfo

use of com.github.zhenwei.core.asn1.x509.DigestInfo in project jmulticard by ctt-gob-es.

the class SignerInformation method doVerify.

private boolean doVerify(SignerInformationVerifier verifier) throws CMSException {
    String encName = CMSSignedHelper.INSTANCE.getEncryptionAlgName(this.getEncryptionAlgOID());
    ContentVerifier contentVerifier;
    try {
        contentVerifier = verifier.getContentVerifier(encryptionAlgorithm, info.getDigestAlgorithm());
    } catch (OperatorCreationException e) {
        throw new CMSException("can't create content verifier: " + e.getMessage(), e);
    }
    try {
        OutputStream sigOut = contentVerifier.getOutputStream();
        if (resultDigest == null) {
            DigestCalculator calc = verifier.getDigestCalculator(this.getDigestAlgorithmID());
            if (content != null) {
                OutputStream digOut = calc.getOutputStream();
                if (signedAttributeSet == null) {
                    if (contentVerifier instanceof RawContentVerifier) {
                        content.write(digOut);
                    } else {
                        OutputStream cOut = new TeeOutputStream(digOut, sigOut);
                        content.write(cOut);
                        cOut.close();
                    }
                } else {
                    content.write(digOut);
                    sigOut.write(this.getEncodedSignedAttributes());
                }
                digOut.close();
            } else if (signedAttributeSet != null) {
                sigOut.write(this.getEncodedSignedAttributes());
            } else {
                // TODO Get rid of this exception and just treat content==null as empty not missing?
                throw new CMSException("data not encapsulated in signature - use detached constructor.");
            }
            resultDigest = calc.getDigest();
        } else {
            if (signedAttributeSet == null) {
                if (content != null) {
                    content.write(sigOut);
                }
            } else {
                sigOut.write(this.getEncodedSignedAttributes());
            }
        }
        sigOut.close();
    } catch (IOException e) {
        throw new CMSException("can't process mime object to create signature.", e);
    } catch (OperatorCreationException e) {
        throw new CMSException("can't create digest calculator: " + e.getMessage(), e);
    }
    // RFC 3852 11.1 Check the content-type attribute is correct
    verifyContentTypeAttributeValue();
    AttributeTable signedAttrTable = this.getSignedAttributes();
    // RFC 6211 Validate Algorithm Identifier protection attribute if present
    verifyAlgorithmIdentifierProtectionAttribute(signedAttrTable);
    // RFC 3852 11.2 Check the message-digest attribute is correct
    verifyMessageDigestAttribute();
    // RFC 3852 11.4 Validate countersignature attribute(s)
    verifyCounterSignatureAttribute(signedAttrTable);
    try {
        if (signedAttributeSet == null && resultDigest != null) {
            if (contentVerifier instanceof RawContentVerifier) {
                RawContentVerifier rawVerifier = (RawContentVerifier) contentVerifier;
                if (encName.equals("RSA")) {
                    DigestInfo digInfo = new DigestInfo(new AlgorithmIdentifier(digestAlgorithm.getAlgorithm(), DERNull.INSTANCE), resultDigest);
                    return rawVerifier.verify(digInfo.getEncoded(ASN1Encoding.DER), this.getSignature());
                }
                return rawVerifier.verify(resultDigest, this.getSignature());
            }
        }
        return contentVerifier.verify(this.getSignature());
    } catch (IOException e) {
        throw new CMSException("can't process mime object to create signature.", e);
    }
}
Also used : TeeOutputStream(org.bouncycastle.util.io.TeeOutputStream) DigestInfo(org.bouncycastle.asn1.x509.DigestInfo) ContentVerifier(org.bouncycastle.operator.ContentVerifier) RawContentVerifier(org.bouncycastle.operator.RawContentVerifier) OutputStream(java.io.OutputStream) TeeOutputStream(org.bouncycastle.util.io.TeeOutputStream) DigestCalculator(org.bouncycastle.operator.DigestCalculator) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) RawContentVerifier(org.bouncycastle.operator.RawContentVerifier) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) IOException(java.io.IOException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 8 with DigestInfo

use of com.github.zhenwei.core.asn1.x509.DigestInfo 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 9 with DigestInfo

use of com.github.zhenwei.core.asn1.x509.DigestInfo 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)

Example 10 with DigestInfo

use of com.github.zhenwei.core.asn1.x509.DigestInfo in project LinLong-Java by zhenwei1108.

the class MacData method toASN1Primitive.

/**
 * <pre>
 * MacData ::= SEQUENCE {
 *     mac      DigestInfo,
 *     macSalt  OCTET STRING,
 *     iterations INTEGER DEFAULT 1
 *     -- Note: The default is for historic reasons and its use is deprecated. A
 *     -- higher value, like 1024 is recommended.
 * </pre>
 *
 * @return the basic ASN1Primitive construction.
 */
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector(3);
    v.add(digInfo);
    v.add(new DEROctetString(salt));
    if (!iterationCount.equals(ONE)) {
        v.add(new ASN1Integer(iterationCount));
    }
    return new DERSequence(v);
}
Also used : DERSequence(com.github.zhenwei.core.asn1.DERSequence) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector) ASN1Integer(com.github.zhenwei.core.asn1.ASN1Integer) DEROctetString(com.github.zhenwei.core.asn1.DEROctetString)

Aggregations

IOException (java.io.IOException)13 DigestInfo (com.github.zhenwei.core.asn1.x509.DigestInfo)7 KeyStoreException (java.security.KeyStoreException)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)6 PrivateKey (java.security.PrivateKey)6 UnrecoverableKeyException (java.security.UnrecoverableKeyException)6 Certificate (java.security.cert.Certificate)6 CertificateEncodingException (java.security.cert.CertificateEncodingException)6 CertificateException (java.security.cert.CertificateException)6 X509Certificate (java.security.cert.X509Certificate)6 Enumeration (java.util.Enumeration)6 Hashtable (java.util.Hashtable)6 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)6 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)6 DigestInfo (org.bouncycastle.asn1.x509.DigestInfo)6 AlgorithmIdentifier (com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier)5 OutputStream (java.io.OutputStream)5 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)5 ASN1OctetString (com.github.zhenwei.core.asn1.ASN1OctetString)4 DEROctetString (com.github.zhenwei.core.asn1.DEROctetString)4