Package es.gob.jmulticard
Class BcCryptoHelper
java.lang.Object
es.gob.jmulticard.CryptoHelper
es.gob.jmulticard.BcCryptoHelper
Funcionalidades criptográficas de utilidad implementadas mediante BouncyCastle.
Contiene código basado en el trabajo del JMRTD team, bajo licencia
GNU Lesser General Public License (LGPL) versión 2.1 o posterior.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static final class
Selector interno para la lectura de los certificados del firmante del SOD.static class
Clave pública RSA con control directo de la creaci&oaccute;n comoBigInteger
de módulo y exponente (para evitar problemas de interpretación del signo (que puede darse en entornos como J2Obc).Nested classes/interfaces inherited from class es.gob.jmulticard.CryptoHelper
CryptoHelper.BlockMode, CryptoHelper.DigestAlgorithm, CryptoHelper.EcCurve, CryptoHelper.PaceChannelHelper, CryptoHelper.Padding
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static final Logger
Logger por defecto.private CryptoHelper.PaceChannelHelper
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprivate static ECPoint
add
(ECPoint x, ECPoint y, ECParameterSpec params) byte[]
aesDecrypt
(byte[] data, byte[] iv, byte[] key, CryptoHelper.BlockMode blockMode, CryptoHelper.Padding padding) Desencripta datos mediante AES.byte[]
aesEncrypt
(byte[] data, byte[] iv, byte[] key, CryptoHelper.BlockMode blockMode, CryptoHelper.Padding padding) Encripta datos mediante AES.private static byte[]
aesEncryptSingleBlock
(byte[] key, byte[] dataBlock) Encripta un único bloque usando AES.private static BigInteger
computeAffineY
(BigInteger affineX, ECParameterSpec params) byte[]
desDecrypt
(byte[] data, byte[] key) Desencripta datos mediante DES (modo ECB sin relleno).byte[]
desedeDecrypt
(byte[] data, byte[] rawKey) Desencripta datos mediante Triple DES (modo CBC sin relleno) y con una semilla (IV) de 8 bytes establecidos a cero.byte[]
desedeEncrypt
(byte[] data, byte[] rawKey) Encripta datos mediante Triple DES (modo CBC sin relleno) y con una semilla (IV) de 8 bytes establecidos a cero.byte[]
desEncrypt
(byte[] data, byte[] key) Encripta datos mediante DES (modo ECB sin relleno).byte[]
digest
(CryptoHelper.DigestAlgorithm algorithm, byte[] data) Realiza una huella digital de los datos proporcionados.private static byte[]
doAes
(byte[] data, byte[] iv, byte[] aesKey, org.bouncycastle.crypto.paddings.BlockCipherPadding padding, boolean forEncryption) byte[]
doAesCmac
(byte[] data, byte[] key) Realiza un CMAC con AES.private static byte[]
doDes
(byte[] data, byte[] key, boolean forEncryption) private static byte[]
doDesede
(byte[] data, byte[] key, boolean forEncryption) Realiza una operación 3DES.private static byte[]
private static ECPoint
fromSpongyCastleECPoint
(org.bouncycastle.math.ec.ECPoint point) generateCertificate
(byte[] encoded) Genera un certificado a partir de su codificación binaria.Genera un certificado a partir de un flujo hacia su codificación binaria.generateEcKeyPair
(CryptoHelper.EcCurve curveName) Genera un par de claves de tipo curva elíptica.byte[]
generateRandomBytes
(int numBytes) Genera contenido aleatorio en un array de bytes.byte[]
getCmsSignatureSignedContent
(byte[] signedDataBytes) Obtiene el contenido firmado de una firma CMS/PKCS#7.getEcPoint
(byte[] nonceS, byte[] sharedSecretH, CryptoHelper.EcCurve curveName) Obtiene un punto en una curva elíptica.Obtiene las utilidades para el establecimiento de un canal PACE (Password Authenticated Connection Establishment).private static BigInteger
getPrime
(ECParameterSpec params) Obtiene una clave pública de un certificado.private static ECParameterSpec
mapNonceGMWithECDH
(BigInteger nonceS, ECPoint sharedSecretPointH, ECParameterSpec params) private static ECPoint
multiply
(BigInteger s, ECPoint point, ECParameterSpec params) private static BigInteger
os2i
(byte[] bytes) Convierte unOctet String
de ASN.1 en un entero (según BSI TR 03111 Sección 3.1.2).private static BigInteger
os2i
(byte[] bytes, int offset, int length) Convierte unOctet String
de ASN.1 en un entero (según BSI TR 03111 Sección 3.1.2).private static byte[]
prepareDesedeKey
(byte[] key) byte[]
rsaDecrypt
(byte[] cipheredData, RSAKey key) Desencripta datos mediante RSA.byte[]
rsaEncrypt
(byte[] data, RSAKey key) Encripta datos mediante RSA.private static org.bouncycastle.math.ec.ECCurve
toSpongyCastleECCurve
(ECParameterSpec params) private static org.bouncycastle.math.ec.ECPoint
toSpongyCastleECPoint
(ECPoint point, ECParameterSpec params) validateCmsSignature
(byte[] signedDataBytes) Valida una firma CMS/PKCS#7.Methods inherited from class es.gob.jmulticard.CryptoHelper
addPkcs1PaddingForPrivateKeyOperation
-
Field Details
-
LOGGER
Logger por defecto. -
paceChannelHelper
-
-
Constructor Details
-
BcCryptoHelper
public BcCryptoHelper()
-
-
Method Details
-
digest
Description copied from class:CryptoHelper
Realiza una huella digital de los datos proporcionados.- Specified by:
digest
in classCryptoHelper
- Parameters:
algorithm
- Algoritmo de huella digital que debe utilizarse.data
- Datos de entrada.- Returns:
- Huella digital de los datos.
- Throws:
IOException
- Si ocurre algún problema generando la huella digital.
-
doDesede
Realiza una operación 3DES.- Parameters:
data
- Datos a cifrar o descifrar.key
- Clave 3DES.forEncryption
- Si se debe cifrar o descifrar.- Returns:
- Datos cifrados o descifrados.
- Throws:
IOException
- Si ocurre cualquier error durante el proceso.
-
desedeEncrypt
Description copied from class:CryptoHelper
Encripta datos mediante Triple DES (modo CBC sin relleno) y con una semilla (IV) de 8 bytes establecidos a cero. Si se le indica una clave de 24 bytes, la utilizaráa tal cual. Si se le indica una clave de 16 bytes, duplicará los 8 primeros y los agregará al final para obtener una de 24.- Specified by:
desedeEncrypt
in classCryptoHelper
- Parameters:
data
- Datos a encriptar.rawKey
- Clave 3DES de cifrado.- Returns:
- Datos cifrados.
- Throws:
IOException
- Si ocurre algún problema durante el encriptado.
-
desedeDecrypt
Description copied from class:CryptoHelper
Desencripta datos mediante Triple DES (modo CBC sin relleno) y con una semilla (IV) de 8 bytes establecidos a cero. Si se le indica una clave de 24 bytes, la utilizaráa tal cual. Si se le indica una clave de 16 bytes, duplicará los 8 primeros y los agregará al final para obtener una de 24.- Specified by:
desedeDecrypt
in classCryptoHelper
- Parameters:
data
- Datos a desencriptar.rawKey
- Clave 3DES de descifrado.- Returns:
- Datos descifrados.
- Throws:
IOException
- Si ocurre algún problema durante el desencriptado.
-
prepareDesedeKey
private static byte[] prepareDesedeKey(byte[] key) -
doDes
- Throws:
IOException
-
desEncrypt
Description copied from class:CryptoHelper
Encripta datos mediante DES (modo ECB sin relleno).- Specified by:
desEncrypt
in classCryptoHelper
- Parameters:
data
- Datos a encriptar.key
- Clave DES de cifrado.- Returns:
- Datos cifrados.
- Throws:
IOException
- Si ocurre algún problema durante el encriptado.
-
desDecrypt
Description copied from class:CryptoHelper
Desencripta datos mediante DES (modo ECB sin relleno).- Specified by:
desDecrypt
in classCryptoHelper
- Parameters:
data
- Datos a desencriptar.key
- Clave DES de descifrado.- Returns:
- Datos descifrados.
- Throws:
IOException
- Si ocurre algún problema durante el desencriptado.
-
doRsa
- Throws:
IOException
-
rsaDecrypt
Description copied from class:CryptoHelper
Desencripta datos mediante RSA.- Specified by:
rsaDecrypt
in classCryptoHelper
- Parameters:
cipheredData
- Datos a desencriptar.key
- Clava RSA de descifrado.- Returns:
- Datos descifrados.
- Throws:
IOException
- Si ocurre algún problema durante el desencriptado.
-
rsaEncrypt
Description copied from class:CryptoHelper
Encripta datos mediante RSA.- Specified by:
rsaEncrypt
in classCryptoHelper
- Parameters:
data
- Datos a encriptar.key
- Clava RSA de cifrado.- Returns:
- Datos encriptados.
- Throws:
IOException
- Si ocurre algún problema durante el encriptado.
-
generateRandomBytes
public byte[] generateRandomBytes(int numBytes) Description copied from class:CryptoHelper
Genera contenido aleatorio en un array de bytes.- Specified by:
generateRandomBytes
in classCryptoHelper
- Parameters:
numBytes
- Número de bytes aleatorios que generar.- Returns:
- Array de bytes aleatorios.
-
aesEncryptSingleBlock
private static byte[] aesEncryptSingleBlock(byte[] key, byte[] dataBlock) Encripta un único bloque usando AES.- Parameters:
key
- Clave AES.dataBlock
- Bloque a crifrar.- Returns:
- Bloque cifrado.
-
doAes
private static byte[] doAes(byte[] data, byte[] iv, byte[] aesKey, org.bouncycastle.crypto.paddings.BlockCipherPadding padding, boolean forEncryption) throws IOException, org.bouncycastle.crypto.InvalidCipherTextException - Throws:
IOException
org.bouncycastle.crypto.InvalidCipherTextException
-
aesDecrypt
public byte[] aesDecrypt(byte[] data, byte[] iv, byte[] key, CryptoHelper.BlockMode blockMode, CryptoHelper.Padding padding) throws IOException Description copied from class:CryptoHelper
Desencripta datos mediante AES.- Specified by:
aesDecrypt
in classCryptoHelper
- Parameters:
data
- Datos a encriptar.iv
- Vector de inicialización. Si se proporcionanull
se usará un vector con valores aleatorios.key
- Clave AES de cifrado.blockMode
- Modo de gestión de bloques.padding
- Relleno a usar en los datos de entrada.- Returns:
- Datos cifrados.
- Throws:
IOException
- Si ocurre algún problema durante el encriptado.
-
aesEncrypt
public byte[] aesEncrypt(byte[] data, byte[] iv, byte[] key, CryptoHelper.BlockMode blockMode, CryptoHelper.Padding padding) throws IOException Description copied from class:CryptoHelper
Encripta datos mediante AES.- Specified by:
aesEncrypt
in classCryptoHelper
- Parameters:
data
- Datos a encriptar.iv
- Vector de inicialización. Si se proporcionanull
se usará un vector con valores aleatorios.key
- Clave AES de cifrado.blockMode
- Modo de gestión de bloques.padding
- Relleno a usar en los datos de entrada.- Returns:
- Datos cifrados.
- Throws:
IOException
- Si ocurre algún problema durante el encriptado.
-
generateEcKeyPair
public KeyPair generateEcKeyPair(CryptoHelper.EcCurve curveName) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException Description copied from class:CryptoHelper
Genera un par de claves de tipo curva elíptica.- Specified by:
generateEcKeyPair
in classCryptoHelper
- Parameters:
curveName
- Tipo de curva elíptica a utilizar.- Returns:
- Par de claves generadas.
- Throws:
NoSuchAlgorithmException
- Si el sistema no soporta la generación de curvas elípticas.InvalidAlgorithmParameterException
- Si el sistema no soporta el tipo de curva elíptica indicada.
-
doAesCmac
public byte[] doAesCmac(byte[] data, byte[] key) Description copied from class:CryptoHelper
Realiza un CMAC con AES.- Specified by:
doAesCmac
in classCryptoHelper
- Parameters:
data
- Datos (deben estar ya con el relleno adecuado).key
- Clave AES.- Returns:
- CMAC.
-
getEcPoint
public AlgorithmParameterSpec getEcPoint(byte[] nonceS, byte[] sharedSecretH, CryptoHelper.EcCurve curveName) Description copied from class:CryptoHelper
Obtiene un punto en una curva elíptica.- Specified by:
getEcPoint
in classCryptoHelper
- Parameters:
nonceS
- Aleatorio de un solo uso.sharedSecretH
- Secreto compartido.curveName
- Nombre de la curva.- Returns:
- Punto encapsulado.
-
os2i
Convierte unOctet String
de ASN.1 en un entero (según BSI TR 03111 Sección 3.1.2).- Parameters:
bytes
- Octet String de ASN.1.- Returns:
- Entero (siempre positivo).
-
os2i
Convierte unOctet String
de ASN.1 en un entero (según BSI TR 03111 Sección 3.1.2).- Parameters:
bytes
-Octet String
de ASN.1.offset
- Desplazamiento (posición de inicio).length
- Longitud delOctet String
.- Returns:
- Entero (siempre positivo).
-
computeAffineY
-
toSpongyCastleECCurve
-
getPrime
-
mapNonceGMWithECDH
private static ECParameterSpec mapNonceGMWithECDH(BigInteger nonceS, ECPoint sharedSecretPointH, ECParameterSpec params) -
multiply
-
fromSpongyCastleECPoint
-
add
-
toSpongyCastleECPoint
private static org.bouncycastle.math.ec.ECPoint toSpongyCastleECPoint(ECPoint point, ECParameterSpec params) -
validateCmsSignature
public X509Certificate[] validateCmsSignature(byte[] signedDataBytes) throws SignatureException, IOException, CertificateException Description copied from class:CryptoHelper
Valida una firma CMS/PKCS#7. No comprueba la validez de los certificados de firma.- Specified by:
validateCmsSignature
in classCryptoHelper
- Parameters:
signedDataBytes
- Firma CMS/PKCS#7.- Returns:
- Cadena de certificados del firmante (para validación externa).
- Throws:
SignatureException
- Si la firma es inválida o está mal formada.IOException
- Si los datos proporcionados no son una firma CMS/PKCS#7 bien formada.CertificateException
- Si hay problemas relacionados con los certificados de firma.
-
getCmsSignatureSignedContent
Description copied from class:CryptoHelper
Obtiene el contenido firmado de una firma CMS/PKCS#7.- Specified by:
getCmsSignatureSignedContent
in classCryptoHelper
- Parameters:
signedDataBytes
- Firma CMS/PKCS#7.- Returns:
- Contenido firmado de una firma CMS/PKCS#7.
- Throws:
IOException
- Si los datos proporcionados no son una firma CMS/PKCS#7 bien formada.
-
generateCertificate
Genera un certificado a partir de su codificación binaria.- Specified by:
generateCertificate
in classCryptoHelper
- Parameters:
encoded
- Codificación binaria del certificado.- Returns:
- Certificado.
- Throws:
CertificateException
- Si la codificación binaria no correspondía a un certificado.
-
generateCertificate
Genera un certificado a partir de un flujo hacia su codificación binaria.- Specified by:
generateCertificate
in classCryptoHelper
- Parameters:
is
- Flujo de lectura hacia la Codificación binaria del certificado.- Returns:
- Certificado.
- Throws:
CertificateException
- Si la codificación binaria no correspondía a un certificado o no se pudo leer del flujo de entrada.
-
getPaceChannelHelper
Description copied from class:CryptoHelper
Obtiene las utilidades para el establecimiento de un canal PACE (Password Authenticated Connection Establishment).- Specified by:
getPaceChannelHelper
in classCryptoHelper
- Returns:
- Utilidades para el establecimiento de un canal PACE
-
getRsaPublicKey
Description copied from class:CryptoHelper
Obtiene una clave pública de un certificado. La razón de tener este método en vez de invocar directamente alinvalid input: '<'getPublicKey()
del certificado es evitar problemas por la interpretaci&oaccute;n del signo delBigInteger
en ciertos entornos (como J2Obc).- Specified by:
getRsaPublicKey
in classCryptoHelper
- Parameters:
cert
- Certificado de origen.- Returns:
- Clave pública RSA del certificado.
-