我有存储在数据库中的值,这些值已使用.NET AesCryptoServiceProvider加密。我需要在Android中解密这些值。我找到了CryptLib类,并且能够使用该类进行加密/解密,但是得到的结果与使用AesCryptoServiceProvider获得的结果不同。我使用的是相同的Key和IV值,并且没有加盐,所以我不明白还要寻找什么。如果有人能指出我正确的方向,我将不胜感激。
为了进行测试,我只是想再次对相同的值进行加密,看看是否得到相同的结果。在CryptLib函数中
public String encryptPlainText(String plainText, String key, String iv) throws Exception {
byte[] bytes = encryptDecrypt(plainText, CryptLib.SHA256(key, 32), EncryptMode.ENCRYPT, iv);
return Base64.encodeToString(bytes, Base64.DEFAULT);
}
我尝试用正键替换CryptLib.SHA256(key,32)。这只是另一个结果。两种方法都不匹配.NET的结果。
这是我如何调用CryptLib类:
CryptLib cryptLib = new CryptLib();
String encryptedString = cryptLib.encryptPlainText(plainText, key, iv);
这是CryptLib类的一部分:
private byte[] encryptDecrypt(String inputText, String encryptionKey,
EncryptMode mode, String initVector) throws UnsupportedEncodingException,
InvalidKeyException, InvalidAlgorithmParameterException,
IllegalBlockSizeException, BadPaddingException {
int len = encryptionKey.getBytes("UTF-8").length; // length of the key provided
if (encryptionKey.getBytes("UTF-8").length > _key.length)
len = _key.length;
int ivlength = initVector.getBytes("UTF-8").length;
if(initVector.getBytes("UTF-8").length > _iv.length)
ivlength = _iv.length;
System.arraycopy(encryptionKey.getBytes("UTF-8"), 0, _key, 0, len);
System.arraycopy(initVector.getBytes("UTF-8"), 0, _iv, 0, ivlength);
SecretKeySpec keySpec = new SecretKeySpec(_key, "AES"); // Create a new SecretKeySpec for the specified key data and algorithm name.
IvParameterSpec ivSpec = new IvParameterSpec(_iv); // Create a new IvParameterSpec instance with the bytes from the specified buffer iv used as initialization vector.
// encryption
if (mode.equals(EncryptMode.ENCRYPT)) {
// Potentially insecure random numbers on Android 4.3 and older. Read for more info.
// https://android-developers.blogspot.com/2013/08/some-securerandom-thoughts.html
_cx.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);// Initialize this cipher instance
return _cx.doFinal(inputText.getBytes("UTF-8")); // Finish multi-part transformation (encryption)
} else {
_cx.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);// Initialize this cipher instance
byte[] decodedValue = Base64.decode(inputText.getBytes(), Base64.DEFAULT);
return _cx.doFinal(decodedValue); // Finish multi-part transformation (decryption)
}
}
.NET:
public static string Encrypt(string plainText, byte [] myaesiv) //, byte[] Key, byte[] IV)
{
byte[] encrypted;
using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
{
aes.Padding = PaddingMode.Zeros;
aes.KeySize = 256;
byte [] aesbyte = Convert.FromBase64String(aeskey);
ICryptoTransform encryptor = aes.CreateEncryptor(aesbyte, myaesiv);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
sw.Write(plainText);
encrypted = ms.ToArray();
}
}
}
String s = Convert.ToBase64String(encrypted, 0, encrypted.Length);
return s;
}