Class BcCryptoHelper

java.lang.Object
es.gob.jmulticard.CryptoHelper
es.gob.jmulticard.crypto.BcCryptoHelper

public final class BcCryptoHelper extends CryptoHelper
Funcionalidades criptográficas de utilidad implementadas mediante BouncyCastle.
  • Field Details

  • Constructor Details

    • BcCryptoHelper

      public BcCryptoHelper()
  • Method Details

    • digest

      public byte[] digest(DigestAlgorithm algorithm, byte[] data) throws 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:
      IOException - Si ocurre algún problema generando la huella digital.
    • doDesede

      private static byte[] doDesede(byte[] data, byte[] key, boolean forEncryption) throws 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:
      IOException - Si ocurre cualquier error durante el proceso.
    • desedeEncrypt

      public byte[] desedeEncrypt(byte[] data, byte[] rawKey) throws 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:
      IOException - Si ocurre algún problema durante el encriptado.
    • desedeDecrypt

      public byte[] desedeDecrypt(byte[] data, byte[] rawKey) throws 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:
      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 IOException
      Throws:
      IOException
    • desEncrypt

      public byte[] desEncrypt(byte[] data, byte[] key) throws 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:
      IOException - Si ocurre algún problema durante el encriptado.
    • desDecrypt

      public byte[] desDecrypt(byte[] data, byte[] key) throws 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:
      IOException - Si ocurre algún problema durante el desencriptado.
    • doRsa

      private static byte[] doRsa(byte[] data, RSAKey key, boolean forEncryption) throws IOException
      Throws:
      IOException
    • rsaDecrypt

      public byte[] rsaDecrypt(byte[] cipheredData, RSAKey key) throws 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:
      IOException - Si ocurre algún problema durante el desencriptado.
    • rsaEncrypt

      public byte[] rsaEncrypt(byte[] data, RSAKey key) throws 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:
      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 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 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:
      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 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:
      IOException - Si ocurre algún problema durante el encriptado.
    • generateEcKeyPair

      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:
      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 class CryptoHelper
      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 class CryptoHelper
      Parameters:
      nonceS - Aleatorio de un solo uso.
      sharedSecretH - Secreto compartido.
      curveName - Nombre de la curva.
      Returns:
      Punto encapsulado.
    • os2i

      private static 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 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 BigInteger computeAffineY(BigInteger affineX, ECParameterSpec params)
    • toBouncyCastleECCurve

      private static org.bouncycastle.math.ec.ECCurve toBouncyCastleECCurve(ECParameterSpec params)
    • getPrime

      private static BigInteger getPrime(ECParameterSpec params)
    • mapNonceGmWithEcdh

      private static ECParameterSpec mapNonceGmWithEcdh(BigInteger nonceS, ECPoint sharedSecretPointH, ECParameterSpec params)
    • multiply

      private static ECPoint multiply(BigInteger s, ECPoint point, ECParameterSpec params)
    • fromBouncyCastleECPoint

      private static ECPoint fromBouncyCastleECPoint(org.bouncycastle.math.ec.ECPoint point)
    • add

      private static ECPoint add(ECPoint x, ECPoint y, ECParameterSpec params)
    • toBouncyCastleECPoint

      private static org.bouncycastle.math.ec.ECPoint toBouncyCastleECPoint(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 class CryptoHelper
      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

      public byte[] getCmsSignatureSignedContent(byte[] signedDataBytes) throws 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:
      IOException - Si los datos proporcionados no son una firma CMS/PKCS#7 bien formada.
    • getPaceChannelHelper

      public CryptoHelper.PaceChannelHelper getPaceChannelHelper(CardAccess cardAccess, PaceChat paceChat)
      Description copied from class: CryptoHelper
      Obtiene las utilidades para el establecimiento de un canal PACE (Password Authenticated Connection Establishment).
      Specified by:
      getPaceChannelHelper in class CryptoHelper
      Parameters:
      cardAccess - CardAccess de la tarjeta.
      paceChat - PACE CHAT a usar en el establecimiento del canal PACE.
      Returns:
      Utilidades para el establecimiento de un canal PACE
    • getRsaPublicKey

      public RSAPublicKey getRsaPublicKey(X509Certificate cert)
      Description copied from class: CryptoHelper
      Obtiene una clave pública de un certificado. Permite evitar invocar directamente al getPublicKey() del certificado y así evitar problemas por la interpretació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.