Search in sources :

Example 6 with DigestInfo

use of es.gob.jmulticard.asn1.der.pkcs1.DigestInfo in project jmulticard by ctt-gob-es.

the class Ceres method sign.

@Override
public byte[] sign(final byte[] data, final String algorithm, final PrivateKeyReference keyRef) throws CryptoCardException, PinException {
    if (data == null) {
        // $NON-NLS-1$
        throw new CryptoCardException("Los datos a firmar no pueden ser nulos");
    }
    if (keyRef == null) {
        // $NON-NLS-1$
        throw new IllegalArgumentException("La clave privada no puede ser nula");
    }
    if (!(keyRef instanceof CeresPrivateKeyReference)) {
        throw new IllegalArgumentException(// $NON-NLS-1$
        "La clave proporcionada debe ser de tipo CeresPrivateKeyReference, pero se ha recibido de tipo " + keyRef.getClass().getName());
    }
    final CeresPrivateKeyReference ceresPrivateKey = (CeresPrivateKeyReference) keyRef;
    // Pedimos el PIN si no se ha pedido antes
    if (!this.authenticated) {
        try {
            verifyPin(getInternalPasswordCallback());
            this.authenticated = true;
        } catch (final ApduConnectionException e1) {
            // $NON-NLS-1$
            throw new CryptoCardException("Error en la verificacion de PIN: " + e1, e1);
        }
    }
    final byte[] digestInfo;
    try {
        digestInfo = DigestInfo.encode(algorithm, data, this.cryptoHelper);
    } catch (final Exception e) {
        throw new CryptoCardException(// $NON-NLS-1$ //$NON-NLS-2$
        "Error creando el DigestInfo para la firma con el algoritmo " + algorithm + ": " + e, // $NON-NLS-1$ //$NON-NLS-2$
        e);
    }
    loadData(ceresPrivateKey.getKeyBitSize(), digestInfo);
    final ResponseApdu res;
    final CommandApdu cmd = new SignDataApduCommand(// Referencia
    ceresPrivateKey.getKeyReference(), // Tamano en bits de la clave
    ceresPrivateKey.getKeyBitSize());
    try {
        res = sendArbitraryApdu(cmd);
    } catch (final Exception e) {
        // $NON-NLS-1$
        throw new CryptoCardException("Error firmando los datos: " + e, e);
    }
    if (!res.isOk()) {
        throw new CryptoCardException(// $NON-NLS-1$
        "No se han podido firmar los datos. Respuesta: " + HexUtils.hexify(res.getBytes(), true));
    }
    return res.getData();
}
Also used : CommandApdu(es.gob.jmulticard.apdu.CommandApdu) ResponseApdu(es.gob.jmulticard.apdu.ResponseApdu) SignDataApduCommand(es.gob.jmulticard.apdu.ceres.SignDataApduCommand) CryptoCardException(es.gob.jmulticard.card.CryptoCardException) ApduConnectionException(es.gob.jmulticard.apdu.connection.ApduConnectionException) ApduConnectionException(es.gob.jmulticard.apdu.connection.ApduConnectionException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) AuthenticationModeLockedException(es.gob.jmulticard.card.AuthenticationModeLockedException) FileNotFoundException(es.gob.jmulticard.card.iso7816four.FileNotFoundException) CryptoCardException(es.gob.jmulticard.card.CryptoCardException) InvalidCardException(es.gob.jmulticard.card.InvalidCardException) BadPinException(es.gob.jmulticard.card.BadPinException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) PinException(es.gob.jmulticard.card.PinException) TlvException(es.gob.jmulticard.asn1.TlvException) Iso7816FourCardException(es.gob.jmulticard.card.iso7816four.Iso7816FourCardException) Asn1Exception(es.gob.jmulticard.asn1.Asn1Exception)

Example 7 with DigestInfo

use of es.gob.jmulticard.asn1.der.pkcs1.DigestInfo in project jmulticard by ctt-gob-es.

the class Ceres method loadData.

