c#加密-对应java DES/ECB/PKCS5Padding
/// <summary> /// 对应java的DES/ECB/PKCS5Padding加密 /// </summary> /// <param name="pToEncrypt"></param> /// <param name="sKey"></param> /// <returns></returns> public static string DESEncryptJ(string pToEncrypt, string sKey) { sKey = sKey.Substring(0, 8); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray; inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt); des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); des.Padding = PaddingMode.PKCS7; des.Mode = CipherMode.ECB; System.IO.MemoryStream ms = new System.IO.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); } return ret.ToString(); } /// <summary> /// 对应java的DES/ECB/PKCS5Padding解密 /// </summary> /// <param name="pToDecrypt"></param> /// <param name="sKey"></param> /// <returns></returns> public static string DESDecryptJ(string pToDecrypt, string sKey) { byte[] inputByteArray = Convert.FromBase64String(pToDecrypt); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { byte[] keys = new byte[8]; for (int i = 0; i < 8; i++) { keys[i] = Convert.ToByte(sKey.Substring(i * 2, 2), 16); } des.Key = keys; des.IV = keys; des.Padding = PaddingMode.PKCS7; des.Mode = CipherMode.ECB; MemoryStream ms = new MemoryStream(); using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } string str = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return str; } }