admin 发布时间:2014-12-10 分类:.NET 阅读:5005次 5 条评论
最近一个项目,涉及到java编写的一个集成系统,与几个用C#编写的子系统之间互相传递加密的数据。
以下分别是C#与Java的加密方式:
/// <summary> /// 加密 /// </summary> /// <param name="encryptString"></param> /// <param name="encryptKey">8位的key</param> /// <returns></returns> public static string DESEncrypt(string encryptString, string encryptKey) { DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider(); byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey); byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, new byte[8]), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Convert.ToBase64String(mStream.ToArray()); }
/// <summary> /// 解密 /// </summary> /// <param name="decryptString"></param> /// <param name="decryptKey">8位的key</param> /// <returns></returns> public static string DESDecrypt(string decryptString, string decryptKey) { byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey); byte[] inputByteArray = Convert.FromBase64String(decryptString.Replace(' ', '+')); DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider(); MemoryStream mStream = new MemoryStream(); CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, new byte[8]), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Encoding.UTF8.GetString(mStream.ToArray()); }
Java加密解密方法:
public static String encryptDES(String encryptString, String encryptKey) throws Exception { IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]); SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES"); Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv); byte[] encryptedData = cipher.doFinal(encryptString.getBytes()); return new BASE64Encoder().encode(encryptedData); } public static String decryptDES(String decryptString, String decryptKey) throws Exception { byte[] byteMi = new BASE64Decoder().decodeBuffer(decryptString); IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]); SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES"); Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key, zeroIv); byte decryptedData[] = cipher.doFinal(byteMi); return new String(decryptedData); }
发布于 2014-12-22 14:41:51 回复该评论
发布于 2014-12-20 16:27:12 回复该评论
发布于 2014-12-15 13:45:53 回复该评论
发布于 2014-12-13 20:10:36 回复该评论
发布于 2014-12-12 15:15:55 回复该评论
发表评论:
◎欢迎您的参与讨论。