using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;
namespace EncryptionAndDecryption
{
public class SHA1
{
#region SHA1加密
///
/// 使用缺省密钥给字符串加密
///
///
///
public string SHA1_Encrypt(string Source_String)
{
byte[] StrRes = Encoding.Default.GetBytes(Source_String);
HashAlgorithm iSHA = new SHA1CryptoServiceProvider();
StrRes = iSHA.ComputeHash(StrRes);
StringBuilder EnText = new StringBuilder();
foreach (byte iByte in StrRes)
{
EnText.AppendFormat("{0:x2}", iByte);
}
return EnText.ToString();
}
///
/// 使用给定密钥加密
///
/// 原始文字
/// 密钥
///
public static string Encryption(string original, string key)
{
return SHA1.Encryption(original, key);
}
///
/// 使用缺省密钥加密文件
///
///
///
public void DesEncrypt(string m_InFilePath, string m_OutFilePath)
{
try
{
FileStream fin = new FileStream(m_InFilePath, FileMode.Open, FileAccess.Read);
FileStream fout = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write);
fout.SetLength(0);
byte[] bin = new byte[100]; //这中间的加密存储。
long rdlen = 0;
long totlen = fin.Length;
int len;
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(), CryptoStreamMode.Write);
//读取输入文件,然后加密并写入到输出文件。
while (rdlen < totlen)
{
len = fin.Read(bin, 0, 100);
encStream.Write(bin, 0, len);
rdlen = rdlen + len;
}
encStream.Close();
fout.Close();
fin.Close();
}
catch
{
//MessageBox.Show(error.Message.ToString());
}
}
///
/// 使用给定密钥加密文件
///
/// Encrypt file path
/// output file
///
public void DesEncrypt(string m_InFilePath, string m_OutFilePath, string strEncrKey)
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
FileStream fin = new FileStream(m_InFilePath, FileMode.Open, FileAccess.Read);
FileStream fout = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write);
fout.SetLength(0);
byte[] bin = new byte[100]; //这中间的加密存储。
long rdlen = 0;
long totlen = fin.Length;
int len;
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
//读取输入文件,然后加密并写入到输出文件。
while (rdlen < totlen)
{
len = fin.Read(bin, 0, 100);
encStream.Write(bin, 0, len);
rdlen = rdlen + len;
}
encStream.Close();
fout.Close();
fin.Close();
}
catch
{
//MessageBox.Show(error.Message.ToString());
}
}
///
/// 生成sha1摘要
///
/// 数据源
///
public static byte[] makeSHA1(byte[] original)
{
SHA1CryptoServiceProvider hashsha1 = new SHA1CryptoServiceProvider();
byte[] keyhash = hashsha1.ComputeHash(original);
hashsha1 = null;
return keyhash;
}
#endregion
}
}