C# 带satting的AES双向加密
我在应用程序中使用Mark Brittingham编写的以下类进行双向AES加密。我将如何修改它以添加盐串C# 带satting的AES双向加密,c#,encryption,aes,C#,Encryption,Aes,我在应用程序中使用Mark Brittingham编写的以下类进行双向AES加密。我将如何修改它以添加盐串 using System; using System.Data; using System.Security.Cryptography; using System.IO; public class SimpleAES { // Change these keys private byte[] Key = { 123, 217, 19, 11, 24, 26, 85, 4
using System;
using System.Data;
using System.Security.Cryptography;
using System.IO;
public class SimpleAES
{
// Change these keys
private byte[] Key = { 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 };
private byte[] Vector = { 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 2521, 112, 79, 32, 114, 156 };
private ICryptoTransform EncryptorTransform, DecryptorTransform;
private System.Text.UTF8Encoding UTFEncoder;
public SimpleAES()
{
//This is our encryption method
RijndaelManaged rm = new RijndaelManaged();
//Create an encryptor and a decryptor using our encryption method, key, and vector.
EncryptorTransform = rm.CreateEncryptor(this.Key, this.Vector);
DecryptorTransform = rm.CreateDecryptor(this.Key, this.Vector);
//Used to translate bytes to text and vice versa
UTFEncoder = new System.Text.UTF8Encoding();
}
/// -------------- Two Utility Methods (not used but may be useful) -----------
/// Generates an encryption key.
static public byte[] GenerateEncryptionKey()
{
//Generate a Key.
RijndaelManaged rm = new RijndaelManaged();
rm.GenerateKey();
return rm.Key;
}
/// Generates a unique encryption vector
static public byte[] GenerateEncryptionVector()
{
//Generate a Vector
RijndaelManaged rm = new RijndaelManaged();
rm.GenerateIV();
return rm.IV;
}
/// ----------- The commonly used methods ------------------------------
/// Encrypt some text and return a string suitable for passing in a URL.
public string EncryptToString(string TextValue)
{
return ByteArrToString(Encrypt(TextValue));
}
/// Encrypt some text and return an encrypted byte array.
public byte[] Encrypt(string TextValue)
{
//Translates our text value into a byte array.
Byte[] bytes = UTFEncoder.GetBytes(TextValue);
//Used to stream the data in and out of the CryptoStream.
MemoryStream memoryStream = new MemoryStream();
/*
* We will have to write the unencrypted bytes to the stream,
* then read the encrypted result back from the stream.
*/
#region Write the decrypted value to the encryption stream
CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write);
cs.Write(bytes, 0, bytes.Length);
cs.FlushFinalBlock();
#endregion
#region Read encrypted value back out of the stream
memoryStream.Position = 0;
byte[] encrypted = new byte[memoryStream.Length];
memoryStream.Read(encrypted, 0, encrypted.Length);
#endregion
//Clean up.
cs.Close();
memoryStream.Close();
return encrypted;
}
/// The other side: Decryption methods
public string DecryptString(string EncryptedString)
{
return Decrypt(StrToByteArray(EncryptedString));
}
/// Decryption when working with byte arrays.
public string Decrypt(byte[] EncryptedValue)
{
#region Write the encrypted value to the decryption stream
MemoryStream encryptedStream = new MemoryStream();
CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write);
decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length);
decryptStream.FlushFinalBlock();
#endregion
#region Read the decrypted value from the stream.
encryptedStream.Position = 0;
Byte[] decryptedBytes = new Byte[encryptedStream.Length];
encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length);
encryptedStream.Close();
#endregion
return UTFEncoder.GetString(decryptedBytes);
}
/// Convert a string to a byte array. NOTE: Normally we'd create a Byte Array from a string using an ASCII encoding (like so).
// System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
// return encoding.GetBytes(str);
// However, this results in character values that cannot be passed in a URL. So, instead, I just
// lay out all of the byte values in a long string of numbers (three per - must pad numbers less than 100).
public byte[] StrToByteArray(string str)
{
if (str.Length == 0)
throw new Exception("Invalid string value in StrToByteArray");
byte val;
byte[] byteArr = new byte[str.Length / 3];
int i = 0;
int j = 0;
do
{
val = byte.Parse(str.Substring(i, 3));
byteArr[j++] = val;
i += 3;
}
while (i < str.Length);
return byteArr;
}
// Same comment as above. Normally the conversion would use an ASCII encoding in the other direction:
// System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
// return enc.GetString(byteArr);
public string ByteArrToString(byte[] byteArr)
{
byte val;
string tempStr = "";
for (int i = 0; i <= byteArr.GetUpperBound(0); i++)
{
val = byteArr[i];
if (val < (byte)10)
tempStr += "00" + val.ToString();
else if (val < (byte)100)
tempStr += "0" + val.ToString();
else
tempStr += val.ToString();
}
return tempStr;
}
}
使用系统;
使用系统数据;
使用System.Security.Cryptography;
使用System.IO;
公共类单纯形
{
//换这些钥匙
私有字节[]密钥={123、217、19、11、24、26、85、45、114、184、27、162、37、112、222、209、241、24、175、144、173、53、196、29、24、26、17、218、131、236、53、209};
私有字节[]向量={146、64、191、111、23、3、113、119、231、121、2521、112、79、32、114、156};
专用ICryptorTransform加密传输、解密传输;
private System.Text.utf8编码UTFEncoder;
公共单纯形()
{
//这是我们的加密方法
RijndaelManaged rm=新的RijndaelManaged();
//使用我们的加密方法、密钥和向量创建加密程序和解密程序。
EncryptorTransform=rm.CreateEncryptor(this.Key,this.Vector);
DecryptorTransform=rm.CreateDecryptor(this.Key,this.Vector);
//用于将字节转换为文本,反之亦然
UTFEncoder=new System.Text.UTF8Encoding();
}
///------两种实用方法(未使用,但可能有用)-----------
///生成加密密钥。
静态公共字节[]GenerateEncryptionKey()
{
//生成一个密钥。
RijndaelManaged rm=新的RijndaelManaged();
rm.GenerateKey();
返回rm.Key;
}
///生成唯一的加密向量
静态公共字节[]GenerateEncryptionVector()
{
//生成向量
RijndaelManaged rm=新的RijndaelManaged();
rm.GenerateIV();
返回rm.IV;
}
///------------常用的方法------------------
///加密一些文本并返回适合传入URL的字符串。
公共字符串EncryptToString(字符串TextValue)
{
返回ByteArrToString(Encrypt(TextValue));
}
///加密一些文本并返回加密的字节数组。
公共字节[]加密(字符串TextValue)
{
//将文本值转换为字节数组。
Byte[]bytes=UTFEncoder.GetBytes(TextValue);
//用于流式传输加密流中的数据。
MemoryStream MemoryStream=新的MemoryStream();
/*
*我们必须将未加密的字节写入流,
*然后从流中读取加密结果。
*/
#区域将解密的值写入加密流
CryptoStream cs=新的加密流(memoryStream、EncryptorTransform、CryptoStreamMode.Write);
cs.Write(字节,0,字节.长度);
cs.FlushFinalBlock();
#端区
#区域从流中读取加密值
memoryStream.Position=0;
字节[]加密=新字节[memoryStream.Length];
memoryStream.Read(加密的,0,加密的.Length);
#端区
//清理一下。
cs.Close();
memoryStream.Close();
返回加密;
}
///另一方面:解密方法
公共字符串解密字符串(字符串加密字符串)
{
返回解密(StrToByteArray(EncryptedString));
}
///使用字节数组时进行解密。
公共字符串解密(字节[]EncryptedValue)
{
#区域将加密值写入解密流
MemoryStream encryptedStream=新的MemoryStream();
CryptoStream DecryptoStream=新的加密流(encryptedStream、DecryptoTransform、CryptoStreamMode.Write);
decryptStream.Write(EncryptedValue,0,EncryptedValue.Length);
decryptStream.FlushFinalBlock();
#端区
#区域从流中读取解密的值。
encryptedStream.Position=0;
Byte[]decryptedBytes=新字节[encryptedStream.Length];
encryptedStream.Read(decryptedBytes,0,decryptedBytes.Length);
encryptedStream.Close();
#端区
返回UTFEncoder.GetString(decryptedBytes);
}
///将字符串转换为字节数组。注意:通常我们会使用ASCII编码从字符串创建字节数组(如下所示)。
//System.Text.asciencoding encoding=新的System.Text.asciencoding();
//返回编码.GetBytes(str);
//但是,这会导致无法在URL中传递字符值
//将所有字节值排列成一长串数字(每个焊盘必须有三个小于100的数字)。
公共字节[]StrToByteArray(字符串str)
{
如果(str.Length==0)
抛出新异常(“StrToByteArray中的字符串值无效”);
字节val;
byte[]byteArr=新字节[str.Length/3];
int i=0;
int j=0;
做
{
val=byte.Parse(str.Substring(i,3));
byteArr[j++]=val;
i+=3;
}
而(i 对于(inti=0;i我使用了一个带有散列密码的salt字符串,但没有使用双向加密
在键和向量的同时添加一个salt字符串(它们应该存储在其他地方,而不是硬编码在类中,但现在,这将起作用)
在EncryptToString中使用,添加到文本值:
return ByteArrToString(Encrypt(TextValue + salt));
然后在解密字符串中删除它:
return Decrypt(StrToByteArray(EncryptedString)).Replace(salt, string.Empty);
我最近发现了Mark的代码,并对其进行了轻微的修改。我通过在字节数组的开头和结尾添加加密随机数添加了一些salt。salt的大小可以随
return Decrypt(StrToByteArray(EncryptedString)).Replace(salt, string.Empty);
using System;
using System.Security.Cryptography;
using System.IO;
public class SimpleAES
{
// Change these keys
private byte[] Key = { 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 };
private byte[] Vector = { 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 2521, 112, 79, 32, 114, 156 };
private const int Salt = 8;
private ICryptoTransform EncryptorTransform, DecryptorTransform;
private System.Text.UTF8Encoding UTFEncoder;
public SimpleAES()
{
//This is our encryption method
RijndaelManaged rm = new RijndaelManaged();
//Create an encryptor and a decryptor using our encryption method, key, and vector.
EncryptorTransform = rm.CreateEncryptor(this.Key, this.Vector);
DecryptorTransform = rm.CreateDecryptor(this.Key, this.Vector);
//Used to translate bytes to text and vice versa
UTFEncoder = new System.Text.UTF8Encoding();
}
/// -------------- Two Utility Methods (not used but may be useful) -----------
/// Generates an encryption key.
static public byte[] GenerateEncryptionKey()
{
//Generate a Key.
RijndaelManaged rm = new RijndaelManaged();
rm.GenerateKey();
return rm.Key;
}
/// Generates a unique encryption vector
static public byte[] GenerateEncryptionVector()
{
//Generate a Vector
RijndaelManaged rm = new RijndaelManaged();
rm.GenerateIV();
return rm.IV;
}
/// ----------- The commonly used methods ------------------------------
/// Encrypt some text and return a string suitable for passing in a URL.
public string EncryptString(string TextValue)
{
return (TextValue != "") ? Convert.ToBase64String(Encrypt(TextValue)) : "";
}
/// Encrypt some text and return an encrypted byte array.
public byte[] Encrypt(string TextValue)
{
//Translates our text value into a byte array.
Byte[] pepper = UTFEncoder.GetBytes(TextValue);
// add salt
Byte[] salt = new byte[Salt];
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
crypto.GetNonZeroBytes(salt);
Byte[] bytes = new byte[2 * Salt + pepper.Length];
System.Buffer.BlockCopy(salt, 0, bytes, 0, Salt);
System.Buffer.BlockCopy(pepper, 0, bytes, Salt, pepper.Length);
crypto.GetNonZeroBytes(salt);
System.Buffer.BlockCopy(salt, 0, bytes, Salt + pepper.Length, Salt);
//Used to stream the data in and out of the CryptoStream.
MemoryStream memoryStream = new MemoryStream();
/*
* We will have to write the unencrypted bytes to the stream,
* then read the encrypted result back from the stream.
*/
#region Write the decrypted value to the encryption stream
CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write);
cs.Write(bytes, 0, bytes.Length);
cs.FlushFinalBlock();
#endregion
#region Read encrypted value back out of the stream
memoryStream.Position = 0;
byte[] encrypted = new byte[memoryStream.Length];
memoryStream.Read(encrypted, 0, encrypted.Length);
#endregion
//Clean up.
cs.Close();
memoryStream.Close();
return encrypted;
}
/// The other side: Decryption methods
public string DecryptString(string EncryptedString)
{
return (EncryptedString != "") ? Decrypt(Convert.FromBase64String(EncryptedString)) : "";
}
/// Decryption when working with byte arrays.
public string Decrypt(byte[] EncryptedValue)
{
#region Write the encrypted value to the decryption stream
MemoryStream encryptedStream = new MemoryStream();
CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write);
decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length);
decryptStream.FlushFinalBlock();
#endregion
#region Read the decrypted value from the stream.
encryptedStream.Position = 0;
Byte[] decryptedBytes = new Byte[encryptedStream.Length];
encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length);
encryptedStream.Close();
#endregion
// remove salt
int len = decryptedBytes.Length - 2 * Salt;
Byte[] pepper = new Byte[len];
System.Buffer.BlockCopy(decryptedBytes, Salt, pepper, 0, len);
return UTFEncoder.GetString(pepper);
}
}