【发布时间】:2023-03-07 17:15:02
【问题描述】:
我有两种方法,一种加密,另一种解密:
加密方法
public static string Encrypt(string EncryptionMessage)
{
string Encrypted = string.Empty;
string EncryptionKey = "0123456789";
byte[] clearBytes = Encoding.Unicode.GetBytes(EncryptionMessage);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
Encrypted = Convert.ToBase64String(ms.ToArray());
}
}
return Encrypted;
}
解密方法
public static string Decrypt(string cipherText)
{
string Decrypted = string.Empty;
string EncryptionKey = "0123456789";
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
Decrypted = Encoding.Unicode.GetString(ms.ToArray());
}
}
return Decrypted;
}
加密的密钥总是返回以下字符:\ 和 /。
我想避免加密密钥返回字符\ 和/。
有什么帮助吗?
PS:语言是 C#,我已经标记了它,我看到的是 c#,但其他人看到的是另一种语言。我标记了 C# 和加密
【问题讨论】:
-
这是什么语言?肯定不是C。可能是 C#?
-
这显示在我的搜索中
C,但更可能是C#或C++请用正确的语言标记它,这样C#的人会来这里帮助你. -
有趣:我认为它是 Java...我同意它不是 C,但它也不是 C++:
using子句对于 C++ 是错误的。 -
好吧,我们
C的开发者连语言都认不出来,我们怎么能帮上忙…… -
@Djama:请修复语言标签。此外,您使用 密钥加密;您不会这样加密密钥。您是否担心从密码短语生成的密钥包含禁止字符,还是加密文本(密文)包含禁止字符?如果您担心加密文本包含这些字符,那么您必须对输出进行编码以避免它们。您需要考虑是否可以处理加密文本中的空字节、换行符、换页符等。最好将输出视为二进制汤,不要担心任何特殊字符。
标签: c# encryption