Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting c# decryption method to android

I am trying to decrypt in JAVA a string that was encrypted in C#. In c# the decryption is succesffull with this method:

  AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider();
        aesProvider.BlockSize = 128;
        aesProvider.KeySize = 128;
        aesProvider.Key = strKey;
        aesProvider.IV = strIV;
        aesProvider.Padding = PaddingMode.PKCS7;
        aesProvider.Mode = CipherMode.CBC;

        ICryptoTransform cryptoTransform = aesProvider.CreateDecryptor(aesProvider.Key, aesProvider.IV);
        byte[] DecryptedBytes = cryptoTransform.TransformFinalBlock(EncryptedBytes, 0, EncryptedBytes.Length);
        return System.Text.Encoding.UTF8.GetString(DecryptedBytes);

What I am trying to do is convert this method to JAVA (Android), this is what I have tried, but get an error message ("Pad block corrupted"):

 try
       {
           byte[] IV = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6 };
           byte[] KEY = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6 };

           SecretKeySpec key = new SecretKeySpec(KEY, "AES/CBC/PKCS7Padding");
           Cipher cipher = Cipher.getInstance ("AES/CBC/PKCS7Padding");

           cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV));

           byte[] bytesData = Utilities.Base64Coder.decode(data);

           Log.i("bytesData", String.valueOf(bytesData.length));

           String strResult = new String(cipher.doFinal(bytesData));


            Log.i("decrypted string", strResult);
            return strResult;
        }
        catch (Exception e) {

            Log.i("decrypted FAILED", e.getMessage());
            return null;
        }

10X :)

like image 573
Udi Idan Avatar asked Apr 06 '26 17:04

Udi Idan


1 Answers

For whom ever search and get to this question - this code works fine, the problem was with the key that was different between c# and Java.

GregS - 10X for raising my attention to check it again.

like image 143
Udi Idan Avatar answered Apr 08 '26 06:04

Udi Idan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!