使用实例:
private string urlPath = "";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
urlPath = Server.MapPath("~/file/");
encryptInfo();
}
}
/// <summary>
/// 字符串加密解密
/// </summary>
private void encryptInfo()
{
Response.Write("MD5加密字符串:" + EncryptHelper.GetMD5("123456") + "<br />");
Response.Write("MD5_16加密字符串:" + EncryptHelper.GetMD5_16("123456") + "<br />");
Response.Write("MD5_32加密字符串:" + EncryptHelper.GetMD5_32("123456", "utf-8") + "<br />");
Response.Write("MD5(哈希)加密字符串:" + EncryptHelper.GetHash("123456") + "<br />");
Response.Write("DES加密字符串:" + EncryptHelper.DESEncrypt("123456", "zhengdec") + "<br />");
Response.Write("DES解密字符串:" + EncryptHelper.DESDecrypt(EncryptHelper.DESEncrypt("123456", "zhengdec"), "zhengdec") + "<br />");
string xmlKeys = "";
string xmlPublicKey = "";
EncryptHelper.RSAKey(out xmlKeys, out xmlPublicKey);
string mm = EncryptHelper.RSAEncrypt("123456", xmlPublicKey);
Response.Write("RSA加密字符串:" + mm + "<br />");
Response.Write("RSA解密字符串:" + EncryptHelper.RSADecrypt(mm, xmlKeys) + "<br />");
Response.Write("AES加密字符串:" + EncryptHelper.AESEncrypt("123456", "zhengdec") + "<br />");
Response.Write("AES解密字符串:" + EncryptHelper.AESDecrypt(EncryptHelper.AESEncrypt("123456", "zhengdec"), "zhengdec") + "<br />");
Response.Write("DES(哈希)加密字符串:" + EncryptHelper.EncryptText("123456", "zhengdec") + "<br />");
Response.Write("DES(哈希)解密字符串:" + EncryptHelper.DecryptText(EncryptHelper.EncryptText("123456", "zhengdec"), "zhengdec") + "<br />");
Response.Write("Base64加密字符串:" + EncryptHelper.EncodeBase64("123456") + "<br />");
Response.Write("Base64解密字符串:" + EncryptHelper.DecodeBase64(EncryptHelper.EncodeBase64("123456")) + "<br />");
/*文件的加密解密两种:第一种需要传一个关键词、第二种直接弄成byte[]传递*/
EncryptHelper.EncryptData(urlPath + "test.txt", urlPath + "text_e.txt", "zhengdec");
//EncryptHelper.DecryptData(urlPath + "text_e.txt", urlPath + "test.txt", "zhengdec");
byte[] deskey = { 198, 125, 20, 111, 77, 71, 228, 9 };
byte[] desiv = { 223, 20, 19, 27, 226, 119, 149, 85 };
EncryptHelper.EncryptData(urlPath + "test.txt", urlPath + "text_e.txt", deskey, desiv); //加密后存储到文件里面(加密文件)
//EncryptHelper.DecryptData(urlPath + "text_e.txt", urlPath + "test.txt", deskey, desiv); //解密文件
/*文件的加密解密两种:第一种需要传一个关键词、第二种直接弄成byte[]传递*/
}类库信息:
/// <summary>
/// 加密解密操作类
/// </summary>
public class EncryptHelper
{
#region MD5字符串加密的算法,非对称加密
/// <summary>
/// MD5加密算法,无需解密
/// </summary>
/// <param name="sEncrypt">加密字符串</param>
/// <returns></returns>
public static string GetMD5(string sEncrypt)
{
MD5CryptoServiceProvider MD5CSP = new MD5CryptoServiceProvider();
byte[] MD5Source = System.Text.Encoding.UTF8.GetBytes(sEncrypt);
byte[] MD5Out = MD5CSP.ComputeHash(MD5Source);
return Convert.ToBase64String(MD5Out);
}
/// <summary>
/// 16位加密
/// </summary>
/// <param name="sEncrypt">加密字符串</param>
/// <returns></returns>
public static string GetMD5_16(string sEncrypt)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(sEncrypt)), 4, 8);
t2 = t2.Replace("-", "");
return t2;
}
/// <summary>
/// 32位加密
/// </summary>
/// <param name="sEncrypt">加密字符串</param>
/// <param name="iCharset">加密字符串编码</param>
/// <returns></returns>
public static string GetMD5_32(string sEncrypt, string iCharset)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] t = md5.ComputeHash(Encoding.GetEncoding(iCharset).GetBytes(sEncrypt));
StringBuilder sb = new StringBuilder(32);
for (int i = 0; i < t.Length; i++)
{
sb.Append(t[i].ToString("x").PadLeft(2, '0'));
}
return sb.ToString();
}
/// <summary>
/// 哈希加密算法,对原始数据进行MD5加密
/// </summary>
/// <param name="m_strSource">待加密数据</param>
/// <returns>返回机密后的数据</returns>
public static string GetHash(string m_strSource)
{
HashAlgorithm algorithm = HashAlgorithm.Create("MD5");
byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
byte[] inArray = algorithm.ComputeHash(bytes);
return Convert.ToBase64String(inArray);
}
#endregion
#region DES字符串加密及解密的算法,对称加密
/// <summary>
/// DES加密算法
/// </summary>
/// <param name="pToEncrypt">加密字符串</param>
/// <param name="sKey">加密密钥必须为8位</param>
/// <returns></returns>
public static string DESEncrypt(string pToEncrypt, string sKey)
{
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); //密钥
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); //向量
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
ret.ToString();
return ret.ToString();
}
catch
{
return "";
}
}
/// <summary>
/// DES解密算法
/// </summary>
/// <param name="pToDecrypt">解密字符串</param>
/// <param name="sKey">解密密钥必须为8位</param>
/// <returns></returns>
public static string DESDecrypt(string pToDecrypt, string sKey)
{
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
for (int x = 0; x < pToDecrypt.Length / 2; x++)
{
int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); //密钥
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); //向量
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
return System.Text.Encoding.ASCII.GetString(ms.ToArray());
}
catch
{
return "";
}
}
#endregion
#region RSA字符串加密及解密的算法,对称加密
/// <summary>
/// RSA产生密钥
/// </summary>
/// <param name="xmlKeys">私钥</param>
/// <param name="xmlPublicKey">公钥</param>
public static void RSAKey(out string xmlKeys, out string xmlPublicKey)
{
try
{
System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
xmlKeys = rsa.ToXmlString(true);
xmlPublicKey = rsa.ToXmlString(false);
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// RSA加密算法
/// </summary>
/// <param name="pToEncrypt">待加密的数据</param>
/// <param name="pKey">加密公钥</param>
/// <returns>RSA公钥加密后的数据</returns>
public static string RSAEncrypt(string pToEncrypt, string pKey)
{
string str2;
try
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(pKey);
byte[] bytes = new UnicodeEncoding().GetBytes(pToEncrypt);
str2 = Convert.ToBase64String(provider.Encrypt(bytes, false));
}
catch (Exception exception)
{
throw exception;
}
return str2;
}
/// <summary>
/// RSA解密算法
/// </summary>
/// <param name="pToDecrypt">待解密的数据</param>
/// <param name="pKey">解密私钥</param>
/// <returns>解密后的结果</returns>
public static string RSADecrypt(string pToDecrypt, string pKey)
{
string str2;
try
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(pKey);
byte[] rgb = Convert.FromBase64String(pToDecrypt);
byte[] buffer2 = provider.Decrypt(rgb, false);
str2 = new UnicodeEncoding().GetString(buffer2);
}
catch (Exception exception)
{
throw exception;
}
return str2;
}
#endregion
#region AES字符串加密及解密的算法,对称加密
/*/// <summary>
/// AES 加密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
/// </summary>
/// <param name="EncryptString">待加密密文</param>
/// <param name="EncryptKey">加密密钥</param>
/// <returns></returns>
public static string AESEncrypt(string EncryptString, string EncryptKey)
{
string m_strEncrypt = "";
byte[] m_btIV = Convert.FromBase64String("4QrcOUm6Wau+VuBX8g+IPg==");
Rijndael m_AESProvider = Rijndael.Create();
try
{
byte[] m_btEncryptString = Encoding.Default.GetBytes(EncryptString);
MemoryStream m_stream = new MemoryStream();
CryptoStream m_csstream = new CryptoStream(m_stream, m_AESProvider.CreateEncryptor(Encoding.Default.GetBytes(EncryptKey), m_btIV), CryptoStreamMode.Write);
m_csstream.Write(m_btEncryptString, 0, m_btEncryptString.Length); m_csstream.FlushFinalBlock();
m_strEncrypt = Convert.ToBase64String(m_stream.ToArray());
m_stream.Close(); m_stream.Dispose();
m_csstream.Close(); m_csstream.Dispose();
}
catch (IOException ex) { throw ex; }
catch (CryptographicException ex) { throw ex; }
catch (ArgumentException ex) { throw ex; }
catch (Exception ex) { throw ex; }
finally { m_AESProvider.Clear(); }
return m_strEncrypt;
}
/// <summary>
/// AES 解密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
/// </summary>
/// <param name="DecryptString">待解密密文</param>
/// <param name="DecryptKey">解密密钥</param>
/// <returns></returns>
public static string AESDecrypt(string DecryptString, string DecryptKey)
{
string m_strDecrypt = "";
byte[] m_btIV = Convert.FromBase64String("4QrcOUm6Wau+VuBX8g+IPg==");
Rijndael m_AESProvider = Rijndael.Create();
try
{
byte[] m_btDecryptString = Convert.FromBase64String(DecryptString);
MemoryStream m_stream = new MemoryStream();
CryptoStream m_csstream = new CryptoStream(m_stream, m_AESProvider.CreateDecryptor(Encoding.Default.GetBytes(DecryptKey), m_btIV), CryptoStreamMode.Write);
m_csstream.Write(m_btDecryptString, 0, m_btDecryptString.Length); m_csstream.FlushFinalBlock();
m_strDecrypt = Encoding.Default.GetString(m_stream.ToArray());
m_stream.Close(); m_stream.Dispose();
m_csstream.Close(); m_csstream.Dispose();
}
catch (IOException ex) { throw ex; }
catch (CryptographicException ex) { throw ex; }
catch (ArgumentException ex) { throw ex; }
catch (Exception ex) { throw ex; }
finally { m_AESProvider.Clear(); }
return m_strDecrypt;
}*/
/// <summary>
/// 有密码的AES加密
/// </summary>
/// <param name="pToEncrypt">加密字符</param>
/// <param name="sKey">加密密钥必须为8位</param>
/// <returns></returns>
public static string AESEncrypt(string pToEncrypt, string sKey)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 128;
rijndaelCipher.BlockSize = 128;
byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(sKey);
byte[] keyBytes = new byte[16];
int len = pwdBytes.Length;
if (len > keyBytes.Length) len = keyBytes.Length;
System.Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
byte[] ivBytes = Convert.FromBase64String(EncryptHelper.GetMD5(sKey)); //使用MD5对字符串加密一次得到向量
rijndaelCipher.IV = ivBytes;
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
byte[] plainText = Encoding.UTF8.GetBytes(pToEncrypt);
byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
return Convert.ToBase64String(cipherBytes);
}
/// <summary>
/// AES解密
/// </summary>
/// <param name="pToDecrypt">加密字符</param>
/// <param name="sKey">加密密钥必须为8位</param>
/// <returns></returns>
public static string AESDecrypt(string pToDecrypt, string sKey)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 128;
rijndaelCipher.BlockSize = 128;
byte[] encryptedData = Convert.FromBase64String(pToDecrypt);
byte[] pwdBytes = System.Text.Encoding.UTF8.GetBytes(sKey);
byte[] keyBytes = new byte[16];
int len = pwdBytes.Length;
if (len > keyBytes.Length) len = keyBytes.Length;
System.Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
byte[] ivBytes = Convert.FromBase64String(EncryptHelper.GetMD5(sKey)); //使用MD5对字符串加密一次得到向量
rijndaelCipher.IV = ivBytes;
ICryptoTransform transform = rijndaelCipher.CreateDecryptor();
byte[] plainText = transform.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
return Encoding.UTF8.GetString(plainText);
}
#endregion
#region DES使用哈希加密及解密的算法,对称加密
/// <summary>
/// DES使用哈希加密算法
/// </summary>
/// <param name="pToEncrypt">加密字符串</param>
/// <param name="sKey">加密密钥</param>
/// <returns></returns>
public static string EncryptText(string pToEncrypt, string sKey)
{
StringBuilder ret = new StringBuilder();
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray;
inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
//通过两次哈希密码设置对称算法的初始化向量
des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile
(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8), "sha1").Substring(0, 8));
//通过两次哈希密码设置算法的机密密钥
des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile
(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8), "md5").Substring(0, 8));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
return ret.ToString();
}
catch
{
return "";
}
}
/// <summary>
/// DES使用哈希解密算法
/// </summary>
/// <param name="pToDecrypt">解密字符串</param>
/// <param name="sKey">加密密钥</param>
/// <returns></returns>
public static string DecryptText(string pToDecrypt, string sKey)
{
try
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider(); //定义DES加密对象
int len;
len = pToDecrypt.Length / 2;
byte[] inputByteArray = new byte[len];
int x, i;
for (x = 0; x < len; x++)
{
i = Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16);
inputByteArray[x] = (byte)i;
}
//通过两次哈希密码设置对称算法的初始化向量
des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile
(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8), "sha1").Substring(0, 8));
//通过两次哈希密码设置算法的机密密钥
des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile
(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8), "md5").Substring(0, 8));
System.IO.MemoryStream ms = new System.IO.MemoryStream();//定义内存流
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);//定义加密流
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Encoding.Default.GetString(ms.ToArray());
}
catch
{
return "";
}
}
#endregion
#region DES文件加密及解密,对称加密
/// <summary>
/// 加密文件
/// </summary>
/// <param name="inName">需加密文件路径</param>
/// <param name="outName">需加密后文件存放路径</param>
/// <param name="sKey">加密密钥必须为8位</param>
public static void EncryptData(String inName, String outName, string sKey)
{
//Create the file streams to handle the input and output files.
FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
fout.SetLength(0);
//Create variables to help with read and write.
byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
long rdlen = 0; //This is the total number of bytes written.
long totlen = fin.Length; //This is the total length of the input file.
int len; //This is the number of bytes to be written at a time.
byte[] desKey = ASCIIEncoding.ASCII.GetBytes(sKey);
byte[] desIV = Convert.FromBase64String(EncryptHelper.GetMD5(sKey)); //可以自定义
DES des = new DESCryptoServiceProvider();
CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);
//Read from the input file, then encrypt and write to the output file.
while (rdlen < totlen)
{
len = fin.Read(bin, 0, 100);
encStream.Write(bin, 0, len);
rdlen = rdlen + len;
}
encStream.Close();
fout.Close();
fin.Close();
}
/// <summary>
/// 解密文件
/// </summary>
/// <param name="inName">需解密文件路径</param>
/// <param name="outName">需解密后文件存放路径</param>
/// <param name="sKey">解密密钥必须为8位</param>
public static void DecryptData(String inName, String outName, string sKey)
{
//Create the file streams to handle the input and output files.
FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
fout.SetLength(0);
//Create variables to help with read and write.
byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
long rdlen = 0; //This is the total number of bytes written.
long totlen = fin.Length; //This is the total length of the input file.
int len; //This is the number of bytes to be written at a time.
byte[] desKey = ASCIIEncoding.ASCII.GetBytes(sKey);
byte[] desIV = Convert.FromBase64String(EncryptHelper.GetMD5(sKey)); //可以自定义
DES des = new DESCryptoServiceProvider();
CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);
//Read from the input file, then encrypt and write to the output file.
while (rdlen < totlen)
{
len = fin.Read(bin, 0, 100);
encStream.Write(bin, 0, len);
rdlen = rdlen + len;
}
encStream.Close();
fout.Close();
fin.Close();
}
/// <summary>
/// 加密文件
/// </summary>
/// <param name="inName">需加密文件路径</param>
/// <param name="outName">需加密后文件存放路径</param>
public static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV)
{
//Create the file streams to handle the input and output files.
FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
fout.SetLength(0);
//Create variables to help with read and write.
byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
long rdlen = 0; //This is the total number of bytes written.
long totlen = fin.Length; //This is the total length of the input file.
int len; //This is the number of bytes to be written at a time.
DES des = new DESCryptoServiceProvider();
CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);
Console.WriteLine("Encrypting...");
//Read from the input file, then encrypt and write to the output file.
while (rdlen < totlen)
{
len = fin.Read(bin, 0, 100);
encStream.Write(bin, 0, len);
rdlen = rdlen + len;
Console.WriteLine("{0} bytes processed", rdlen);
}
encStream.Close();
fout.Close();
fin.Close();
}
/// <summary>
/// 解密文件
/// </summary>
/// <param name="inName">需解密文件路径</param>
/// <param name="outName">需解密后文件存放路径</param>
public static void DecryptData(String inName, String outName, byte[] desKey, byte[] desIV)
{
//Create the file streams to handle the input and output files.
FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
fout.SetLength(0);
//Create variables to help with read and write.
byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
long rdlen = 0; //This is the total number of bytes written.
long totlen = fin.Length; //This is the total length of the input file.
int len; //This is the number of bytes to be written at a time.
DES des = new DESCryptoServiceProvider();
CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);
Console.WriteLine("Encrypting...");
//Read from the input file, then encrypt and write to the output file.
while (rdlen < totlen)
{
len = fin.Read(bin, 0, 100);
encStream.Write(bin, 0, len);
rdlen = rdlen + len;
Console.WriteLine("{0} bytes processed", rdlen);
}
encStream.Close();
fout.Close();
fin.Close();
}
#endregion
#region Base64加密及解密算法,对称加密
/// <summary>
/// Base64加密
/// </summary>
/// <param name="text">要加密的字符串</param>
/// <returns></returns>
public static string EncodeBase64(string text)
{
//如果字符串为空,则返回
if (string.IsNullOrEmpty(text))
{
return "";
}
try
{
char[] Base64Code = new char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T',
'U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n',
'o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7',
'8','9','+','/','='};
byte empty = (byte)0;
ArrayList byteMessage = new ArrayList(Encoding.Default.GetBytes(text));
StringBuilder outmessage;
int messageLen = byteMessage.Count;
int page = messageLen / 3;
int use = 0;
if ((use = messageLen % 3) > 0)
{
for (int i = 0; i < 3 - use; i++)
byteMessage.Add(empty);
page++;
}
outmessage = new System.Text.StringBuilder(page * 4);
for (int i = 0; i < page; i++)
{
byte[] instr = new byte[3];
instr[0] = (byte)byteMessage[i * 3];
instr[1] = (byte)byteMessage[i * 3 + 1];
instr[2] = (byte)byteMessage[i * 3 + 2];
int[] outstr = new int[4];
outstr[0] = instr[0] >> 2;
outstr[1] = ((instr[0] & 0x03) << 4) ^ (instr[1] >> 4);
if (!instr[1].Equals(empty))
outstr[2] = ((instr[1] & 0x0f) << 2) ^ (instr[2] >> 6);
else
outstr[2] = 64;
if (!instr[2].Equals(empty))
outstr[3] = (instr[2] & 0x3f);
else
outstr[3] = 64;
outmessage.Append(Base64Code[outstr[0]]);
outmessage.Append(Base64Code[outstr[1]]);
outmessage.Append(Base64Code[outstr[2]]);
outmessage.Append(Base64Code[outstr[3]]);
}
return outmessage.ToString();
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Base64解密
/// </summary>
/// <param name="text">要解密的字符串</param>
public static string DecodeBase64(string text)
{
//如果字符串为空,则返回
if (string.IsNullOrEmpty(text))
{
return "";
}
//将空格替换为加号
text = text.Replace(" ", "+");
try
{
if ((text.Length % 4) != 0)
{
return "包含不正确的BASE64编码";
}
if (!Regex.IsMatch(text, "^[A-Z0-9/+=]*$", RegexOptions.IgnoreCase))
{
return "包含不正确的BASE64编码";
}
string Base64Code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
int page = text.Length / 4;
ArrayList outMessage = new ArrayList(page * 3);
char[] message = text.ToCharArray();
for (int i = 0; i < page; i++)
{
byte[] instr = new byte[4];
instr[0] = (byte)Base64Code.IndexOf(message[i * 4]);
instr[1] = (byte)Base64Code.IndexOf(message[i * 4 + 1]);
instr[2] = (byte)Base64Code.IndexOf(message[i * 4 + 2]);
instr[3] = (byte)Base64Code.IndexOf(message[i * 4 + 3]);
byte[] outstr = new byte[3];
outstr[0] = (byte)((instr[0] << 2) ^ ((instr[1] & 0x30) >> 4));
if (instr[2] != 64)
{
outstr[1] = (byte)((instr[1] << 4) ^ ((instr[2] & 0x3c) >> 2));
}
else
{
outstr[2] = 0;
}
if (instr[3] != 64)
{
outstr[2] = (byte)((instr[2] << 6) ^ instr[3]);
}
else
{
outstr[2] = 0;
}
outMessage.Add(outstr[0]);
if (outstr[1] != 0)
outMessage.Add(outstr[1]);
if (outstr[2] != 0)
outMessage.Add(outstr[2]);
}
byte[] outbyte = (byte[])outMessage.ToArray(Type.GetType("System.Byte"));
return Encoding.Default.GetString(outbyte);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region RHA加密的算法,非对称加密
public static String getSha1(String str)
{
//建立SHA1对象
SHA1 sha = new SHA1CryptoServiceProvider();
//将mystr转换成byte[]
ASCIIEncoding enc = new ASCIIEncoding();
byte[] dataToHash = enc.GetBytes(str);
//Hash运算
byte[] dataHashed = sha.ComputeHash(dataToHash);
//将运算结果转换成string
string hash = BitConverter.ToString(dataHashed).Replace("-", "");
return hash;
}
public static String Sha1(String s)
{
char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try
{
byte[] btInput = System.Text.Encoding.Default.GetBytes(s);
SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
byte[] md = sha.ComputeHash(btInput);
// 把密文转换成十六进制的字符串形式
int j = md.Length;
char[] str = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++)
{
byte byte0 = md[i];
str[k++] = hexDigits[(int)(((byte)byte0) >> 4) & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new string(str);
}
catch (Exception e)
{
Console.Error.WriteLine(e.StackTrace);
return null;
}
}
#endregion
}显示效果:

可以使用不同的加密秘钥生成不同密码。
以上类库内容来源互联网,站长稍作整理
评论列表: