我想在 c# 中加密文件并在我的 android 应用程序中通过 java 代码解密 c# 加密文件,我知道最好的算法是 AES256,我在 android 中的代码工作正常(加密和解密)但我可以'通过我的 android 应用程序解密 C# 结果文件,我使用以下代码(非常感谢):
加密和解密函数(android):
加密:
static void Encrypt() throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { try { FileInputStream fis = new FileInputStream(Environment .getExternalStorageDirectory().getAbsolutePath() + "/logo.png"); FileOutputStream fos = new FileOutputStream(Environment .getExternalStorageDirectory().getAbsolutePath() + "/Encrypted"); SecretKeySpec aeskeySpec = new SecretKeySpec( "12345678901234567890123456789012".getBytes(), "AES"); tv.setText(aeskeySpec.getEncoded().toString()); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, aeskeySpec); CipherOutputStream cos = new CipherOutputStream(fos, cipher); int b; byte[] d = new byte[8]; while ((b = fis.read(d)) != -1) { cos.write(d, 0, b); } cos.flush(); cos.close(); fis.close(); }// try catch (Exception e) { // TODO: handle exception tv.setText("Error :" + e.getMessage()); } }// encrypt
static void Decrypt() throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { File file = new File(Environment.getExternalStorageDirectory() .getAbsolutePath() + "/Encrypted"); FileInputStream fis = new FileInputStream(file); long length = file.length(); if (length > Integer.MAX_VALUE) { // File is too large } byte[] bytes = new byte[(int) length]; int offset = 0; int numRead = 0; bytes = IOUtils.toByteArray(fis); byte[] N = new byte[(int) length - offset]; int g, s = 0; for (g = offset; g < length; g++) { N[s++] = bytes[g]; } FileOutputStream fos = new FileOutputStream(Environment .getExternalStorageDirectory().getAbsolutePath() + "/Decrypted"); SecretKeySpec sks = new SecretKeySpec( "12345678901234567890123456789012".getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, sks); byte[] b = cipher.update(N); int j = 0; while (j < b.length) { fos.write(b[j]); j++; } fos.flush(); fos.close(); }
我在 c# 中使用此代码进行加密:
public void Encrypt(string FIStr, string FOStr, string PassKey) { FileStream fsInput = new FileStream(FIStr, FileMode.Open, FileAccess.Read); FileStream fsEncrypted = new FileStream(FOStr, FileMode.Create, FileAccess.Write); AesCryptoServiceProvider AES = new AesCryptoServiceProvider(); System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); byte[] bytes=encoding.GetBytes(PassKey); AES.Key = bytes; ICryptoTransform aesencrypt = AES.CreateEncryptor(); CryptoStream cryptostream = new CryptoStream(fsEncrypted, aesencrypt, CryptoStreamMode.Write); byte[] bytearrayinput = new byte[fsInput.Length]; fsInput.Read(bytearrayinput, 0, bytearrayinput.Length); cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length); cryptostream.Close(); fsInput.Close(); fsEncrypted.Close();}
此代码加密我的文件,但我无法通过我的 android 应用程序解密此文件:(,请帮助我,谢谢大家。