gpt4 book ai didi

c# - .NET 加密问题

转载 作者:太空宇宙 更新时间:2023-11-03 16:49:39 24 4
gpt4 key购买 nike

我引用了这篇文章http://www.codeproject.com/KB/security/DotNetCrypto.aspx我正在尝试写一个加密的字符串而不是纯文本。下面是我正在使用的代码:

TextWriter tw = new StreamWriter("c:\\temp\\test.txt");
string plainString = "String to be encrypted";
PasswordDeriveBytes pdb = new PasswordDeriveBytes("Test",new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
Rijndael alg = Rijndael.Create();
alg.Key = pdb.GetBytes(32);
alg.IV = pdb.GetBytes(16);
tw.WriteLine(alg.IV.ToString());
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms,alg.CreateEncryptor(), CryptoStreamMode.Write);
byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(plainString);
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
tw.WriteLine(ms.ToString());
ms.Close();
tw.Flush();

但是,当我打开文件时,我得到的是 System.IO.MemoryStream 而不是一些加密字符。我错过了什么?

最佳答案

我认为 .net 非常支持使用 MD5 算法加密字符串。如果要使用 MD5,请参见以下代码。

private void encrypt(ref string password)
{
Int32 counter;
Char[] passwordArr;
String encryptedPassword;
Byte[] hashedPassword;
MD5CryptoServiceProvider obj = new MD5CryptoServiceProvider();

passwordArr = password.ToCharArray();
Byte[] passwordBytes = new byte[passwordArr.Length - 1];
for (counter = 0; counter < passwordBytes.Length; counter++)
{
passwordBytes[counter] = Convert.ToByte(passwordArr[counter]);
}
hashedPassword = obj.ComputeHash(passwordBytes);
encryptedPassword = BitConverter.ToString(hashedPassword);
password = encryptedPassword;
obj = null;
}

关于c# - .NET 加密问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4506141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com