我在C#中有一个应用程序,它使用这种方法使用AES算法加密我的文件:
// strKey = "sample-16chr-key"
private static void encryptFile(string inputFile, string outputFile, string strKey)
{
try
{
using (RijndaelManaged aes = new RijndaelManaged())
{
byte[] key = Encoding.UTF8.GetBytes(strKey);
byte[] IV = Encoding.UTF8.GetBytes(strKey);
using (FileStream fsCrypt = new FileStream(outputFile, FileMode.Create))
{
using (ICryptoTransform encryptor = aes.CreateEncryptor(key, IV))
{
using (CryptoStream cs = new CryptoStream(fsCrypt, encryptor, CryptoStreamMode.Write))
{
using (FileStream fsIn = new FileStream(inputFile, FileMode.Open))
{
int data;
while ((data = fsIn.ReadByte()) != -1)
{
cs.WriteByte((byte)data);
}
}
}
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
该文件已加密,没有问题。
然后我想用我的 Android (2.2) 应用程序解密加密的文件。所以我这样做:
// myDoc is my Document object;
byte[] docBytes = serialize(myDoc);
byte[] key = ("sample-16chr-key").getBytes("UTF-8");
IvParameterSpec iv = new IvParameterSpec(key);
Cipher c = Cipher.getInstance("AES");
SecretKeySpec k = new SecretKeySpec(key, "AES");
c.init(Cipher.DECRYPT_MODE, k, iv);
// IllegalBlockSizeException Occurred
byte[] decryptedDocBytes = c.doFinal(docBytes);
Document decryptedDoc = (Document)deserialize(decryptedDocBytes);
还有我的序列化/反序列化方法:
private static byte[] serialize(Document obj) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(obj);
return out.toByteArray();
}
private static Object deserialize(byte[] data) throws IOException, ClassNotFoundException {
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
return is.readObject();
}
这里有什么问题?两种编码都是 UTF-8 并且密钥字节是相同的。
我错过了什么吗?
如果这不是我的应用程序的解决方案,我该怎么办?