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();
}
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");
}
}
use of es.gob.jmulticard.asn1.der.pkcs1.DigestInfo in project jmulticard by ctt-gob-es.
the class TestAsn1SimpleTypes method testDigestInfoCreation.
/**
* Prueba de creació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);
}
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ónica.
* @param data Datos de los que obtener la estructura.
* @param cryptoHelper Manejador de operaciones criptográ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;
}
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();
}
}
}
Aggregations