hte*_*lez 2 c# encryption cryptography aes
我的目标是得到一个非常简单的分组密码,即 AES 的核心。它必须接受一个键和一个块并返回一个块。解密器应该获取密钥和块并返回原始块。
我一直在使用以下密钥(十六进制)进行测试
AA000000000000000000000000000000
Run Code Online (Sandbox Code Playgroud)
以及以下纯文本
AA000000000000000000000000000000
Run Code Online (Sandbox Code Playgroud)
(再次以十六进制表示,是的,与密钥相同)
结果应该是
814827A94525FF24B90F20BEC065866D
Run Code Online (Sandbox Code Playgroud)
确实如此。(您可以在此处验证这应该是http://www.cryptogrium.com/aes-encryption-online-ecb.html上的结果,并将其作为输入并选择 AES-128)。
但解密器总是返回
00000000000000000000000000000000
Run Code Online (Sandbox Code Playgroud)
(只有零)。
我在以下实现中做错了什么?此实现仅用于教育目的。这就是为什么我使用 ECB 模式以及为什么我期望始终使用相同的加密。
namespace CryptographyCSharp
{
using System;
using System.Security.Cryptography;
public class MyAes
{
public static string EncryptStringToBytes_Aes(string msg_hex, string key_hex)
{
if (msg_hex == null)
throw new ArgumentNullException("msg_hex");
if (key_hex == null)
throw new ArgumentNullException("key_hex");
byte[] output = new byte[16];
msg_hex = msg_hex.PadRight(32, '0');
key_hex = key_hex.PadRight(32, '0');
using (var aes = Aes.Create("AES"))
{
aes.BlockSize = 128;
aes.KeySize = 128;
aes.Mode = CipherMode.ECB;
if (!aes.ValidKeySize(128))
{
throw new Exception();
}
ICryptoTransform encryptor = aes.CreateEncryptor(key_hex.hex2bytes(), null);
encryptor.TransformBlock(msg_hex.hex2bytes(), 0, 16, output, 0);
encryptor.Dispose();
}
return output.tohex();
}
public static string DecryptStringFromBytes_Aes(string hex_ct, string key_hex)
{
if (hex_ct == null)
throw new ArgumentNullException("cipherText");
if (key_hex == null)
throw new ArgumentNullException("Key");
hex_ct = hex_ct.PadRight(32, '0');
key_hex = key_hex.PadRight(32, '0');
string plaintext = null;
using (Aes aes = Aes.Create("AES"))
{
aes.BlockSize = 128;
aes.KeySize = 128;
aes.Mode = CipherMode.ECB;
if (!aes.ValidKeySize(128))
{
throw new Exception();
}
ICryptoTransform decryptor = aes.CreateDecryptor(key_hex.hex2bytes(), null);
var output = new byte[16];
decryptor.TransformBlock(hex_ct.hex2bytes(), 0, 16, output, 0);
plaintext = output.tohex();
}
return plaintext;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我使用了一些将十六进制转换为字节和反之亦然的扩展方法(即 string.hex2bytes 和 bytes[].tohex)。如果你需要它们,我可以提供它们。
| 归档时间: |
|
| 查看次数: |
1076 次 |
| 最近记录: |