I worked on a project where we should safely store the pdf file in the android sd card. We want this to be encrypted in .net, because it must be passed through the API. I implemented in .NET but could not decrypt in android.
File Encryption Code
public static void EncryptFile(string inputFile, string outputFile) { try { string password = @"myKey123"; // Your Key Here UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(password); string cryptFile = outputFile; FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create); RijndaelManaged RMCrypto = new RijndaelManaged(); RMCrypto.Mode = CipherMode.CBC; //remember this parameter RMCrypto.Padding = PaddingMode.PKCS7; //remember this parameter RMCrypto.KeySize = 0x80; RMCrypto.BlockSize = 0x80; CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write); FileStream fsIn = new FileStream(inputFile, FileMode.Open); int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } fsIn.Close(); cs.Close(); fsCrypt.Close(); } catch { Console.WriteLine("Encryption failed!", "Error"); } }
Code to decrypt a file
public static void DecryptFile(string inputFile, string outputFile) { { string password = @"myKey123"; // Your Key Here UnicodeEncoding UE = new UnicodeEncoding(); byte[] key = UE.GetBytes(password); FileStream fsCrypt = new FileStream(inputFile, FileMode.Open); RijndaelManaged RMCrypto = new RijndaelManaged(); RMCrypto.Mode = CipherMode.CBC; //remember this parameter RMCrypto.Padding = PaddingMode.PKCS7; //remember this parameter RMCrypto.KeySize = 0x80; RMCrypto.BlockSize = 0x80; CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read); FileStream fsOut = new FileStream(outputFile, FileMode.Create); int data; while ((data = cs.ReadByte()) != -1) fsOut.WriteByte((byte)data); fsOut.Close(); cs.Close(); fsCrypt.Close(); } }
I tried on Android using below code
public static byte[] decodeFile(String key, byte[] fileData) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); //this parameters should not be changed byte[] keyBytes = new byte[16]; byte[] b = key.getBytes("UTF-16"); System.out.println("RAM"+b); int len = b.length; if (len > keyBytes.length) len = keyBytes.length; System.arraycopy(b, 0, keyBytes, 0, len); SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES"); IvParameterSpec ivSpec = new IvParameterSpec(keyBytes); cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); byte[] decrypted = cipher.doFinal(fileData); return decrypted; }
When I run this code, I get an error:
error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt