byte與base64string的相互轉化以及加密算法


//在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
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM