Search code examples
javavb.netencryptionrijndael

How to get the right KEY and IV in Rinjdael encryption equivalent in JAVA


I have a code in VB.Net with a Rijndael encryption algorithm:

Public Function DesencriptarCertificado(ByVal pCertificado As String, ByVal pClave As String) As Byte()
    Dim byteCertificadoDescencriptado As Byte() = Nothing
    Dim Algoritmo As SymmetricAlgorithm = New RijndaelManaged()
    Dim CertClaveDesencriptada As String = ""

    CertClaveDesencriptada = DesencriptarString(pClave, "")
    Transform(CertClaveDesencriptada, Algoritmo)


    Dim ICryptoTransform As ICryptoTransform = Algoritmo.CreateDecryptor()
        byteCertificadoDescencriptado = HexToByte(pCertificado)
        byteCertificadoDescencriptado = ICryptoTransform.TransformFinalBlock(byteCertificadoDescencriptado, 0, byteCertificadoDescencriptado.Length)
    Return byteCertificadoDescencriptado
End Function

Public Sub Transform(ByVal pClave As String, ByRef pAlgoritmo As SymmetricAlgorithm)

    Dim bytes As Byte() = New Byte(7) {}
    Dim BytesClave As Byte() = Encoding.ASCII.GetBytes(pClave)
    Dim length As Integer = Math.Min(BytesClave.Length, bytes.Length)

    For i As Integer = 0 To length - 1
        bytes(i) = BytesClave(i)
    Next

    Dim key As New Rfc2898DeriveBytes(pClave, bytes)
    //ASIGNO BYTES A KEY E IV
    pAlgoritmo.Key = key.GetBytes(pAlgoritmo.KeySize \ 8)
    pAlgoritmo.IV = key.GetBytes(pAlgoritmo.BlockSize \ 8)
End Sub

The problem is the IV and KEY in JAVA do not get the same bytes, so signature is not the same, it works perfectly if I initialize the KEY and IV manually with the same bytes that are generated in VB.Net, but it is not feasible of course because it would only work for a specific certificate, and the idea is that it works generically, after a search I tried some variants but without success, I could not get the KEY And IV, I would appreciate any help with the subject.

Java Code

public byte[] DesencriptarCertificado(String pCertificado, String pClave) throws NoSuchAlgorithmException, InvalidKeySpecException, UnsupportedEncodingException, NoSuchPaddingException, InvalidAlgorithmParameterException, NoSuchProviderException, ShortBufferException, IOException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    try {
        String CertClaveDesencriptada = DesencriptarString(pClave, "");

        ////////////Transform//////////////
        byte[] bytes = new byte[8];
        byte[] BytesClave = CertClaveDesencriptada.getBytes();
        int length = Math.min(BytesClave.length, bytes.length);

        for (int i = 0; i < length; i++) {
            bytes[i] = BytesClave[i];
        }

        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec pbeKeySpec = new PBEKeySpec(CertClaveDesencriptada.toCharArray(), bytes, 12, 1000);
        Key secretKey = factory.generateSecret(pbeKeySpec);
        byte[] encoded = secretKey.getEncoded();

        byte[] KEY = new byte[32];
        byte[] IV = new byte[16];

        //ASIGNO BYTES A KEY E IV
        System.arraycopy(encoded, 0, KEY, 0, 32); 
        System.arraycopy(encoded, 32, IV, 0, 16);

        SecretKeySpec secret = new SecretKeySpec(key, "Rijndael");
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(IV);
        _cipherDecrypEncrypt = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
        _cipherDecrypEncrypt.init(Cipher.DECRYPT_MODE, secret, ivSpec);


        ///////////////DESENCRIPTAR CERTIFICADO/////////////////////
        byte[] beforeEncrypt = HexToByte(pCertificado);
        byte[] byteCertificadoDescencriptado = _cipherDecrypEncrypt.doFinal(beforeEncrypt);

        return byteCertificadoDescencriptado;

    } catch (InvalidKeyException e) {
        throw new TAFACE2ApiEntidad.TAException(e.getMessage());
    } catch (IllegalBlockSizeException e) {
        System.out.println(e);
        throw new TAFACE2ApiEntidad.TAException(e.getMessage());
    } catch (BadPaddingException e) {
        System.out.println(e);
        throw new TAFACE2ApiEntidad.TAException(e.getMessage());
    }

}

Solution

    1. If your salt is supposed to be 7 bytes long, as seen in your VB.NET code Dim bytes As Byte() = New Byte(7) {}, you should declare it as such:

      byte[] bytes = new byte[7];
      
    2. The constructor for PBEKeySpec that you're trying to use is PBEKeySpec(char[] password, byte[] salt, int iterationCount, int keyLength) where you use request 12 iterations for an output length of 1000.

      You need to use

      new PBEKeySpec(CertClaveDesencriptada.toCharArray(), bytes, 1000, 384);
      

      where 384 means 32 + 16 bytes in bits.