标签:否则 enc 存在 static blog 字符 uil style foreach
原文:DES加密解密
DES(Data Encryption Standard)的加密与MD5不同,DES可以解密,而MD5的加密是不可逆的;用于数字签名和数据加密,对称加密-即加密秘钥和解密秘钥相同。
标准的DES密钥长度为64bit,密钥每个字符占7bit,外加1bit的奇偶校验,64/(7+1)=8;所以必须是8个字符也只能是8个字符,但 .NET 里 DESCryptoServiceProvider 这个类是微软已经封装好的了,如果密钥长度不足,会以 PKCS7Padding 方式补足位。
加密:
首先我们先定义好key和iv
private static string key = "abcd1234";//密文 加密解密是都需要密文且保持一致 private static string iv = "12345678";//加密解密时key 、 iv 中传入的key、iv值一致
注意:
public string Des(string encryptString) { DESCryptoServiceProvider des=new DESCryptoServiceProvider(); byte[] sor = Encoding.UTF8.GetBytes(encryptString); //传入key、iv des.Key = UTF8Encoding.UTF8.GetBytes(key); des.IV = UTF8Encoding.UTF8.GetBytes(iv); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(sor, 0, sor.Length); cs.FlushFinalBlock(); StringBuilder sb = new StringBuilder(); foreach (byte b in ms.ToArray()) { sb.AppendFormat("{0:X2}", b); } return sb.ToString(); }
几个必要的对象:
解密:
public string DecryptString(string pToDecrypt) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = new byte[pToDecrypt.Length / 2]; for (int x = 0; x < pToDecrypt.Length / 2; x++) { int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16)); inputByteArray[x] = (byte)i; }
des.Key = UTF8Encoding.UTF8.GetBytes(key);//***************key与加密时的Key保持一致 des.IV = UTF8Encoding.UTF8.GetBytes(iv);//*****************skey与加密时的IV保持一致 MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); return Encoding.UTF8.GetString(ms.ToArray()); }
标签:否则 enc 存在 static blog 字符 uil style foreach
原文地址:https://www.cnblogs.com/lonelyxmas/p/11410024.html