Class 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.
    • 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.ECPoint add​(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.BigInteger computeAffineY​(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.ECPoint fromSpongyCastleECPoint​(org.bouncycastle.math.ec.ECPoint point)  
      java.security.cert.X509Certificate generateCertificate​(byte[] encoded)
      Genera un certificado a partir de su codificación binaria.
      java.security.cert.X509Certificate generateCertificate​(java.io.InputStream is)
      Genera un certificado a partir de un flujo hacia su codificación binaria.
      java.security.KeyPair 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.
      java.security.spec.AlgorithmParameterSpec getEcPoint​(byte[] nonceS, byte[] sharedSecretH, CryptoHelper.EcCurve curveName)
      Obtiene un punto en una curva elíptica.
      CryptoHelper.PaceChannelHelper getPaceChannelHelper()
      Obtiene las utilidades para el establecimiento de un canal PACE (Password Authenticated Connection Establishment).
      private static java.math.BigInteger getPrime​(java.security.spec.ECParameterSpec params)  
      java.security.interfaces.RSAPublicKey getRsaPublicKey​(java.security.cert.X509Certificate cert)
      Obtiene una clave pública de un certificado.
      private static java.security.spec.ECParameterSpec mapNonceGMWithECDH​(java.math.BigInteger nonceS, java.security.spec.ECPoint sharedSecretPointH, java.security.spec.ECParameterSpec params)  
      private static java.security.spec.ECPoint multiply​(java.math.BigInteger s, java.security.spec.ECPoint point, java.security.spec.ECParameterSpec params)  
      private static java.math.BigInteger os2i​(byte[] bytes)
      Convierte un Octet String de ASN.1 en un entero (según BSI TR 03111 Sección 3.1.2).
      private static java.math.BigInteger os2i​(byte[] bytes, int offset, int length)
      Convierte un Octet 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, 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.ECCurve toSpongyCastleECCurve​(java.security.spec.ECParameterSpec params)  
      private static org.bouncycastle.math.ec.ECPoint toSpongyCastleECPoint​(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 java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • LOGGER

        private static final java.util.logging.Logger LOGGER
        Logger por defecto.
    • Constructor Detail

      • BcCryptoHelper

        public BcCryptoHelper()
    • Method Detail

      • digest

        public byte[] digest​(CryptoHelper.DigestAlgorithm algorithm,
                             byte[] data)
                      throws java.io.IOException
        Description copied from class: CryptoHelper
        Realiza una huella digital de los datos proporcionados.
        Specified by:
        digest in class CryptoHelper
        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.IOException
        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:
        java.io.IOException - Si ocurre cualquier error durante el proceso.
      • desedeEncrypt

        public byte[] desedeEncrypt​(byte[] data,
                                    byte[] rawKey)
                             throws java.io.IOException
        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 class CryptoHelper
        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.IOException
        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 class CryptoHelper
        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.IOException
        Description copied from class: CryptoHelper
        Encripta datos mediante DES (modo ECB sin relleno).
        Specified by:
        desEncrypt in class CryptoHelper
        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.IOException
        Description copied from class: CryptoHelper
        Desencripta datos mediante DES (modo ECB sin relleno).
        Specified by:
        desDecrypt in class CryptoHelper
        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.IOException
        Description copied from class: CryptoHelper
        Desencripta datos mediante RSA.
        Specified by:
        rsaDecrypt in class CryptoHelper
        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.IOException
        Description copied from class: CryptoHelper
        Encripta datos mediante RSA.
        Specified by:
        rsaEncrypt in class CryptoHelper
        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: CryptoHelper
        Genera contenido aleatorio en un array de bytes.
        Specified by:
        generateRandomBytes in class CryptoHelper
        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.IOException
        org.bouncycastle.crypto.InvalidCipherTextException
      • aesDecrypt

        public byte[] aesDecrypt​(byte[] data,
                                 byte[] iv,
                                 byte[] key,
                                 CryptoHelper.BlockMode blockMode,
                                 CryptoHelper.Padding padding)
                          throws java.io.IOException
        Description copied from class: CryptoHelper
        Desencripta datos mediante AES.
        Specified by:
        aesDecrypt in class CryptoHelper
        Parameters:
        data - Datos a encriptar.
        iv - Vector de inicialización. Si se proporciona null 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:
        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.IOException
        Description copied from class: CryptoHelper
        Encripta datos mediante AES.
        Specified by:
        aesEncrypt in class CryptoHelper
        Parameters:
        data - Datos a encriptar.
        iv - Vector de inicialización. Si se proporciona null 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:
        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: CryptoHelper
        Genera un par de claves de tipo curva elíptica.
        Specified by:
        generateEcKeyPair in class CryptoHelper
        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: CryptoHelper
        Realiza un CMAC con AES.
        Specified by:
        doAesCmac in class CryptoHelper
        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: CryptoHelper
        Obtiene un punto en una curva elíptica.
        Specified by:
        getEcPoint in class CryptoHelper
        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 un Octet 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

        private static java.math.BigInteger os2i​(byte[] bytes,
                                                 int offset,
                                                 int length)
        Convierte un Octet 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 del Octet 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.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 class CryptoHelper
        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.IOException
        Description copied from class: CryptoHelper
        Obtiene el contenido firmado de una firma CMS/PKCS#7.
        Specified by:
        getCmsSignatureSignedContent in class CryptoHelper
        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.CertificateException
        Genera un certificado a partir de su codificación binaria.
        Specified by:
        generateCertificate in class CryptoHelper
        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.CertificateException
        Genera un certificado a partir de un flujo hacia su codificación binaria.
        Specified by:
        generateCertificate in class CryptoHelper
        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.
      • getRsaPublicKey

        public java.security.interfaces.RSAPublicKey getRsaPublicKey​(java.security.cert.X509Certificate cert)
        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 al del certificado es evitar problemas por la interpretaci&oaccute;n del signo del BigInteger en ciertos entornos (como J2Obc).
        Specified by:
        getRsaPublicKey in class CryptoHelper
        Parameters:
        cert - Certificado de origen.
        Returns:
        Clave pública RSA del certificado.