[英]Encryption and Descyption issue in Flutter and C#
我使用以下鏈接在 Flutter 中使用加密: https : //pub.dev/packages/encrypt
代碼是
final plainText = 'some plain text here';
final key = encrypt.Key.fromUtf8('16 characters key');
final iv = IV.fromLength(16);
final encrypter = Encrypter(AES(key,mode: AESMode.cbc,padding: 'PKCS7'));
final encrypted = encrypter.encrypt(plainText, iv: iv);
final decrypted = encrypter.decrypt(encrypted, iv: iv);
print(decrypted);
print(encrypted.base64);
C# 代碼(用於解密)
public static String TestDecrypt(String encryptedText)
{
var encryptedBytes = Convert.FromBase64String(encryptedText);
return Encoding.UTF8.GetString(Decrypt(encryptedBytes, GetRijndaelManaged("16 characters key")));
}
public static RijndaelManaged GetRijndaelManaged(String secretKey)
{
var keyBytes = new byte[16];
var secretKeyBytes = Encoding.UTF8.GetBytes(secretKey);
Array.Copy(secretKeyBytes, keyBytes, Math.Min(keyBytes.Length, secretKeyBytes.Length));
return new RijndaelManaged
{
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7,
KeySize = 128,
BlockSize = 128,
Key = keyBytes,
IV = keyBytes
};
}
我在 flutter dart 代碼中加密了一些明文,但是在使用 c# 代碼解密加密文本后我沒有得到正確的純文本。
我收到一條消息
填充無效且無法移除
在顫動中使用線下
final iv = IV.fromUtf8('16 個字符鍵');
這對我有用: 鍵:
String keySTR = "16 characters"; //16 byte
String ivSTR = "16 characters"; //16 byte
撲
final plainText = 'Works!';
final key = encrypt.Key.fromUtf8(keySTR);
final iv = encrypt.IV.fromUtf8(ivSTR);
final encrypter = encrypt.Encrypter(encrypt.AES(key,mode: encrypt.AESMode.cbc,padding: 'PKCS7'));
final encrypted = encrypter.encrypt(plainText, iv: iv);
final decrypted = encrypter.decrypt(encrypted, iv: iv);
print('decrypted:'+decrypted);
print('encrypted.base64:'+encrypted.base64);
C#
using (System.Security.Cryptography.RijndaelManaged rjm =
new System.Security.Cryptography.RijndaelManaged
{
KeySize = 128,
BlockSize = 128,
Key = ASCIIEncoding.ASCII.GetBytes(keySTR),
IV = ASCIIEncoding.ASCII.GetBytes(ivSTR)
}
)
{
Byte[] input = Encoding.UTF8.GetBytes(stringToEncrypt);
Byte[] output = rjm.CreateEncryptor().TransformFinalBlock(input, 0, input.Length);
return Convert.ToBase64String(output);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.