<pre name="code" class="csharp"> //Encryption,MD5 Hash Algorithm
class MD5Encryption
{
public string GetMd5Hash(string input)
{
using (MD5CryptoServiceProvider md5=new MD5CryptoServiceProvider ())
{
return BitConverter.ToString(md5.ComputeHash
(UTF8Encoding.Default.GetBytes(input))).Replace("-","");
}
}
public string GetFileMd5Hash(string filePath)
{
using (MD5CryptoServiceProvider md5=new MD5CryptoServiceProvider ())
using (FileStream fs=new FileStream(filePath,FileMode.Open,FileAccess.Read,FileShare.Read))
{
return BitConverter.ToString(md5.ComputeHash(fs)).Replace("-", "");
}
}
}
对称加密
//Symmetric Algorithm
class SymmetricEncryption
{
static int bufferSize = 128 * 1024;
//salt key
static byte[] salt = { 134, 216, 7, 36, 88, 164, 91, 227, 174, 76, 191, 197, 192, 154, 200, 248 };
static byte[] iv = { 134, 216, 7, 36, 88, 164, 91, 227, 174, 76, 191, 197, 192, 154, 200, 248 };
private static SymmetricAlgorithm CreateRijndael(string password, byte[] salt)
{
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;
}
public static void EncryptFile(string inFile, string outFile, string password)
{
using (FileStream infs=File.OpenRead(inFile),
outfs=File.Open(outFile,FileMode.OpenOrCreate))
using (SymmetricAlgorithm algorithm =CreateRijndael(password,salt))
{
algorithm.IV = iv;
using (CryptoStream crypoStream=new CryptoStream (outfs,algorithm.CreateEncryptor(),CryptoStreamMode.Write))
{
byte[] bytes = new byte[bufferSize];
int readSize = -1;
while ((readSize=infs.Read(bytes,0,bytes.Length))!=0)
{
crypoStream.Write(bytes, 0, readSize);
}
crypoStream.Flush();
}
}
}
public static void DecryptFile(string inFile, string outFile, string password)
{
using (FileStream infs=File.OpenRead(inFile),
outfs=File.OpenWrite(outFile))
using(SymmetricAlgorithm algorithm=CreateRijndael(password,salt))
{
algorithm.IV = iv;
using (CryptoStream crypoStream=new CryptoStream (infs,algorithm.CreateDecryptor(),CryptoStreamMode.Read))
{
byte[] bytes = new byte[bufferSize];
int readSize = -1;
int numReads = (int)(infs.Length / bufferSize);
int slack = (int)(infs.Length % bufferSize);
for (int i = 0; i < numReads; ++i)
{
readSize = crypoStream.Read(bytes, 0, bytes.Length);
outfs.Write(bytes, 0, readSize);
}
if (slack>0)
{
readSize = crypoStream.Read(bytes, 0, (int)slack);
outfs.Write(bytes, 0, readSize);
}
outfs.Flush();
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/14831.html