//在C#中 //图片到byte[]再到base64string的转换:
Bitmap bmp = new Bitmap(filepath);
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
byte[] arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(arr, 0, (int)ms.Length);
ms.Close();
string pic = Convert.ToBase64String(arr);
//base64string到byte[]再到图片的转换:
byte[] imageBytes = Convert.FromBase64String(pic);
//读入MemoryStream对象
MemoryStream memoryStream = new MemoryStream(imageBytes, 0, imageBytes.Length);
memoryStream.Write(imageBytes, 0, imageBytes.Length);
//转成图片
Image image = Image.FromStream(memoryStream);
//现在的数据库开发中:图片的存放方式一般有CLOB:存放base64string BLOB:存放byte[] // 一般推荐使用byte[]。因为图片可以直接转换为byte[]存放到数据库中若使用base64string 还需要从byte[]转换成base64string 。更浪费性能。
des加密采用CBC和PKCS7
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace des
{
class Program
{
static void Main(string[] args)
{
string ss = EncryptDES("1123", "12345678");
string aa = DecryptDES(ss, "12345678");
}
//默认密钥向量
private static string iv = "1234567812345678";
/// <summary>
/// DES加密字符串
/// </summary>
/// <param name="encryptString">待加密的字符串</param>
/// <param name="encryptKey">加密密钥,要求为8位</param>
/// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
public static string EncryptDES(string encryptString, string encryptKey)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
byte[] rgbIV = Encoding.UTF8.GetBytes(iv);
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
dCSP.Mode = CipherMode.CBC;
dCSP.Padding = PaddingMode.PKCS7;
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());
}
catch
{
return encryptString;
}
}
/// <summary>
/// DES解密字符串
/// </summary>
/// <param name="decryptString">待解密的字符串</param>
/// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
/// <returns>解密成功返回解密后的字符串,失败返源串</returns>
public static string DecryptDES(string decryptString, string decryptKey)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8));
byte[] rgbIV = Encoding.UTF8.GetBytes(iv);
byte[] inputByteArray = Convert.FromBase64String(decryptString);
DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
dCSP.Mode = CipherMode.CBC;
dCSP.Padding = PaddingMode.PKCS7;
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray());
}
catch
{
return decryptString;
}
}
}
}
各种加密解密方法
using System;using System.Security.Cryptography;using System.IO;using System.Text;using System.Globalization;using System.Xml.Linq;using System.Collections.Generic;namespace EncriptSample{ /// <summary> /// 加密、解密 /// </summary> class Encrypter { //DES默认密钥向量 private static byte[] DES_IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; //AES默认密钥向量 public static readonly byte[] AES_IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; #region MD5 /// <summary> /// MD5加密为32字符长度的16进制字符串 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string EncryptByMD5(string input) { MD5 md5Hasher = MD5.Create(); byte[] data = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(input)); StringBuilder sBuilder = new StringBuilder(); //将每个字节转为16进制 for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } return sBuilder.ToString(); } #endregion #region SHA1 /// <summary> /// SHA1加密 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string EncryptBySHA1(string input) { SHA1 sha = new SHA1CryptoServiceProvider(); byte[] bytes = Encoding.Unicode.GetBytes(input); byte[] result = sha.ComputeHash(bytes); return BitConverter.ToString(result); } #endregion #region DES /// <summary> /// 加密方法 /// </summary> /// <param name="input"></param> /// <param name="key"></param> /// <returns></returns> public static string EncryptByDES(string input, string key) { byte[] inputBytes = Encoding.UTF8.GetBytes(input); //Encoding.UTF8.GetBytes(input); byte[] keyBytes = ASCIIEncoding.UTF8.GetBytes(key); byte[] encryptBytes = EncryptByDES(inputBytes, keyBytes, keyBytes); //string result = Encoding.UTF8.GetString(encryptBytes); //无法解码,其加密结果中文出现乱码:d\"�e����(��uπ�W��-��,_�\nJn7 //原因:如果明文为中文,UTF8编码两个字节标识一个中文字符,但是加密后,两个字节密文,不一定还是中文字符。 using (DES des = new DESCryptoServiceProvider()) { using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { using (StreamWriter writer = new StreamWriter(cs)) { writer.Write(inputBytes); } } } } string result = Convert.ToBase64String(encryptBytes); return result; } /// <summary> /// DES加密 /// </summary> /// <param name="inputBytes">输入byte数组</param> /// <param name="key">密钥,只能是英文字母或数字</param> /// <param name="IV">偏移向量</param> /// <returns></returns> public static byte[] EncryptByDES(byte[] inputBytes, byte[] key, byte[] IV) { DES des = new DESCryptoServiceProvider(); //建立加密对象的密钥和偏移量 des.Key = key; des.IV = IV; string result = string.Empty; //1、如果通过CryptoStreamMode.Write方式进行加密,然后CryptoStreamMode.Read方式进行解密,解密成功。 using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(inputBytes, 0, inputBytes.Length); } return ms.ToArray(); } //2、如果通过CryptoStreamMode.Write方式进行加密,然后再用CryptoStreamMode.Write方式进行解密,可以得到正确结果 //3、如果通过CryptoStreamMode.Read方式进行加密,然后再用CryptoStreamMode.Read方式进行解密,无法解密,Error:要解密的数据的长度无效。 //4、如果通过CryptoStreamMode.Read方式进行加密,然后再用CryptoStreamMode.Write方式进行解密,无法解密,Error:要解密的数据的长度无效。 //using (MemoryStream ms = new MemoryStream(inputBytes)) //{ // using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Read)) // { // using (StreamReader reader = new StreamReader(cs)) // { // result = reader.ReadToEnd(); // return Encoding.UTF8.GetBytes(result); // } // } //} } /// <summary> /// 解密 /// </summary> /// <param name="input"></param> /// <param name="key"></param> /// <returns></returns> public static string DecryptByDES(string input, string key) { //UTF8无法解密,Error: 要解密的数据的长度无效。 //byte[] inputBytes = Encoding.UTF8.GetBytes(input);//UTF8乱码,见加密算法 byte[] inputBytes = Convert.FromBase64String(input); byte[] keyBytes = ASCIIEncoding.UTF8.GetBytes(key); byte[] resultBytes = DecryptByDES(inputBytes, keyBytes, keyBytes); string result = Encoding.UTF8.GetString(resultBytes); return result; } /// <summary> /// 解密方法 /// </summary> /// <param name="inputBytes"></param> /// <param name="key"></param> /// <param name="iv"></param> /// <returns></returns> public static byte[] DecryptByDES(byte[] inputBytes, byte[] key, byte[] iv) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); //建立加密对象的密钥和偏移量,此值重要,不能修改 des.Key = key; des.IV = iv; //通过write方式解密 //using (MemoryStream ms = new MemoryStream()) //{ // using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) // { // cs.Write(inputBytes, 0, inputBytes.Length); // } // return ms.ToArray(); //} //通过read方式解密 using (MemoryStream ms = new MemoryStream(inputBytes)) { using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read)) { using (StreamReader reader = new StreamReader(cs)) { string result = reader.ReadToEnd(); return Encoding.UTF8.GetBytes(result); } } } //错误写法,注意哪个是输出流的位置,如果范围ms,与原文不一致。 //using (MemoryStream ms = new MemoryStream(inputBytes)) //{ // using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read)) // { // cs.Read(inputBytes, 0, inputBytes.Length); // } // return ms.ToArray(); //} } /// <summary> /// 加密字符串 /// </summary> /// <param name="input"></param> /// <param name="sKey"></param> /// <returns></returns> public static string EncryptString(string input, string sKey) { byte[] data = Encoding.UTF8.GetBytes(input); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); ICryptoTransform desencrypt = des.CreateEncryptor(); byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length); return BitConverter.ToString(result); } } /// <summary> /// 解密字符串 /// </summary> /// <param name="input"></param> /// <param name="sKey"></param> /// <returns></returns> public static string DecryptString(string input, string sKey) { string[] sInput = input.Split("-".ToCharArray()); byte[] data = new byte[sInput.Length]; for (int i = 0; i < sInput.Length; i++) { data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber); } using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); ICryptoTransform desencrypt = des.CreateDecryptor(); byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length); return Encoding.UTF8.GetString(result); } } #endregion #region AES /// <summary> /// AES加密算法 /// </summary> /// <param name="input">明文字符串</param> /// <param name="key">密钥</param> /// <returns>字符串</returns> public static string EncryptByAES(string input, string key) { byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 32)); using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider()) { aesAlg.Key = keyBytes; aesAlg.IV = AES_IV; ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(input); } byte[] bytes = msEncrypt.ToArray(); //return Convert.ToBase64String(bytes);//此方法不可用 return BitConverter.ToString(bytes); } } } } /// <summary> /// AES解密 /// </summary> /// <param name="input">密文字节数组</param> /// <param name="key">密钥</param> /// <returns>返回解密后的字符串</returns> public static string DecryptByAES(string input, string key) { //byte[] inputBytes = Convert.FromBase64String(input); //Encoding.UTF8.GetBytes(input); string[] sInput = input.Split("-".ToCharArray()); byte[] inputBytes = new byte[sInput.Length]; for (int i = 0; i < sInput.Length; i++) { inputBytes[i] = byte.Parse(sInput[i], NumberStyles.HexNumber); } byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 32)); using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider()) { aesAlg.Key = keyBytes; aesAlg.IV = AES_IV; ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msEncrypt = new MemoryStream(inputBytes)) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srEncrypt = new StreamReader(csEncrypt)) { return srEncrypt.ReadToEnd(); } } } } } /// <summary> /// AES加密 /// </summary> /// <param name="inputdata">输入的数据</param> /// <param name="iv">向量128位</param> /// <param name="strKey">加密密钥</param> /// <returns></returns> public static byte[] EncryptByAES(byte[] inputdata, byte[] key, byte[] iv) { 分组加密算法 //Aes aes = new AesCryptoServiceProvider(); 设置密钥及密钥向量 //aes.Key = key; //aes.IV = iv; //using (MemoryStream ms = new MemoryStream()) //{ // using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write)) // { // using (StreamWriter writer = new StreamWriter(cs)) // { // writer.Write(inputdata); // } // return ms.ToArray(); // } //} using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider()) { aesAlg.Key = key; aesAlg.IV = iv; ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(inputdata); } byte[] encrypted = msEncrypt.ToArray(); return encrypted; } } } } /// <summary> /// AES解密 /// </summary> /// <param name="inputdata">输入的数据</param> /// <param name="key">key</param> /// <param name="iv">向量128</param> /// <returns></returns> public static byte[] DecryptByAES(byte[] inputBytes, byte[] key, byte[] iv) { Aes aes = new AesCryptoServiceProvider(); aes.Key = key; aes.IV = iv; byte[] decryptBytes; using (MemoryStream ms = new MemoryStream(inputBytes)) { using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read)) { using (StreamReader reader = new StreamReader(cs)) { string result = reader.ReadToEnd(); decryptBytes = Encoding.UTF8.GetBytes(result); } } } return decryptBytes; } #endregion #region DSA #endregion #region RSA /// <summary> /// RSA加密 /// </summary> /// <param name="plaintext">明文</param> /// <param name="publicKey">公钥</param> /// <returns>密文字符串</returns> public static string EncryptByRSA(string plaintext, string publicKey) { UnicodeEncoding ByteConverter = new UnicodeEncoding(); byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext); using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { RSA.FromXmlString(publicKey); byte[] encryptedData = RSA.Encrypt(dataToEncrypt, false); return Convert.ToBase64String(encryptedData); } } /// <summary> /// RSA解密 /// </summary> /// <param name="ciphertext">密文</param> /// <param name="privateKey">私钥</param> /// <returns>明文字符串</returns> public static string DecryptByRSA(string ciphertext, string privateKey) { UnicodeEncoding byteConverter = new UnicodeEncoding(); using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { RSA.FromXmlString(privateKey); byte[] encryptedData = Convert.FromBase64String(ciphertext); byte[] decryptedData = RSA.Decrypt(encryptedData, false); return byteConverter.GetString(decryptedData); } } //public static string signByRSA(string plaintext, string privateKey) //{ // UnicodeEncoding ByteConverter = new UnicodeEncoding(); // byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext); // using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) // { // RSA.FromXmlString(privateKey); // byte[] encryptedData = RSA.SignData(dataToEncrypt,); // return Convert.ToBase64String(encryptedData); // } //} /// <summary> /// 数字签名 /// </summary> /// <param name="plaintext">原文</param> /// <param name="privateKey">私钥</param> /// <returns>签名</returns> public static string HashAndSignString(string plaintext, string privateKey) { UnicodeEncoding ByteConverter = new UnicodeEncoding(); byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext); using (RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider()) { RSAalg.FromXmlString(privateKey); //使用SHA1进行摘要算法,生成签名 byte[] encryptedData = RSAalg.SignData(dataToEncrypt, new SHA1CryptoServiceProvider()); return Convert.ToBase64String(encryptedData); } } /// <summary> /// 验证签名 /// </summary> /// <param name="plaintext">原文</param> /// <param name="SignedData">签名</param> /// <param name="publicKey">公钥</param> /// <returns></returns> public static bool VerifySigned(string plaintext, string SignedData, string publicKey) { using (RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider()) { RSAalg.FromXmlString(publicKey); UnicodeEncoding ByteConverter = new UnicodeEncoding(); byte[] dataToVerifyBytes = ByteConverter.GetBytes(plaintext); byte[] signedDataBytes = Convert.FromBase64String(SignedData); return RSAalg.VerifyData(dataToVerifyBytes, new SHA1CryptoServiceProvider(), signedDataBytes); } } /// <summary> /// 获取Key /// 键为公钥,值为私钥 /// </summary> /// <returns></returns> public static KeyValuePair<string, string> CreateRSAKey() { RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); string privateKey = RSA.ToXmlString(true); string publicKey = RSA.ToXmlString(false); return new KeyValuePair<string, string>(publicKey, privateKey); } #endregion #region other /// <summary> /// /// </summary> /// <param name="input"></param> /// <returns></returns> public static byte[] GetBytes(string input) { string[] sInput = input.Split("-".ToCharArray()); byte[] inputBytes = new byte[sInput.Length]; for (int i = 0; i < sInput.Length; i++) { inputBytes[i] = byte.Parse(sInput[i], NumberStyles.HexNumber); } return inputBytes; } #endregion }}MD5算法
对md5算法是以512位分组来处理输入信息的,并且每一分组又被划分为13个32位的子分组,经过处理,算出四个32位分组,将这四个32位分组级联后生产一个128位散列值。
1.填充:如果输入信息的长度(BIT)对512求余的结果不等于448,就需要填充使对512求余的结果等于448.填充的方法是填充一个1和n个0.填充完毕后,信息的长度就为N*512+448(bit);
2. 记录信息长度:用64位来存储填充前信息长度。这64位加在第一步结果的后面,这样信息长度就变为N*512+448+64=(N+1)*512位。
3.装入标准的幻数(四个整数):标准的幻数(物理顺序)是(A=(01234567)16,B=(89ABCDEF)16,C=(FEDCBA98)16,D=(76543210)16)。如果在程序中定义应该是(A=0X67452301L,B=0XEFCDAB89L,C=0X98BADCFEL,D=0X10325476L)。有点晕哈,其实想一想就明白了。
4四轮循环运算:循环的次数是分组的个数(N+1)
1)将每一512字节细分成16个小组,每个小组64位(8个字节)
2)先认识四个线性函数(&是与,|是或,~是非,^是异或)
F(X,Y,Z)=(X&Y)|((~X)&Z)
G(X,Y,Z)=(X&Z)|(Y&(~Z))
H(X,Y,Z)=X^Y^Z
I(X,Y,Z)=Y^(X|(~Z))
3)设Mj表示消息的第j个子分组(从0到15),<<<s表示循环左移s位,则四种操作为:
FF(a,b,c,d,Mj,s,ti)表示a=b+((a+F(b,c,d)+Mj+ti)<<<s)
GG(a,b,c,d,Mj,s,ti)表示a=b+((a+G(b,c,d)+Mj+ti)<<<s)
HH(a,b,c,d,Mj,s,ti)表示a=b+((a+H(b,c,d)+Mj+ti)<<<s)
II(a,b,c,d,Mj,s,ti)表示a=b+((a+I(b,c,d)+Mj+ti)<<<s)
4)四轮运算
第一轮
a=FF(a,b,c,d,M0,7,0xd76aa478)
b=FF(d,a,b,c,M1,12,0xe8c7b756)
c=FF(c,d,a,b,M2,17,0x242070db)
d=FF(b,c,d,a,M3,22,0xc1bdceee)
a=FF(a,b,c,d,M4,7,0xf57c0faf)
b=FF(d,a,b,c,M5,12,0x4787c62a)
c=FF(c,d,a,b,M6,17,0xa8304613)
d=FF(b,c,d,a,M7,22,0xfd469501)
a=FF(a,b,c,d,M8,7,0x698098d8)
b=FF(d,a,b,c,M9,12,0x8b44f7af)
c=FF(c,d,a,b,M10,17,0xffff5bb1)
d=FF(b,c,d,a,M11,22,0x895cd7be)
a=FF(a,b,c,d,M12,7,0x6b901122)
b=FF(d,a,b,c,M13,12,0xfd987193)
c=FF(c,d,a,b,M14,17,0xa679438e)
d=FF(b,c,d,a,M15,22,0x49b40821)
第二轮
a=GG(a,b,c,d,M1,5,0xf61e2562)
b=GG(d,a,b,c,M6,9,0xc040b340)
c=GG(c,d,a,b,M11,14,0x265e5a51)
d=GG(b,c,d,a,M0,20,0xe9b6c7aa)
a=GG(a,b,c,d,M5,5,0xd62f105d)
b=GG(d,a,b,c,M10,9,0x02441453)
c=GG(c,d,a,b,M15,14,0xd8a1e681)
d=GG(b,c,d,a,M4,20,0xe7d3fbc8)
a=GG(a,b,c,d,M9,5,0x21e1cde6)
b=GG(d,a,b,c,M14,9,0xc33707d6)
c=GG(c,d,a,b,M3,14,0xf4d50d87)
d=GG(b,c,d,a,M8,20,0x455a14ed)
a=GG(a,b,c,d,M13,5,0xa9e3e905)
b=GG(d,a,b,c,M2,9,0xfcefa3f8)
c=GG(c,d,a,b,M7,14,0x676f02d9)
d=GG(b,c,d,a,M12,20,0x8d2a4c8a)
第三轮
a=HH(a,b,c,d,M5,4,0xfffa3942)
b=HH(d,a,b,c,M8,11,0x8771f681)
c=HH(c,d,a,b,M11,16,0x6d9d6122)
d=HH(b,c,d,a,M14,23,0xfde5380c)
a=HH(a,b,c,d,M1,4,0xa4beea44)
b=HH(d,a,b,c,M4,11,0x4bdecfa9)
c=HH(c,d,a,b,M7,16,0xf6bb4b60)
d=HH(b,c,d,a,M10,23,0xbebfbc70)
a=HH(a,b,c,d,M13,4,0x289b7ec6)
b=HH(d,a,b,c,M0,11,0xeaa127fa)
c=HH(c,d,a,b,M3,16,0xd4ef3085)
d=HH(b,c,d,a,M6,23,0x04881d05)
a=HH(a,b,c,d,M9,4,0xd9d4d039)
b=HH(d,a,b,c,M12,11,0xe6db99e5)
c=HH(c,d,a,b,M15,16,0x1fa27cf8)
d=HH(b,c,d,a,M2,23,0xc4ac5665)
第四轮
a=II(a,b,c,d,M0,6,0xf4292244)
b=II(d,a,b,c,M7,10,0x432aff97)
c=II(c,d,a,b,M14,15,0xab9423a7)
d=II(b,c,d,a,M5,21,0xfc93a039)
a=II(a,b,c,d,M12,6,0x655b59c3)
b=II(d,a,b,c,M3,10,0x8f0ccc92)
c=II(c,d,a,b,M10,15,0xffeff47d)
d=II(b,c,d,a,M1,21,0x85845dd1)
a=II(a,b,c,d,M8,6,0x6fa87e4f)
b=II(d,a,b,c,M15,10,0xfe2ce6e0)
c=II(c,d,a,b,M6,15,0xa3014314)
d=II(b,c,d,a,M13,21,0x4e0811a1)
a=II(a,b,c,d,M4,6,0xf7537e82)
b=II(d,a,b,c,M11,10,0xbd3af235)
c=II(c,d,a,b,M2,15,0x2ad7d2bb)
d=II(b,c,d,a,M9,21,0xeb86d391)
5)每轮循环后,将A,B,C,D分别加上a,b,c,d,然后进入下一循环。
package woxingwosu;
public class MD5 {
static final String hexs[]={"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
//标准的幻数
private static final long A=0x67452301L;
private static final long B=0xefcdab89L;
private static final long C=0x98badcfeL;
private static final long D=0x10325476L;
//下面这些S11-S44实际上是一个4*4的矩阵,在四轮循环运算中用到
static final int S11 = 7;
static final int S12 = 12;
static final int S13 = 17;
static final int S14 = 22;
static final int S21 = 5;
static final int S22 = 9;
static final int S23 = 14;
static final int S24 = 20;
static final int S31 = 4;
static final int S32 = 11;
static final int S33 = 16;
static final int S34 = 23;
static final int S41 = 6;
static final int S42 = 10;
static final int S43 = 15;
static final int S44 = 21;
//java不支持无符号的基本数据(unsigned)
private long [] result={A,B,C,D};//存储hash结果,共4×32=128位,初始化值为(幻数的级联)
public static void main(String []args){
MD5 md=new MD5();
System.out.println("md5(abc)="+md.digest("abc"));
}
private String digest(String inputStr){
byte [] inputBytes=inputStr.getBytes();
int byteLen=inputBytes.length;//长度(字节)
int groupCount=0;//完整分组的个数
groupCount=byteLen/64;//每组512位(64字节)
long []groups=null;//每个小组(64字节)再细分后的16个小组(4字节)
//处理每一个完整 分组
for(int step=0;step<groupCount;step++){
groups=divGroup(inputBytes,step*64);
trans(groups);//处理分组,核心算法
}
//处理完整分组后的尾巴
int rest=byteLen%64;//512位分组后的余数
byte [] tempBytes=new byte[64];
if(rest<=56){
for(int i=0;i<rest;i++)
tempBytes[i]=inputBytes[byteLen-rest+i];
if(rest<56){
tempBytes[rest]=(byte)(1<<7);
for(int i=1;i<56-rest;i++)
tempBytes[rest+i]=0;
}
long len=(long)(byteLen<<3);
for(int i=0;i<8;i++){
tempBytes[56+i]=(byte)(len&0xFFL);
len=len>>8;
}
groups=divGroup(tempBytes,0);
trans(groups);//处理分组
}else{
for(int i=0;i<rest;i++)
tempBytes[i]=inputBytes[byteLen-rest+i];
tempBytes[rest]=(byte)(1<<7);
for(int i=rest+1;i<64;i++)
tempBytes[i]=0;
groups=divGroup(tempBytes,0);
trans(groups);//处理分组
for(int i=0;i<56;i++)
tempBytes[i]=0;
long len=(long)(byteLen<<3);
for(int i=0;i<8;i++){
tempBytes[56+i]=(byte)(len&0xFFL);
len=len>>8;
}
groups=divGroup(tempBytes,0);
trans(groups);//处理分组
}
//将Hash值转换成十六进制的字符串
String resStr="";
long temp=0;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
temp=result[i]&0x0FL;
String a=hexs[(int)(temp)];
result[i]=result[i]>>4;
temp=result[i]&0x0FL;
resStr+=hexs[(int)(temp)]+a;
result[i]=result[i]>>4;
}
}
return resStr;
}
/**
* 从inputBytes的index开始取512位,作为新的分组
* 将每一个512位的分组再细分成16个小组,每个小组64位(8个字节)
* @param inputBytes
* @param index
* @return
*/
private static long[] divGroup(byte[] inputBytes,int index){
long [] temp=new long[16];
for(int i=0;i<16;i++){
temp[i]=b2iu(inputBytes[4*i+index])|
(b2iu(inputBytes[4*i+1+index]))<<8|
(b2iu(inputBytes[4*i+2+index]))<<16|
(b2iu(inputBytes[4*i+3+index]))<<24;
}
return temp;
}
/**
* 这时不存在符号位(符号位存储不再是代表正负),所以需要处理一下
* @param b
* @return
*/
public static long b2iu(byte b){
return b < 0 ? b & 0x7F + 128 : b;
}
/**
* 主要的操作,四轮循环
* @param groups[]--每一个分组512位(64字节)
*/
private void trans(long[] groups) {
long a = result[0], b = result[1], c = result[2], d = result[3];
/*第一轮*/
a = FF(a, b, c, d, groups[0], S11, 0xd76aa478L); /* 1 */
d = FF(d, a, b, c, groups[1], S12, 0xe8c7b756L); /* 2 */
c = FF(c, d, a, b, groups[2], S13, 0x242070dbL); /* 3 */
b = FF(b, c, d, a, groups[3], S14, 0xc1bdceeeL); /* 4 */
a = FF(a, b, c, d, groups[4], S11, 0xf57c0fafL); /* 5 */
d = FF(d, a, b, c, groups[5], S12, 0x4787c62aL); /* 6 */
c = FF(c, d, a, b, groups[6], S13, 0xa8304613L); /* 7 */
b = FF(b, c, d, a, groups[7], S14, 0xfd469501L); /* 8 */
a = FF(a, b, c, d, groups[8], S11, 0x698098d8L); /* 9 */
d = FF(d, a, b, c, groups[9], S12, 0x8b44f7afL); /* 10 */
c = FF(c, d, a, b, groups[10], S13, 0xffff5bb1L); /* 11 */
b = FF(b, c, d, a, groups[11], S14, 0x895cd7beL); /* 12 */
a = FF(a, b, c, d, groups[12], S11, 0x6b901122L); /* 13 */
d = FF(d, a, b, c, groups[13], S12, 0xfd987193L); /* 14 */
c = FF(c, d, a, b, groups[14], S13, 0xa679438eL); /* 15 */
b = FF(b, c, d, a, groups[15], S14, 0x49b40821L); /* 16 */
/*第二轮*/
a = GG(a, b, c, d, groups[1], S21, 0xf61e2562L); /* 17 */
d = GG(d, a, b, c, groups[6], S22, 0xc040b340L); /* 18 */
c = GG(c, d, a, b, groups[11], S23, 0x265e5a51L); /* 19 */
b = GG(b, c, d, a, groups[0], S24, 0xe9b6c7aaL); /* 20 */
a = GG(a, b, c, d, groups[5], S21, 0xd62f105dL); /* 21 */
d = GG(d, a, b, c, groups[10], S22, 0x2441453L); /* 22 */
c = GG(c, d, a, b, groups[15], S23, 0xd8a1e681L); /* 23 */
b = GG(b, c, d, a, groups[4], S24, 0xe7d3fbc8L); /* 24 */
a = GG(a, b, c, d, groups[9], S21, 0x21e1cde6L); /* 25 */
d = GG(d, a, b, c, groups[14], S22, 0xc33707d6L); /* 26 */
c = GG(c, d, a, b, groups[3], S23, 0xf4d50d87L); /* 27 */
b = GG(b, c, d, a, groups[8], S24, 0x455a14edL); /* 28 */
a = GG(a, b, c, d, groups[13], S21, 0xa9e3e905L); /* 29 */
d = GG(d, a, b, c, groups[2], S22, 0xfcefa3f8L); /* 30 */
c = GG(c, d, a, b, groups[7], S23, 0x676f02d9L); /* 31 */
b = GG(b, c, d, a, groups[12], S24, 0x8d2a4c8aL); /* 32 */
/*第三轮*/
a = HH(a, b, c, d, groups[5], S31, 0xfffa3942L); /* 33 */
d = HH(d, a, b, c, groups[8], S32, 0x8771f681L); /* 34 */
c = HH(c, d, a, b, groups[11], S33, 0x6d9d6122L); /* 35 */
b = HH(b, c, d, a, groups[14], S34, 0xfde5380cL); /* 36 */
a = HH(a, b, c, d, groups[1], S31, 0xa4beea44L); /* 37 */
d = HH(d, a, b, c, groups[4], S32, 0x4bdecfa9L); /* 38 */
c = HH(c, d, a, b, groups[7], S33, 0xf6bb4b60L); /* 39 */
b = HH(b, c, d, a, groups[10], S34, 0xbebfbc70L); /* 40 */
a = HH(a, b, c, d, groups[13], S31, 0x289b7ec6L); /* 41 */
d = HH(d, a, b, c, groups[0], S32, 0xeaa127faL); /* 42 */
c = HH(c, d, a, b, groups[3], S33, 0xd4ef3085L); /* 43 */
b = HH(b, c, d, a, groups[6], S34, 0x4881d05L); /* 44 */
a = HH(a, b, c, d, groups[9], S31, 0xd9d4d039L); /* 45 */
d = HH(d, a, b, c, groups[12], S32, 0xe6db99e5L); /* 46 */
c = HH(c, d, a, b, groups[15], S33, 0x1fa27cf8L); /* 47 */
b = HH(b, c, d, a, groups[2], S34, 0xc4ac5665L); /* 48 */
/*第四轮*/
a = II(a, b, c, d, groups[0], S41, 0xf4292244L); /* 49 */
d = II(d, a, b, c, groups[7], S42, 0x432aff97L); /* 50 */
c = II(c, d, a, b, groups[14], S43, 0xab9423a7L); /* 51 */
b = II(b, c, d, a, groups[5], S44, 0xfc93a039L); /* 52 */
a = II(a, b, c, d, groups[12], S41, 0x655b59c3L); /* 53 */
d = II(d, a, b, c, groups[3], S42, 0x8f0ccc92L); /* 54 */
c = II(c, d, a, b, groups[10], S43, 0xffeff47dL); /* 55 */
b = II(b, c, d, a, groups[1], S44, 0x85845dd1L); /* 56 */
a = II(a, b, c, d, groups[8], S41, 0x6fa87e4fL); /* 57 */
d = II(d, a, b, c, groups[15], S42, 0xfe2ce6e0L); /* 58 */
c = II(c, d, a, b, groups[6], S43, 0xa3014314L); /* 59 */
b = II(b, c, d, a, groups[13], S44, 0x4e0811a1L); /* 60 */
a = II(a, b, c, d, groups[4], S41, 0xf7537e82L); /* 61 */
d = II(d, a, b, c, groups[11], S42, 0xbd3af235L); /* 62 */
c = II(c, d, a, b, groups[2], S43, 0x2ad7d2bbL); /* 63 */
b = II(b, c, d, a, groups[9], S44, 0xeb86d391L); /* 64 */
/*加入到之前计算的结果当中*/
result[0] += a;
result[1] += b;
result[2] += c;
result[3] += d;
result[0]=result[0]&0xFFFFFFFFL;
result[1]=result[1]&0xFFFFFFFFL;
result[2]=result[2]&0xFFFFFFFFL;
result[3]=result[3]&0xFFFFFFFFL;
}
/**
* 下面是处理要用到的线性函数
*/
private static long F(long x, long y, long z) {
return (x & y) | ((~x) & z);
}
private static long G(long x, long y, long z) {
return (x & z) | (y & (~z));
}
private static long H(long x, long y, long z) {
return x ^ y ^ z;
}
private static long I(long x, long y, long z) {
return y ^ (x | (~z));
}
private static long FF(long a, long b, long c, long d, long x, long s,
long ac) {
a += (F(b, c, d)&0xFFFFFFFFL) + x + ac;
a = ((a&0xFFFFFFFFL)<< s) | ((a&0xFFFFFFFFL) >>> (32 - s));
a += b;
return (a&0xFFFFFFFFL);
}
private static long GG(long a, long b, long c, long d, long x, long s,
long ac) {
a += (G(b, c, d)&0xFFFFFFFFL) + x + ac;
a = ((a&0xFFFFFFFFL) << s) | ((a&0xFFFFFFFFL) >>> (32 - s));
a += b;
return (a&0xFFFFFFFFL);
}
private static long HH(long a, long b, long c, long d, long x, long s,
long ac) {
a += (H(b, c, d)&0xFFFFFFFFL) + x + ac;
a = ((a&0xFFFFFFFFL) << s) | ((a&0xFFFFFFFFL) >>> (32 - s));
a += b;
return (a&0xFFFFFFFFL);
}
private static long II(long a, long b, long c, long d, long x, long s,
long ac) {
a += (I(b, c, d)&0xFFFFFFFFL) + x + ac;
a = ((a&0xFFFFFFFFL) << s) | ((a&0xFFFFFFFFL) >>> (32 - s));
a += b;
return (a&0xFFFFFFFFL);
}
}
using System;
using System.Security.Cryptography;using System.IO;using System.Text;using System.Globalization;using System.Xml.Linq;using System.Collections.Generic;namespace EncriptSample{ /// <summary> /// 加密、解密 /// </summary> class Encrypter { //DES默认密钥向量 private static byte[] DES_IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; //AES默认密钥向量 public static readonly byte[] AES_IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; #region MD5 /// <summary> /// MD5加密为32字符长度的16进制字符串 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string EncryptByMD5(string input) { MD5 md5Hasher = MD5.Create(); byte[] data = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(input)); StringBuilder sBuilder = new StringBuilder(); //将每个字节转为16进制 for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } return sBuilder.ToString(); } #endregion #region SHA1 /// <summary> /// SHA1加密 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string EncryptBySHA1(string input) { SHA1 sha = new SHA1CryptoServiceProvider(); byte[] bytes = Encoding.Unicode.GetBytes(input); byte[] result = sha.ComputeHash(bytes); return BitConverter.ToString(result); } #endregion #region DES /// <summary> /// 加密方法 /// </summary> /// <param name="input"></param> /// <param name="key"></param> /// <returns></returns> public static string EncryptByDES(string input, string key) { byte[] inputBytes = Encoding.UTF8.GetBytes(input); //Encoding.UTF8.GetBytes(input); byte[] keyBytes = ASCIIEncoding.UTF8.GetBytes(key); byte[] encryptBytes = EncryptByDES(inputBytes, keyBytes, keyBytes); //string result = Encoding.UTF8.GetString(encryptBytes); //无法解码,其加密结果中文出现乱码:d\"�e����(��uπ�W��-��,_�\nJn7 //原因:如果明文为中文,UTF8编码两个字节标识一个中文字符,但是加密后,两个字节密文,不一定还是中文字符。 using (DES des = new DESCryptoServiceProvider()) { using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { using (StreamWriter writer = new StreamWriter(cs)) { writer.Write(inputBytes); } } } } string result = Convert.ToBase64String(encryptBytes); return result; } /// <summary> /// DES加密 /// </summary> /// <param name="inputBytes">输入byte数组</param> /// <param name="key">密钥,只能是英文字母或数字</param> /// <param name="IV">偏移向量</param> /// <returns></returns> public static byte[] EncryptByDES(byte[] inputBytes, byte[] key, byte[] IV) { DES des = new DESCryptoServiceProvider(); //建立加密对象的密钥和偏移量 des.Key = key; des.IV = IV; string result = string.Empty; //1、如果通过CryptoStreamMode.Write方式进行加密,然后CryptoStreamMode.Read方式进行解密,解密成功。 using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(inputBytes, 0, inputBytes.Length); } return ms.ToArray(); } //2、如果通过CryptoStreamMode.Write方式进行加密,然后再用CryptoStreamMode.Write方式进行解密,可以得到正确结果 //3、如果通过CryptoStreamMode.Read方式进行加密,然后再用CryptoStreamMode.Read方式进行解密,无法解密,Error:要解密的数据的长度无效。 //4、如果通过CryptoStreamMode.Read方式进行加密,然后再用CryptoStreamMode.Write方式进行解密,无法解密,Error:要解密的数据的长度无效。 //using (MemoryStream ms = new MemoryStream(inputBytes)) //{ // using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Read)) // { // using (StreamReader reader = new StreamReader(cs)) // { // result = reader.ReadToEnd(); // return Encoding.UTF8.GetBytes(result); // } // } //} } /// <summary> /// 解密 /// </summary> /// <param name="input"></param> /// <param name="key"></param> /// <returns></returns> public static string DecryptByDES(string input, string key) { //UTF8无法解密,Error: 要解密的数据的长度无效。 //byte[] inputBytes = Encoding.UTF8.GetBytes(input);//UTF8乱码,见加密算法 byte[] inputBytes = Convert.FromBase64String(input); byte[] keyBytes = ASCIIEncoding.UTF8.GetBytes(key); byte[] resultBytes = DecryptByDES(inputBytes, keyBytes, keyBytes); string result = Encoding.UTF8.GetString(resultBytes); return result; } /// <summary> /// 解密方法 /// </summary> /// <param name="inputBytes"></param> /// <param name="key"></param> /// <param name="iv"></param> /// <returns></returns> public static byte[] DecryptByDES(byte[] inputBytes, byte[] key, byte[] iv) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); //建立加密对象的密钥和偏移量,此值重要,不能修改 des.Key = key; des.IV = iv; //通过write方式解密 //using (MemoryStream ms = new MemoryStream()) //{ // using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) // { // cs.Write(inputBytes, 0, inputBytes.Length); // } // return ms.ToArray(); //} //通过read方式解密 using (MemoryStream ms = new MemoryStream(inputBytes)) { using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read)) { using (StreamReader reader = new StreamReader(cs)) { string result = reader.ReadToEnd(); return Encoding.UTF8.GetBytes(result); } } } //错误写法,注意哪个是输出流的位置,如果范围ms,与原文不一致。 //using (MemoryStream ms = new MemoryStream(inputBytes)) //{ // using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read)) // { // cs.Read(inputBytes, 0, inputBytes.Length); // } // return ms.ToArray(); //} } /// <summary> /// 加密字符串 /// </summary> /// <param name="input"></param> /// <param name="sKey"></param> /// <returns></returns> public static string EncryptString(string input, string sKey) { byte[] data = Encoding.UTF8.GetBytes(input); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); ICryptoTransform desencrypt = des.CreateEncryptor(); byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length); return BitConverter.ToString(result); } } /// <summary> /// 解密字符串 /// </summary> /// <param name="input"></param> /// <param name="sKey"></param> /// <returns></returns> public static string DecryptString(string input, string sKey) { string[] sInput = input.Split("-".ToCharArray()); byte[] data = new byte[sInput.Length]; for (int i = 0; i < sInput.Length; i++) { data[i] = byte.Parse(sInput[i], NumberStyles.HexNumber); } using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); ICryptoTransform desencrypt = des.CreateDecryptor(); byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length); return Encoding.UTF8.GetString(result); } } #endregion #region AES /// <summary> /// AES加密算法 /// </summary> /// <param name="input">明文字符串</param> /// <param name="key">密钥</param> /// <returns>字符串</returns> public static string EncryptByAES(string input, string key) { byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 32)); using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider()) { aesAlg.Key = keyBytes; aesAlg.IV = AES_IV; ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(input); } byte[] bytes = msEncrypt.ToArray(); //return Convert.ToBase64String(bytes);//此方法不可用 return BitConverter.ToString(bytes); } } } } /// <summary> /// AES解密 /// </summary> /// <param name="input">密文字节数组</param> /// <param name="key">密钥</param> /// <returns>返回解密后的字符串</returns> public static string DecryptByAES(string input, string key) { //byte[] inputBytes = Convert.FromBase64String(input); //Encoding.UTF8.GetBytes(input); string[] sInput = input.Split("-".ToCharArray()); byte[] inputBytes = new byte[sInput.Length]; for (int i = 0; i < sInput.Length; i++) { inputBytes[i] = byte.Parse(sInput[i], NumberStyles.HexNumber); } byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 32)); using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider()) { aesAlg.Key = keyBytes; aesAlg.IV = AES_IV; ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msEncrypt = new MemoryStream(inputBytes)) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srEncrypt = new StreamReader(csEncrypt)) { return srEncrypt.ReadToEnd(); } } } } } /// <summary> /// AES加密 /// </summary> /// <param name="inputdata">输入的数据</param> /// <param name="iv">向量128位</param> /// <param name="strKey">加密密钥</param> /// <returns></returns> public static byte[] EncryptByAES(byte[] inputdata, byte[] key, byte[] iv) { 分组加密算法 //Aes aes = new AesCryptoServiceProvider(); 设置密钥及密钥向量 //aes.Key = key; //aes.IV = iv; //using (MemoryStream ms = new MemoryStream()) //{ // using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write)) // { // using (StreamWriter writer = new StreamWriter(cs)) // { // writer.Write(inputdata); // } // return ms.ToArray(); // } //} using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider()) { aesAlg.Key = key; aesAlg.IV = iv; ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(inputdata); } byte[] encrypted = msEncrypt.ToArray(); return encrypted; } } } } /// <summary> /// AES解密 /// </summary> /// <param name="inputdata">输入的数据</param> /// <param name="key">key</param> /// <param name="iv">向量128</param> /// <returns></returns> public static byte[] DecryptByAES(byte[] inputBytes, byte[] key, byte[] iv) { Aes aes = new AesCryptoServiceProvider(); aes.Key = key; aes.IV = iv; byte[] decryptBytes; using (MemoryStream ms = new MemoryStream(inputBytes)) { using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read)) { using (StreamReader reader = new StreamReader(cs)) { string result = reader.ReadToEnd(); decryptBytes = Encoding.UTF8.GetBytes(result); } } } return decryptBytes; } #endregion #region DSA #endregion #region RSA /// <summary> /// RSA加密 /// </summary> /// <param name="plaintext">明文</param> /// <param name="publicKey">公钥</param> /// <returns>密文字符串</returns> public static string EncryptByRSA(string plaintext, string publicKey) { UnicodeEncoding ByteConverter = new UnicodeEncoding(); byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext); using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { RSA.FromXmlString(publicKey); byte[] encryptedData = RSA.Encrypt(dataToEncrypt, false); return Convert.ToBase64String(encryptedData); } } /// <summary> /// RSA解密 /// </summary> /// <param name="ciphertext">密文</param> /// <param name="privateKey">私钥</param> /// <returns>明文字符串</returns> public static string DecryptByRSA(string ciphertext, string privateKey) { UnicodeEncoding byteConverter = new UnicodeEncoding(); using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) { RSA.FromXmlString(privateKey); byte[] encryptedData = Convert.FromBase64String(ciphertext); byte[] decryptedData = RSA.Decrypt(encryptedData, false); return byteConverter.GetString(decryptedData); } } //public static string signByRSA(string plaintext, string privateKey) //{ // UnicodeEncoding ByteConverter = new UnicodeEncoding(); // byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext); // using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider()) // { // RSA.FromXmlString(privateKey); // byte[] encryptedData = RSA.SignData(dataToEncrypt,); // return Convert.ToBase64String(encryptedData); // } //} /// <summary> /// 数字签名 /// </summary> /// <param name="plaintext">原文</param> /// <param name="privateKey">私钥</param> /// <returns>签名</returns> public static string HashAndSignString(string plaintext, string privateKey) { UnicodeEncoding ByteConverter = new UnicodeEncoding(); byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext); using (RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider()) { RSAalg.FromXmlString(privateKey); //使用SHA1进行摘要算法,生成签名 byte[] encryptedData = RSAalg.SignData(dataToEncrypt, new SHA1CryptoServiceProvider()); return Convert.ToBase64String(encryptedData); } } /// <summary> /// 验证签名 /// </summary> /// <param name="plaintext">原文</param> /// <param name="SignedData">签名</param> /// <param name="publicKey">公钥</param> /// <returns></returns> public static bool VerifySigned(string plaintext, string SignedData, string publicKey) { using (RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider()) { RSAalg.FromXmlString(publicKey); UnicodeEncoding ByteConverter = new UnicodeEncoding(); byte[] dataToVerifyBytes = ByteConverter.GetBytes(plaintext); byte[] signedDataBytes = Convert.FromBase64String(SignedData); return RSAalg.VerifyData(dataToVerifyBytes, new SHA1CryptoServiceProvider(), signedDataBytes); } } /// <summary> /// 获取Key /// 键为公钥,值为私钥 /// </summary> /// <returns></returns> public static KeyValuePair<string, string> CreateRSAKey() { RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); string privateKey = RSA.ToXmlString(true); string publicKey = RSA.ToXmlString(false); return new KeyValuePair<string, string>(publicKey, privateKey); } #endregion #region other /// <summary> /// /// </summary> /// <param name="input"></param> /// <returns></returns> public static byte[] GetBytes(string input) { string[] sInput = input.Split("-".ToCharArray()); byte[] inputBytes = new byte[sInput.Length]; for (int i = 0; i < sInput.Length; i++) { inputBytes[i] = byte.Parse(sInput[i], NumberStyles.HexNumber); } return inputBytes; } #endregion }}