C# DES算法指定键的大小对于此算法无效
网上找的使用csharp的des算法加密字符串时报错:
指定键的大小对于此算法无效。
说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。
异常详细信息: System.ArgumentException: 指定键的大小对于此算法无效。
源错误:
行 39: //访问数据加密标准(DES)算法的加密服务提供程序 (CSP) 版本的包装对象 行 40: DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 行 41: des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); //建立加密对象的密钥和偏移量
网上找了下说是:des.key 和des.IV 必须达到8位。
我的sKey长度已经达到9位了,干嘛还报错?于是改成8位,成功调用asp.net的DES算法加密解密。DES难道key长度只能设置为8位的?晓不得。。
下面贴出找到的C# DES加密解密源代码,附带MD5加密
using System.Web.Security; using System.Security.Cryptography; using System.IO; /// <summary> /// 加密解密类 /// </summary> public class Crypt { public static string sKey = "你的密钥字符串";//长度为8位,要不报错:指定键的大小对于此算法无效 /// <summary> /// md5加密算法 /// </summary> /// <param name="str">要加密的字符创</param> /// <param name="Len16">是否长度为16,对应asp的md5加密</param> /// <returns>加密后的字符串</returns> public static string MD5(string str, bool Len16) { if (Len16) return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "md5").ToLower().Substring(8, 16); else return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "md5").ToLower(); } /// <summary> /// DES 加密过程 /// </summary> /// <param name="pToDecrypt">被解密的字符串</param> /// <returns>返回被解密的字符串</returns> public static string Encrypt(string pToEncrypt) { //访问数据加密标准(DES)算法的加密服务提供程序 (CSP) 版本的包装对象 DESCryptoServiceProvider des = new DESCryptoServiceProvider(); des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); //建立加密对象的密钥和偏移量 des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); //原文使用ASCIIEncoding.ASCII方法的GetBytes方法 byte[] inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt);//把字符串放到byte数组中 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(); } /// <summary> /// DES 解密过程 /// </summary> /// <param name="pToDecrypt">被解密的字符串</param> /// <returns>返回被解密的字符串</returns> public static string Decrypt(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 = ASCIIEncoding.ASCII.GetBytes(sKey); //建立加密对象的密钥和偏移量,此值重要,不能修改 des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); //建立StringBuild对象,createDecrypt使用的是流对象,必须把解密后的文本变成流对象 StringBuilder ret = new StringBuilder(); return System.Text.Encoding.UTF8.GetString(ms.ToArray()); } }
加支付宝好友偷能量挖...
原创文章,转载请注明出处:C# DES算法指定键的大小对于此算法无效