Package es.gob.jmulticard
Class BcCryptoHelper
- java.lang.Object
-
- es.gob.jmulticard.CryptoHelper
-
- es.gob.jmulticard.BcCryptoHelper
-
public final class BcCryptoHelper extends CryptoHelper
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 Classes Modifier and Type Class Description private static classBcCryptoHelper.CertHolderBySignerIdSelectorSelector interno para la lectura de los certificados del firmante del SOD.static classBcCryptoHelper.CustomRsaPublicKeyClave pública RSA con control directo de la creaci&oaccute;n comoBigIntegerde 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
Fields Modifier and Type Field Description private static java.util.logging.LoggerLOGGERLogger por defecto.private CryptoHelper.PaceChannelHelperpaceChannelHelper
-
Constructor Summary
Constructors Constructor Description BcCryptoHelper()
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description private static java.security.spec.ECPointadd(java.security.spec.ECPoint x, java.security.spec.ECPoint y, java.security.spec.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 java.math.BigIntegercomputeAffineY(java.math.BigInteger affineX, java.security.spec.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[]doRsa(byte[] data, java.security.interfaces.RSAKey key, boolean forEncryption)private static java.security.spec.ECPointfromSpongyCastleECPoint(org.bouncycastle.math.ec.ECPoint point)java.security.cert.X509CertificategenerateCertificate(byte[] encoded)Genera un certificado a partir de su codificación binaria.java.security.cert.X509CertificategenerateCertificate(java.io.InputStream is)Genera un certificado a partir de un flujo hacia su codificación binaria.java.security.KeyPairgenerateEcKeyPair(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.java.security.spec.AlgorithmParameterSpecgetEcPoint(byte[] nonceS, byte[] sharedSecretH, CryptoHelper.EcCurve curveName)Obtiene un punto en una curva elíptica.CryptoHelper.PaceChannelHelpergetPaceChannelHelper()Obtiene las utilidades para el establecimiento de un canal PACE (Password Authenticated Connection Establishment).private static java.math.BigIntegergetPrime(java.security.spec.ECParameterSpec params)java.security.interfaces.RSAPublicKeygetRsaPublicKey(java.security.cert.X509Certificate cert)Obtiene una clave pública de un certificado.private static java.security.spec.ECParameterSpecmapNonceGMWithECDH(java.math.BigInteger nonceS, java.security.spec.ECPoint sharedSecretPointH, java.security.spec.ECParameterSpec params)private static java.security.spec.ECPointmultiply(java.math.BigInteger s, java.security.spec.ECPoint point, java.security.spec.ECParameterSpec params)private static java.math.BigIntegeros2i(byte[] bytes)Convierte unOctet Stringde ASN.1 en un entero (según BSI TR 03111 Sección 3.1.2).private static java.math.BigIntegeros2i(byte[] bytes, int offset, int length)Convierte unOctet Stringde 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, java.security.interfaces.RSAKey key)Desencripta datos mediante RSA.byte[]rsaEncrypt(byte[] data, java.security.interfaces.RSAKey key)Encripta datos mediante RSA.private static org.bouncycastle.math.ec.ECCurvetoSpongyCastleECCurve(java.security.spec.ECParameterSpec params)private static org.bouncycastle.math.ec.ECPointtoSpongyCastleECPoint(java.security.spec.ECPoint point, java.security.spec.ECParameterSpec params)java.security.cert.X509Certificate[]validateCmsSignature(byte[] signedDataBytes)Valida una firma CMS/PKCS#7.-
Methods inherited from class es.gob.jmulticard.CryptoHelper
addPkcs1PaddingForPrivateKeyOperation
-
-
-
-
Field Detail
-
LOGGER
private static final java.util.logging.Logger LOGGER
Logger por defecto.
-
paceChannelHelper
private transient CryptoHelper.PaceChannelHelper paceChannelHelper
-
-
Method Detail
-
digest
public byte[] digest(CryptoHelper.DigestAlgorithm algorithm, byte[] data) throws java.io.IOException
Description copied from class:CryptoHelperRealiza una huella digital de los datos proporcionados.- Specified by:
digestin classCryptoHelper- Parameters:
algorithm- Algoritmo de huella digital que debe utilizarse.data- Datos de entrada.- Returns:
- Huella digital de los datos.
- Throws:
java.io.IOException- Si ocurre algún problema generando la huella digital.
-
doDesede
private static byte[] doDesede(byte[] data, byte[] key, boolean forEncryption) throws java.io.IOExceptionRealiza 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:
java.io.IOException- Si ocurre cualquier error durante el proceso.
-
desedeEncrypt
public byte[] desedeEncrypt(byte[] data, byte[] rawKey) throws java.io.IOExceptionDescription copied from class:CryptoHelperEncripta 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:
desedeEncryptin classCryptoHelper- Parameters:
data- Datos a encriptar.rawKey- Clave 3DES de cifrado.- Returns:
- Datos cifrados.
- Throws:
java.io.IOException- Si ocurre algún problema durante el encriptado.
-
desedeDecrypt
public byte[] desedeDecrypt(byte[] data, byte[] rawKey) throws java.io.IOExceptionDescription copied from class:CryptoHelperDesencripta 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:
desedeDecryptin classCryptoHelper- Parameters:
data- Datos a desencriptar.rawKey- Clave 3DES de descifrado.- Returns:
- Datos descifrados.
- Throws:
java.io.IOException- Si ocurre algún problema durante el desencriptado.
-
prepareDesedeKey
private static byte[] prepareDesedeKey(byte[] key)
-
doDes
private static byte[] doDes(byte[] data, byte[] key, boolean forEncryption) throws java.io.IOException- Throws:
java.io.IOException
-
desEncrypt
public byte[] desEncrypt(byte[] data, byte[] key) throws java.io.IOExceptionDescription copied from class:CryptoHelperEncripta datos mediante DES (modo ECB sin relleno).- Specified by:
desEncryptin classCryptoHelper- Parameters:
data- Datos a encriptar.key- Clave DES de cifrado.- Returns:
- Datos cifrados.
- Throws:
java.io.IOException- Si ocurre algún problema durante el encriptado.
-
desDecrypt
public byte[] desDecrypt(byte[] data, byte[] key) throws java.io.IOExceptionDescription copied from class:CryptoHelperDesencripta datos mediante DES (modo ECB sin relleno).- Specified by:
desDecryptin classCryptoHelper- Parameters:
data- Datos a desencriptar.key- Clave DES de descifrado.- Returns:
- Datos descifrados.
- Throws:
java.io.IOException- Si ocurre algún problema durante el desencriptado.
-
doRsa
private static byte[] doRsa(byte[] data, java.security.interfaces.RSAKey key, boolean forEncryption) throws java.io.IOException- Throws:
java.io.IOException
-
rsaDecrypt
public byte[] rsaDecrypt(byte[] cipheredData, java.security.interfaces.RSAKey key) throws java.io.IOExceptionDescription copied from class:CryptoHelperDesencripta datos mediante RSA.- Specified by:
rsaDecryptin classCryptoHelper- Parameters:
cipheredData- Datos a desencriptar.key- Clava RSA de descifrado.- Returns:
- Datos descifrados.
- Throws:
java.io.IOException- Si ocurre algún problema durante el desencriptado.
-
rsaEncrypt
public byte[] rsaEncrypt(byte[] data, java.security.interfaces.RSAKey key) throws java.io.IOExceptionDescription copied from class:CryptoHelperEncripta datos mediante RSA.- Specified by:
rsaEncryptin classCryptoHelper- Parameters:
data- Datos a encriptar.key- Clava RSA de cifrado.- Returns:
- Datos encriptados.
- Throws:
java.io.IOException- Si ocurre algún problema durante el encriptado.
-
generateRandomBytes
public byte[] generateRandomBytes(int numBytes)
Description copied from class:CryptoHelperGenera contenido aleatorio en un array de bytes.- Specified by:
generateRandomBytesin 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 java.io.IOException, org.bouncycastle.crypto.InvalidCipherTextException- Throws:
java.io.IOExceptionorg.bouncycastle.crypto.InvalidCipherTextException
-
aesDecrypt
public byte[] aesDecrypt(byte[] data, byte[] iv, byte[] key, CryptoHelper.BlockMode blockMode, CryptoHelper.Padding padding) throws java.io.IOExceptionDescription copied from class:CryptoHelperDesencripta datos mediante AES.- Specified by:
aesDecryptin classCryptoHelper- Parameters:
data- Datos a encriptar.iv- Vector de inicialización. Si se proporcionanullse 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:
java.io.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 java.io.IOExceptionDescription copied from class:CryptoHelperEncripta datos mediante AES.- Specified by:
aesEncryptin classCryptoHelper- Parameters:
data- Datos a encriptar.iv- Vector de inicialización. Si se proporcionanullse 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:
java.io.IOException- Si ocurre algún problema durante el encriptado.
-
generateEcKeyPair
public java.security.KeyPair generateEcKeyPair(CryptoHelper.EcCurve curveName) throws java.security.NoSuchAlgorithmException, java.security.InvalidAlgorithmParameterException
Description copied from class:CryptoHelperGenera un par de claves de tipo curva elíptica.- Specified by:
generateEcKeyPairin classCryptoHelper- Parameters:
curveName- Tipo de curva elíptica a utilizar.- Returns:
- Par de claves generadas.
- Throws:
java.security.NoSuchAlgorithmException- Si el sistema no soporta la generación de curvas elípticas.java.security.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:CryptoHelperRealiza un CMAC con AES.- Specified by:
doAesCmacin classCryptoHelper- Parameters:
data- Datos (deben estar ya con el relleno adecuado).key- Clave AES.- Returns:
- CMAC.
-
getEcPoint
public java.security.spec.AlgorithmParameterSpec getEcPoint(byte[] nonceS, byte[] sharedSecretH, CryptoHelper.EcCurve curveName)Description copied from class:CryptoHelperObtiene un punto en una curva elíptica.- Specified by:
getEcPointin classCryptoHelper- Parameters:
nonceS- Aleatorio de un solo uso.sharedSecretH- Secreto compartido.curveName- Nombre de la curva.- Returns:
- Punto encapsulado.
-
os2i
private static java.math.BigInteger os2i(byte[] bytes)
Convierte unOctet Stringde 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
private static java.math.BigInteger os2i(byte[] bytes, int offset, int length)Convierte unOctet Stringde ASN.1 en un entero (según BSI TR 03111 Sección 3.1.2).- Parameters:
bytes-Octet Stringde ASN.1.offset- Desplazamiento (posición de inicio).length- Longitud delOctet String.- Returns:
- Entero (siempre positivo).
-
computeAffineY
private static java.math.BigInteger computeAffineY(java.math.BigInteger affineX, java.security.spec.ECParameterSpec params)
-
toSpongyCastleECCurve
private static org.bouncycastle.math.ec.ECCurve toSpongyCastleECCurve(java.security.spec.ECParameterSpec params)
-
getPrime
private static java.math.BigInteger getPrime(java.security.spec.ECParameterSpec params)
-
mapNonceGMWithECDH
private static java.security.spec.ECParameterSpec mapNonceGMWithECDH(java.math.BigInteger nonceS, java.security.spec.ECPoint sharedSecretPointH, java.security.spec.ECParameterSpec params)
-
multiply
private static java.security.spec.ECPoint multiply(java.math.BigInteger s, java.security.spec.ECPoint point, java.security.spec.ECParameterSpec params)
-
fromSpongyCastleECPoint
private static java.security.spec.ECPoint fromSpongyCastleECPoint(org.bouncycastle.math.ec.ECPoint point)
-
add
private static java.security.spec.ECPoint add(java.security.spec.ECPoint x, java.security.spec.ECPoint y, java.security.spec.ECParameterSpec params)
-
toSpongyCastleECPoint
private static org.bouncycastle.math.ec.ECPoint toSpongyCastleECPoint(java.security.spec.ECPoint point, java.security.spec.ECParameterSpec params)
-
validateCmsSignature
public java.security.cert.X509Certificate[] validateCmsSignature(byte[] signedDataBytes) throws java.security.SignatureException, java.io.IOException, java.security.cert.CertificateExceptionDescription copied from class:CryptoHelperValida una firma CMS/PKCS#7. No comprueba la validez de los certificados de firma.- Specified by:
validateCmsSignaturein classCryptoHelper- Parameters:
signedDataBytes- Firma CMS/PKCS#7.- Returns:
- Cadena de certificados del firmante (para validación externa).
- Throws:
java.security.SignatureException- Si la firma es inválida o está mal formada.java.io.IOException- Si los datos proporcionados no son una firma CMS/PKCS#7 bien formada.java.security.cert.CertificateException- Si hay problemas relacionados con los certificados de firma.
-
getCmsSignatureSignedContent
public byte[] getCmsSignatureSignedContent(byte[] signedDataBytes) throws java.io.IOExceptionDescription copied from class:CryptoHelperObtiene el contenido firmado de una firma CMS/PKCS#7.- Specified by:
getCmsSignatureSignedContentin classCryptoHelper- Parameters:
signedDataBytes- Firma CMS/PKCS#7.- Returns:
- Contenido firmado de una firma CMS/PKCS#7.
- Throws:
java.io.IOException- Si los datos proporcionados no son una firma CMS/PKCS#7 bien formada.
-
generateCertificate
public java.security.cert.X509Certificate generateCertificate(byte[] encoded) throws java.security.cert.CertificateExceptionGenera un certificado a partir de su codificación binaria.- Specified by:
generateCertificatein classCryptoHelper- Parameters:
encoded- Codificación binaria del certificado.- Returns:
- Certificado.
- Throws:
java.security.cert.CertificateException- Si la codificación binaria no correspondía a un certificado.
-
generateCertificate
public java.security.cert.X509Certificate generateCertificate(java.io.InputStream is) throws java.security.cert.CertificateExceptionGenera un certificado a partir de un flujo hacia su codificación binaria.- Specified by:
generateCertificatein classCryptoHelper- Parameters:
is- Flujo de lectura hacia la Codificación binaria del certificado.- Returns:
- Certificado.
- Throws:
java.security.cert.CertificateException- Si la codificación binaria no correspondía a un certificado o no se pudo leer del flujo de entrada.
-
getPaceChannelHelper
public CryptoHelper.PaceChannelHelper getPaceChannelHelper()
Description copied from class:CryptoHelperObtiene las utilidades para el establecimiento de un canal PACE (Password Authenticated Connection Establishment).- Specified by:
getPaceChannelHelperin classCryptoHelper- Returns:
- Utilidades para el establecimiento de un canal PACE
-
getRsaPublicKey
public java.security.interfaces.RSAPublicKey getRsaPublicKey(java.security.cert.X509Certificate cert)
Description copied from class:CryptoHelperObtiene una clave pública de un certificado. La razón de tener este método en vez de invocar directamente aldel certificado es evitar problemas por la interpretaci&oaccute;n del signo del BigIntegeren ciertos entornos (como J2Obc).- Specified by:
getRsaPublicKeyin classCryptoHelper- Parameters:
cert- Certificado de origen.- Returns:
- Clave pública RSA del certificado.
-
-