首先我对DES加密的各种算法不了解
在网上找了很多.net下的DES算法,要求输入的密钥都是8个字节的字符串
但是我现在手里面的密钥是16个字符的字符串。
比如我要求的密钥是:1234567812345678
但是我用方法传人这个密钥就会报错的————>“指定键的大小对于此算法无效。”
不懂这中间怎么转换,还是方法不对呢。
下面是加密的方法。
希望会的朋友帮下忙,很急的。。。
- C# code
public static string DESEnCode(string pToEncrypt, string sKey) { pToEncrypt = HttpContext.Current.Server.UrlEncode(pToEncrypt); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt); des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes("1111111111111111"); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } ret.ToString(); return ret.ToString().ToLower(); }
------解决方案--------------------------------------------------------
- C# code
public static string My3DESEnCode(string pToEncrypt, string sKey) { pToEncrypt = HttpContext.Current.Server.UrlEncode(pToEncrypt); //DESCryptoServiceProvider des = new DESCryptoServiceProvider(); SymmetricAlgorithm des = TripleDES.Create(); byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt); des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes("12345678"); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } ret.ToString(); return ret.ToString().ToLower(); }