【发布时间】:2019-10-30 06:29:33
【问题描述】:
Bouncy Castle CRT Csharp, Decrypt 获取纯文本失败
测试失败
static void Main(string[] args) {
string toEncrypt = "This is a test string";
byte[] key = Encoding.ASCII.GetBytes("0123456789abcdef");
byte[] iv = { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff };
Console.Write("\n Plain: " + toEncrypt);
// create AES cipher
IBufferedCipher cipher = CipherUtilities.GetCipher("AES/CTR/NoPadding");
cipher.Init(true, new ParametersWithIV(ParameterUtilities.CreateKeyParameter("AES", key), iv));
// encrypted
byte[] input = Encoding.ASCII.GetBytes(toEncrypt);
byte[] encryptedBytes = cipher.DoFinal(input);
string base64EncryptedOutputString = Convert.ToBase64String(encryptedBytes);
Console.Write("\n Base64Encrypted:" + base64EncryptedOutputString);
// decrypted
byte[] toDecrypt = Encoding.ASCII.GetBytes(base64EncryptedOutputString);
cipher.Init(false, new ParametersWithIV(ParameterUtilities.CreateKeyParameter("AES", key), iv));
byte[] plainBytes = cipher.DoFinal(toDecrypt);
Console.WriteLine("\n Decrypted:" + Encoding.ASCII.GetString(plainBytes));
}
Plain:这是一个测试字符串
Base64加密:71WVSPK31A+QrCUyqppI56fQixMV
解密:??m?????z??=????4G???e?w?
--->解密与纯文本不一样:)
【问题讨论】:
-
你不应该使用 ASCII,因为它只支持 128 个基本的拉丁字母、数字和符号。改用 UTF8 来支持所有 100,000+ Unicode 字符。
标签: c# encryption aes bouncycastle