DES加密是第一次使用,现在已经是一种过时的加密方式了,由于需求用到,这里列举一个示例:
核心代码:
/// <summary> /// DES加密 /// </summary> /// <param name="data">加密字符串</param> /// <param name="key">商户私钥</param> /// <param name="iv">偏移量</param> /// <returns></returns> public static string DESEncrypt(string data, string key, string iv) { //byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(key.Substring(0,8)); //byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(iv); //注意这里key最多只能有8位,超出8位自动截断 byte[] byKey = Encoding.UTF8.GetBytes(key.Substring(0, 8)); byte[] byIV = Encoding.UTF8.GetBytes(iv); DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider(); cryptoProvider.Mode = CipherMode.CBC; cryptoProvider.Padding = PaddingMode.PKCS7; MemoryStream ms = new MemoryStream(); CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write); StreamWriter sw = new StreamWriter(cst); sw.Write(data); sw.Flush(); cst.FlushFinalBlock(); sw.Flush(); return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length); }
常见问题:Specified key is not a valid size for this algorithm. (给出的key的长度大于8位导致的,代码里已经做了兼容,最多取8位)
也可以使用其他在线校验核对工具,跟代码生成数据进行比对:http://tool.chacuo.net/cryptdes
标签:加密,key,DES,cryptoProvider,new,byte From: https://www.cnblogs.com/lxhbky/p/16650208.html