У меня есть значения, хранящиеся в базе данных, которые были зашифрованы с помощью .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 (ключ, 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;
}