【发布时间】:2019-10-24 10:39:02
【问题描述】:
晚上好!
我正在尝试在 c# 中使用 Rijndael 算法和 Rijndael 类来实现加密器。我试图遵循(不做完全相同的代码)下面的链接,但问题是给出了一个要加密的字符串我没有得到任何结果。我也没有收到任何错误消息。
CryptDecrypt.cs
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace RijndaelAlgorithm {
public class CryptDecrypt {
private Byte[] iv;
private Byte[] key;
public CryptDecrypt(String key) {
iv = new Byte[] {21, 10, 21, 251, 132, 76, 121, 27, 210, 81, 215, 99, 14, 235, 11, 75};
this.key = Encoding.ASCII.GetBytes(key);
}
public String encryptMsg(String originalMsg) {
byte[] encryptedMsg;
Rijndael rijAlg = Rijndael.Create();
rijAlg.Key = formatKey();
rijAlg.IV = iv;
MemoryStream msEncrypt = new MemoryStream();
ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
StreamWriter swEncrypt = new StreamWriter(csEncrypt);
swEncrypt.Write(originalMsg);
encryptedMsg = msEncrypt.ToArray();
Console.WriteLine("encryptedMsg.Length: " + encryptedMsg.Length);
return Convert.ToBase64String(encryptedMsg, 0, encryptedMsg.Length);
}
private Byte[] formatKey() {
int len = key.Length;
String strKey = System.Text.Encoding.UTF8.GetString(key);
String fillKey = "";
String strFormatedKey = "";
Byte[] formatedKeyByte;
if (len < 16)
fillKey = new String('X',(16 - len));
strFormatedKey = String.Concat(strKey, fillKey);
formatedKeyByte = Encoding.ASCII.GetBytes(strFormatedKey);
return formatedKeyByte;
}
}
}
菜单.cs
using System;
namespace RijndaelAlgorithm {
public class Menu {
private CryptDecrypt r;
public Menu() {
r = new CryptDecrypt("123654");
}
public void showMenu() {
Console.WriteLine("the encrypted message is: " + r.encryptMsg("isjustatest"));
}
}
}
【问题讨论】:
-
您能否在单独的项目或 .net 上创建一个 minimal reproducible example,仅解决您问题的加密部分
-
我尽我所能。 RijndaelAlgorithm 类只有两个方法,可能问题出在 formatKey() 中。可能不会,但我不知道。 Menu 类是我定义要加密的密钥和消息的地方。
-
为什么要去掉 using() 结构?由于它们已经消失,您现在必须手动调用
swEncrypt.Flush();,然后在写入之后调用csEncrypt.FlushFinalBlock()。 -
因为我是 c# 的新手,而且这个合成器对我来说非常丑陋和不寻常。我添加了 swEncrypt.Flush();然后是 swEncrypt.Write(originalMsg); 之后的 csEncrypt.FlushFinalBlock()现在工作正常。显然。问题是我尝试在crypt-online.ru/en/crypts/aes 中加密相同的消息,但我得到了另一件事。我为密钥大小选择 256 位,为密钥选择“123654”,我得到了编码:U2FsdGVkX1+IVWR60YK3F6fN7F3a7SKPSpPDvF6ZXlA= 并使用我的代码得到 GlIhsK3UihG+nlmBZHgHYg== 为什么?
-
您的代码使用 128 位密钥,而不是 256。此外,使用
'X'填充是非常不寻常的,并且不太可能由该在线工具完成。使用基于密码的密钥派生函数(例如 Argon2 或 PBKDF2)将低熵密钥转换为适当的加密密钥。并且不要为任何给定的密钥重复使用 IV。
标签: c# encryption aes rijndael