我使用此代码(在此处找到c Sharp Helper aes 加密)来加密字符串以及我想要保存到文件中的加密字符串。
#region "Encrypt Strings and Byte[]"
// Note that extension methods must be defined in a non-generic static class.
// Encrypt or decrypt the data in in_bytes[] and return the result.
public static byte[] CryptBytes(string password, byte[] in_bytes, bool encryptAES)
{
// Make an AES service provider.
AesCryptoServiceProvider aes_provider = new AesCryptoServiceProvider();
// Find a valid key size for this provider.
int key_size_bits = 0;
for (int i = 4096; i > 1; i--)
{
if (aes_provider.ValidKeySize(i))
{
key_size_bits = i;
break;
}
}
Debug.Assert(key_size_bits > 0);
Console.WriteLine("Key size: " + key_size_bits);
// Get the block size for this provider.
int block_size_bits = aes_provider.BlockSize;
// Generate the key and initialization vector.
byte[] key = null;
byte[] iv = null;
byte[] salt = { 0x0, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0xF1, 0xF0, 0xEE, 0x21, 0x22, 0x45 };
MakeKeyAndIV(password, salt, key_size_bits, block_size_bits, out key, out iv);
// Make the encryptor or decryptor.
ICryptoTransform crypto_transform;
if (encryptAES)
{
crypto_transform = aes_provider.CreateEncryptor(key, iv);
}
else
{
crypto_transform = aes_provider.CreateDecryptor(key, iv);
}
// Create the output stream.
using (MemoryStream out_stream = new MemoryStream())
{
// Attach a crypto stream to the output stream.
using (CryptoStream crypto_stream = new CryptoStream(out_stream,
crypto_transform, CryptoStreamMode.Write))
{
// Write the bytes into the CryptoStream.
crypto_stream.Write(in_bytes, 0, in_bytes.Length);
try
{
crypto_stream.FlushFinalBlock();
}
catch (CryptographicException)
{
// Ignore this exception. The password is bad.
}
catch
{
// Re-throw this exception.
throw;
}
// return the result.
return out_stream.ToArray();
}
}
}
// String extensions to encrypt and decrypt strings.
public static byte[] EncryptAES(this string the_string, string password)
{
System.Text.ASCIIEncoding ascii_encoder = new System.Text.ASCIIEncoding();
byte[] plain_bytes = ascii_encoder.GetBytes(the_string);
return CryptBytes(password, plain_bytes, true);
}
public static string DecryptAES(this byte[] the_bytes, string password)
{
byte[] decrypted_bytes = CryptBytes(password, the_bytes, false);
System.Text.ASCIIEncoding ascii_encoder = new System.Text.ASCIIEncoding();
return ascii_encoder.GetString(decrypted_bytes);
}
public static string CryptString(string password, string in_string, bool encrypt)
{
// Make a stream holding the input string.
byte[] in_bytes = Encoding.ASCII.GetBytes(in_string);
using (MemoryStream in_stream = new MemoryStream(in_bytes))
{
// Make an output stream.
using (MemoryStream out_stream = new MemoryStream())
{
// Encrypt.
CryptStream(password, in_stream, out_stream, true);
// Return the result.
out_stream.Seek(0, SeekOrigin.Begin);
using (StreamReader stream_reader = new StreamReader(out_stream))
{
return stream_reader.ReadToEnd();
}
}
}
}
// Convert a byte array into a readable string of hexadecimal values.
public static string ToHex(this byte[] the_bytes)
{
return ToHex(the_bytes, false);
}
public static string ToHex(this byte[] the_bytes, bool add_spaces)
{
string result = "";
string separator = "";
if (add_spaces) separator = " ";
for (int i = 0; i < the_bytes.Length; i++)
{
result += the_bytes[i].ToString("x2") + separator;
}
return result;
}
// Convert a string containing 2-digit hexadecimal values into a byte array.
public static byte[] ToBytes(this string the_string)
{
List<byte> the_bytes = new List<byte>();
the_string = the_string.Replace(" ", "");
for (int i = 0; i < the_string.Length; i += 2)
{
the_bytes.Add(
byte.Parse(the_string.Substring(i, 2),
System.Globalization.NumberStyles.HexNumber));
}
return the_bytes.ToArray();
}
#endregion // Encrypt Strings and Byte[]
通过上面的代码,您将获得一个列表字节,此函数将其转换为列表字符
// Return a string that represents the byte array
// as a series of hexadecimal values separated
// by a separator character.
public static string ToHex(this byte[] the_bytes, char separator)
{
return BitConverter.ToString(the_bytes, 0).Replace('-', separator);
}
我从字符串列表中获取数据,像这样加密它们,并想将它们写入文件
var encryptedLines = (from line in output
select Helper.ToHex(Encryption.EncryptAES(line, symKey),' ').ToList());
但是
File.WriteAllLines(fileWrite, encryptedLines);
总是给我标题的异常,或者如果我写结果,它当然只是写下System.Collections.Generic.List`1[System.Char],因为它并没有真正将数据类型转换为列表字符串
那只蜜蜂说我不明白为什么我不能将所有字符行写入文件?
我尝试过
.ToString()
或var result = encryptedLines.Select(c => c.ToString()).ToList();
您可以将字符列表转换为字符数组或使用
将字符列表转换为字符串 listOfChars.Aggregate("", (str, x) => str + x);
^ 不推荐这种方法,因为它具有二次复杂度(查看此答案的评论)
感谢 Lee 的评论,我再次检查了一下,发现这样做效率更高:
listOfChars.Aggregate(new StringBuilder(""), (str, x) => str.Append(x));