private void loadData(final int keyBitSize, final byte[] digestInfo) throws CryptoCardException {
    final byte[] paddedData;
    try {
        paddedData = CryptoHelper.addPkcs1PaddingForPrivateKeyOperation(digestInfo, keyBitSize);
    } catch (final Exception e1) {
        throw new CryptoCardException(// $NON-NLS-1$
        "Error realizando el relleno PKCS#1 de los datos a firmar: " + e1, // $NON-NLS-1$
        e1);
    }
    ResponseApdu res;
    // Si la clave es de 1024 la carga se puede hacer en una unica APDU
    if (keyBitSize < 2048) {
        try {
            res = sendArbitraryApdu(new LoadDataApduCommand(paddedData));
        } catch (final Exception e) {
            throw new CryptoCardException(// $NON-NLS-1$
            "Error enviando los datos a firmar a la tarjeta: " + e, // $NON-NLS-1$
            e);
        }
        if (!res.isOk()) {
            throw new CryptoCardException(// $NON-NLS-1$
            "No se han podido enviar los datos a firmar a la tarjeta. Respuesta: " + HexUtils.hexify(res.getBytes(), true));
        }
    } else // Pero si es de 2048 hacen falta dos APDU, envolviendo la APDU de carga de datos
    if (keyBitSize == 2048) {
        final byte[] envelopedLoadDataApdu = new byte[] { (byte) 0x90, (byte) 0x58, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x00 };
        // La primera APDU carga 0xFF octetos (254)
        byte[] data = new byte[255];
        System.arraycopy(envelopedLoadDataApdu, 0, data, 0, envelopedLoadDataApdu.length);
        System.arraycopy(paddedData, 0, data, envelopedLoadDataApdu.length, 255 - envelopedLoadDataApdu.length);
        try {
            res = sendArbitraryApdu(new EnvelopeDataApduCommand(data));
        } catch (final Exception e) {
            throw new CryptoCardException(// $NON-NLS-1$
            "Error en el primer envio a la tarjeta de los datos a firmar: " + e, // $NON-NLS-1$
            e);
        }
        if (!res.isOk()) {
            throw new CryptoCardException(// $NON-NLS-1$
            "No se han podido enviar (primera tanda) los datos a firmar a la tarjeta. Respuesta: " + HexUtils.hexify(res.getBytes(), true));
        }
        // La segunda APDU es de 0x08 octetos (8)
        data = new byte[8];
        System.arraycopy(paddedData, 255 - envelopedLoadDataApdu.length, data, 0, 8);
        try {
            res = sendArbitraryApdu(new EnvelopeDataApduCommand(data));
        } catch (final Exception e) {
            throw new CryptoCardException(// $NON-NLS-1$
            "Error en el segundo envio a la tarjeta de los datos a firmar: " + e, // $NON-NLS-1$
            e);
        }
        if (!res.isOk()) {
            throw new CryptoCardException(// $NON-NLS-1$
            "No se han podido enviar (segunda tanda) los datos a firmar a la tarjeta. Respuesta: " + HexUtils.hexify(res.getBytes(), true));
        }
    } else {
        // $NON-NLS-1$
        throw new IllegalArgumentException("Solo se soportan claves de 2048 o menos bits");
    }
}
Also used : EnvelopeDataApduCommand(es.gob.jmulticard.apdu.iso7816eight.EnvelopeDataApduCommand) ResponseApdu(es.gob.jmulticard.apdu.ResponseApdu) CryptoCardException(es.gob.jmulticard.card.CryptoCardException) ApduConnectionException(es.gob.jmulticard.apdu.connection.ApduConnectionException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) AuthenticationModeLockedException(es.gob.jmulticard.card.AuthenticationModeLockedException) FileNotFoundException(es.gob.jmulticard.card.iso7816four.FileNotFoundException) CryptoCardException(es.gob.jmulticard.card.CryptoCardException) InvalidCardException(es.gob.jmulticard.card.InvalidCardException) BadPinException(es.gob.jmulticard.card.BadPinException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) PinException(es.gob.jmulticard.card.PinException) TlvException(es.gob.jmulticard.asn1.TlvException) Iso7816FourCardException(es.gob.jmulticard.card.iso7816four.Iso7816FourCardException) Asn1Exception(es.gob.jmulticard.asn1.Asn1Exception) LoadDataApduCommand(es.gob.jmulticard.apdu.ceres.LoadDataApduCommand)

Example 8 with DigestInfo

use of es.gob.jmulticard.asn1.der.pkcs1.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 9 with DigestInfo

use of es.gob.jmulticard.asn1.der.pkcs1.DigestInfo in project jmulticard by ctt-gob-es.

the class DigestInfo method encode.

/**
 * Codifica una estructura <code>DigestInfo</code>.
 * @param signingAlgorithm Algoritmo de huella digital o de firma electr&oacute;nica.
 * @param data Datos de los que obtener la estructura.
 * @param cryptoHelper Manejador de operaciones criptogr&aacute;ficas.
 * @return Estructura DigestInfo.
 * @throws IOException Cuando se produce algun error en la estrucura de la estructura.
 */
public static byte[] encode(final String signingAlgorithm, final byte[] data, final CryptoHelper cryptoHelper) throws IOException {
    final String normalizedSignningAlgorithm = getNormalizedSigningAlgorithm(signingAlgorithm);
    final DigestAlgorithm digestAlgorithm = getDigestAlgorithm(normalizedSignningAlgorithm);
    final byte[] header = selectHeaderTemplate(digestAlgorithm);
    final byte[] md = cryptoHelper.digest(digestAlgorithm, data);
    final byte[] digestInfo = new byte[header.length + md.length];
    System.arraycopy(header, 0, digestInfo, 0, header.length);
    System.arraycopy(md, 0, digestInfo, header.length, md.length);
    return digestInfo;
}
Also used : OctectString(es.gob.jmulticard.asn1.der.OctectString) DigestAlgorithm(es.gob.jmulticard.CryptoHelper.DigestAlgorithm)

Example 10 with DigestInfo

use of es.gob.jmulticard.asn1.der.pkcs1.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)

Aggregations

IOException (java.io.IOException)11 CertificateException (java.security.cert.CertificateException)7 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)5 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)5 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)5 DigestInfo (org.bouncycastle.asn1.x509.DigestInfo)5 KeyStoreException (java.security.KeyStoreException)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 PrivateKey (java.security.PrivateKey)4 UnrecoverableKeyException (java.security.UnrecoverableKeyException)4 Certificate (java.security.cert.Certificate)4 CertificateEncodingException (java.security.cert.CertificateEncodingException)4 X509Certificate (java.security.cert.X509Certificate)4 Enumeration (java.util.Enumeration)4 Hashtable (java.util.Hashtable)4 DERBMPString (org.bouncycastle.asn1.DERBMPString)4 DEROctetString (org.bouncycastle.asn1.DEROctetString)4 AuthenticatedSafe (org.bouncycastle.asn1.pkcs.AuthenticatedSafe)4 CertBag (org.bouncycastle.asn1.pkcs.CertBag)4 ContentInfo (org.bouncycastle.asn1.pkcs.ContentInfo)4