//对称加密
private void button1_Click(object sender, EventArgs e)
{
EncryptFile(@"D:\temp.txt",@"D:\tempJiaMi.txt","123随意");
}
private void btnDecrytion_Click(object sender, EventArgs e)
{
DecryptFile(@"D:\tempJiaMi.txt", @"D:\tempJieMi.txt", "123随意");
}
static int bufferSize = 128 * 1024;
static byte[] salt = { 134, 216, 7, 36, 88, 164, 91, 227, 174, 76, 191, 197, 192, 154, 200, 248 };//密钥salt
static byte[] iv = { 134, 216, 7, 36, 88, 164, 91, 227, 174, 76, 191, 197, 192, 154, 200, 248 };//初始化向量
//初始化并返回对称加密算法
static SymmetricAlgorithm CreateRijndael(string password, byte[] salt)
{
//使用用来导出密钥的密码、密钥 salt、哈希名和迭代数初始化 PasswordDeriveBytes 类的新实例
PasswordDeriveBytes pdb = new PasswordDeriveBytes(password,salt,"SHA256",1000);
SymmetricAlgorithm sma = Rijndael.Create();
sma.KeySize = 256;
sma.Key = pdb.GetBytes(32);
sma.Padding = PaddingMode.PKCS7;
return sma;
}
/* 从 SymmetricAlgorithm 类派生的类使用一种称为密码块链接 (CBC) 的链接模式,
* 该模式需要密钥 (Key) 和初始化向量 (IV) 才能执行数据的加密转换。
* 若要解密使用其中一个 SymmetricAlgorithm 类加密的数据,
* 必须将 Key 属性和 IV 属性设置为用于加密的相同值。为了保证对称算法有效,
* 必须只有发送方和接收方知道密钥。
* */
static void EncryptFile(string inFile,string outFile,string password)
{
using(FileStream inFileStream =File.OpenRead(inFile),
outFileStream =File.Open(outFile,FileMode.OpenOrCreate))
using (SymmetricAlgorithm algorithm = CreateRijndael(password, salt))
{
algorithm.IV = iv;
using (CryptoStream cryptoStream = new CryptoStream(outFileStream,
algorithm.CreateEncryptor(), CryptoStreamMode.Write))
{
byte[] bytes=new byte[bufferSize];
int readSize = 1;
while ((readSize = inFileStream.Read(bytes, 0, bytes.Length)) != 0)
{
cryptoStream.Write(bytes,0,readSize);
}
cryptoStream.Flush();
}
}
}
static void DecryptFile(string inFile, string outFile, string password)
{
using(FileStream inFileStream =File.OpenRead(inFile),
outFileStream =File.OpenWrite(outFile))
using (SymmetricAlgorithm algorithm = CreateRijndael(password, salt))
{
algorithm.IV = iv;
using (CryptoStream cryptoStream = new CryptoStream(inFileStream,
algorithm.CreateDecryptor(), CryptoStreamMode.Read))
{
byte[] bytes =new byte[bufferSize];
int readSize = -1;
int numReads = (int)(inFileStream.Length / bufferSize);
int slack = (int)(inFileStream.Length % bufferSize);
for (int i = 0; i < numReads; i++)
{
readSize = cryptoStream.Read(bytes,0,bytes.Length);
outFileStream.Write(bytes,0,readSize);
}
if (slack > 0)
{
readSize = cryptoStream.Read(bytes, 0, (int)slack);
outFileStream.Write(bytes,0,readSize);
}
outFileStream.Flush();
}
}
}
对称加密
最新推荐文章于 2023-08-04 16:39:05 发布