-3

I have c sharp code snippet for encryption which uses .Key file for key and my requirement is to decrypt the encrypted text using same key in android, having problem

public static byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes) {
        byte[] encryptedBytes = null;

        // Set your salt here, change it to meet your flavor:
        // The salt bytes must be at least 8 bytes.
        byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

        using (MemoryStream ms = new MemoryStream())
        {
            using (RijndaelManaged AES = new RijndaelManaged())
            {
                AES.KeySize = 256;
                AES.BlockSize = 128;

                var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
                AES.Key = key.GetBytes(AES.KeySize / 8);
                AES.IV = key.GetBytes(AES.BlockSize / 8);

                AES.Mode = CipherMode.CBC;

                using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                    cs.Close();
                }
                encryptedBytes = ms.ToArray();
            }
        }

        return encryptedBytes;
    }
Nikhil Vartak
  • 5,002
  • 3
  • 26
  • 32

1 Answers1

1

If you want to decrypt some data with AES you can use this method:

private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
  SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
  Cipher cipher = Cipher.getInstance("AES");
  cipher.init(Cipher.DECRYPT_MODE, skeySpec);
  byte[] decrypted = cipher.doFinal(encrypted);
  return decrypted;
}

for complete code look at : android encryption/decryption with AES

Community
  • 1
  • 1
mehd azizi
  • 594
  • 1
  • 5
  • 16
  • 2
    Please note that Java & C# have different default cipher block mode (ECB vs CBC), you need a little bit tweaks to set both en/decryptor on CBC (see http://stackoverflow.com/a/6671819/900284 for issue related on ECB). – Tetsuya Yamamoto Jul 19 '16 at 05:59
  • no it will not work, i have tried almost all kinds of code with but didn't work – Satish Ghatale Jul 19 '16 at 06:00