AESEncrypt.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. namespace HaBookCms.Common.CryptHelper
  7. {
  8. /// <summary>
  9. /// AES加密算法
  10. /// --敏感信息加密使用(动态密钥)
  11. /// --需实例化加密解密类
  12. /// </summary>
  13. public class AESEncrypt
  14. {
  15. public const string RetError = "x07x07x07x07x07";
  16. private readonly byte[] _iv = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
  17. private byte[] _key = { 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5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 0x16 };
  18. private const int CryptoKeyLength = 32;
  19. private AesCryptoServiceProvider _mAesCryptoServiceProvider;
  20. private string _mMessage;
  21. public string Message
  22. {
  23. get { return _mMessage; }
  24. set { _mMessage = value; }
  25. }
  26. private bool _mContainKey;
  27. /// <summary>
  28. /// True:密文中包含密钥
  29. /// False:密文中不包含密钥
  30. /// </summary>
  31. public bool ContainKey
  32. {
  33. get { return _mContainKey; }
  34. set { _mContainKey = value; }
  35. }
  36. public AESEncrypt()
  37. {
  38. _mAesCryptoServiceProvider = new AesCryptoServiceProvider();
  39. _mContainKey = true;
  40. _mMessage = string.Empty;
  41. }
  42. public AESEncrypt(bool containKey)
  43. : this()
  44. {
  45. _mContainKey = containKey;
  46. }
  47. private string Encrypt(string sCrypto, byte[] key)
  48. {
  49. string sEncryped = string.Empty;
  50. byte[] crypto, encrypted;
  51. ICryptoTransform ct;
  52. try
  53. {
  54. crypto = string2Byte(sCrypto);
  55. _mAesCryptoServiceProvider.Key = key;
  56. _mAesCryptoServiceProvider.IV = _iv;
  57. ct = _mAesCryptoServiceProvider.CreateEncryptor();
  58. encrypted = ct.TransformFinalBlock(crypto, 0, crypto.Length);
  59. if (_mContainKey)
  60. {
  61. sEncryped += byte2HexString(key);
  62. }
  63. sEncryped += byte2HexString(encrypted);
  64. return sEncryped;
  65. }
  66. catch (Exception ex)
  67. {
  68. _mMessage = ex.ToString();
  69. return RetError;
  70. }
  71. }
  72. /// <summary>
  73. /// 指定密钥对明文进行AES加密
  74. /// </summary>
  75. /// <param name="sCrypto">明文</param>
  76. /// <param name="sKey">加密密钥</param>
  77. /// <returns></returns>
  78. public string Encrypt(string sCrypto, string sKey)
  79. {
  80. byte[] key = new byte[CryptoKeyLength];
  81. byte[] temp = string2Byte(sKey);
  82. if (temp.Length > key.Length)
  83. {
  84. _mMessage = "Key too long,need less than 32 Bytes key.";
  85. return RetError;
  86. }
  87. key = string2Byte(sKey.PadRight(key.Length));
  88. return Encrypt(sCrypto, key);
  89. }
  90. /// <summary>
  91. /// 动态生成密钥,并对明文进行AES加密
  92. /// </summary>
  93. /// <param name="sCrypto">明文</param>
  94. /// <returns></returns>
  95. public string Encrypt(string sCrypto)
  96. {
  97. byte[] key = new byte[CryptoKeyLength];
  98. _mAesCryptoServiceProvider.GenerateKey();
  99. key = _mAesCryptoServiceProvider.Key;
  100. return Encrypt(sCrypto, key);
  101. }
  102. private string Decrypt(string sEncrypted, byte[] key)
  103. {
  104. string s_decrypted = string.Empty;
  105. byte[] encrypted, decrypted;
  106. ICryptoTransform ct;
  107. try
  108. {
  109. encrypted = hexString2Byte(sEncrypted);
  110. _mAesCryptoServiceProvider.Key = key;
  111. _mAesCryptoServiceProvider.IV = _iv;
  112. ct = _mAesCryptoServiceProvider.CreateDecryptor();
  113. decrypted = ct.TransformFinalBlock(encrypted, 0, encrypted.Length);
  114. s_decrypted += byte2String(decrypted);
  115. return s_decrypted;
  116. }
  117. catch (Exception ex)
  118. {
  119. _mMessage = ex.ToString();
  120. _mMessage = "Decrypt fail.";
  121. return RetError;
  122. }
  123. }
  124. /// <summary>
  125. /// 从密文中解析出密钥,并对密文进行解密
  126. /// </summary>
  127. /// <param name="sEncrypted">密文</param>
  128. /// <returns></returns>
  129. public string Decrypt(string sEncrypted)
  130. {
  131. string s_key = string.Empty;
  132. byte[] key = new byte[CryptoKeyLength];
  133. if (sEncrypted.Length <= CryptoKeyLength * 2)
  134. {
  135. _mMessage = "Encrypted string invalid.";
  136. return RetError;
  137. }
  138. if (_mContainKey)
  139. {
  140. s_key = sEncrypted.Substring(0, CryptoKeyLength * 2);
  141. sEncrypted = sEncrypted.Substring(CryptoKeyLength * 2);
  142. }
  143. key = hexString2Byte(s_key);
  144. return Decrypt(sEncrypted, key);
  145. }
  146. /// <summary>
  147. /// 指定密钥,并对密文进行解密
  148. /// </summary>
  149. /// <param name="sEncrypted">密文</param>
  150. /// <param name="sKey">密钥</param>
  151. /// <returns></returns>
  152. public string Decrypt(string sEncrypted, string sKey)
  153. {
  154. byte[] key = new byte[CryptoKeyLength];
  155. byte[] temp = string2Byte(sKey);
  156. if (temp.Length > key.Length)
  157. {
  158. _mMessage = "Key invalid.too long,need less than 32 Bytes";
  159. return RetError;
  160. }
  161. key = string2Byte(sKey.PadRight(key.Length));
  162. if (_mContainKey)
  163. {
  164. sEncrypted = sEncrypted.Substring(CryptoKeyLength * 2);
  165. }
  166. return Decrypt(sEncrypted, key);
  167. }
  168. #region 私有方法
  169. private string byte2HexString(byte[] bytes)
  170. {
  171. StringBuilder sb = new StringBuilder();
  172. foreach (byte b in bytes)
  173. {
  174. sb.AppendFormat("{0:X2}", b);
  175. }
  176. return sb.ToString();
  177. }
  178. private byte[] hexString2Byte(string hex)
  179. {
  180. int len = hex.Length / 2;
  181. byte[] bytes = new byte[len];
  182. for (int i = 0; i < len; i++)
  183. {
  184. bytes[i] = (byte)(Convert.ToInt32(hex.Substring(i * 2, 2), 16));
  185. }
  186. return bytes;
  187. }
  188. private byte[] string2Byte(string str)
  189. {
  190. return Encoding.UTF8.GetBytes(str);
  191. }
  192. private string byte2String(byte[] bytes)
  193. {
  194. return Encoding.UTF8.GetString(bytes);
  195. }
  196. #endregion
  197. }
  198. /// <summary>
  199. ///3DES加密解密程序
  200. /// --备用
  201. /// </summary>
  202. public class DES3Encrypt
  203. {
  204. //密钥
  205. private static string sKey = "qJzGEh6hESZDVJeCnFPGuxzaiFYTLQM3";
  206. //矢量,矢量可以为空
  207. private static string sIV = "qcDY6X+aPLw=";
  208. //构造一个对称算法
  209. private static SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider();
  210. public DES3Encrypt() { }
  211. /// <summary>
  212. /// 加密
  213. /// </summary>
  214. /// <param name="Value">明文</param>
  215. /// <returns>加密后的密文</returns>
  216. public static string EncryptString(string Value)
  217. {
  218. try
  219. {
  220. ICryptoTransform ct;
  221. MemoryStream ms;
  222. CryptoStream cs;
  223. byte[] byt;
  224. mCSP.Key = Convert.FromBase64String(sKey);
  225. mCSP.IV = Convert.FromBase64String(sIV);
  226. //指定加密的运算模式
  227. mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;
  228. //获取或设置加密算法的填充模式
  229. mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
  230. ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);
  231. byt = Encoding.UTF8.GetBytes(Value + "_0212YUAN");
  232. ms = new MemoryStream();
  233. cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
  234. cs.Write(byt, 0, byt.Length);
  235. cs.FlushFinalBlock();
  236. cs.Close();
  237. return Convert.ToBase64String(ms.ToArray());
  238. }
  239. catch (Exception ex)
  240. {
  241. return Value;
  242. }
  243. }
  244. /// <summary>
  245. /// 解密
  246. /// </summary>
  247. /// <param name="Value"></param>
  248. /// <returns></returns>
  249. public static string DecryptString(string Value)
  250. {
  251. try
  252. {
  253. ICryptoTransform ct;
  254. MemoryStream ms;
  255. CryptoStream cs;
  256. byte[] byt;
  257. mCSP.Key = Convert.FromBase64String(sKey);
  258. mCSP.IV = Convert.FromBase64String(sIV);
  259. mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;
  260. mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
  261. ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);
  262. byt = Convert.FromBase64String(Value);
  263. ms = new MemoryStream();
  264. cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
  265. cs.Write(byt, 0, byt.Length);
  266. cs.FlushFinalBlock();
  267. cs.Close();
  268. return Encoding.UTF8.GetString(ms.ToArray()).Remove(Encoding.UTF8.GetString(ms.ToArray()).Length - 9, 9);
  269. }
  270. catch (Exception ex)
  271. {
  272. return Value;
  273. }
  274. }
  275. }
  276. }