对接Java所谓的DES加解密
众所周知,Java的一些封装方法中默认编码方式和实现略有不同与c#, 以及基础类型整型默认范围是有符号的,可以是负数,但是c#中默认是有符号的,不能为负数.
两者在对接的时候,涉及到一些编码方式,以及加解密时问题就来了,网上铺天盖地的各种兼容写法实际上手之后很难凑效,下面针对DES加解密默认方式来处理
C# 代码如下,针对 java 默认的是ECB模式,PKCS5padding;
public static string EncryptKiaser(string destring, string secretKey, bool bolCode = false) { // 示例数据和密钥 byte[] keyBytes = Encoding.UTF8.GetBytes(secretKey); byte[] keyIV = keyBytes; byte[] inputByteArray = Encoding.UTF8.GetBytes(destring); DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider(); // java 默认的是ECB模式,PKCS5padding;c#默认的CBC模式,PKCS7padding 所以这里我们默认使用ECB方式 desProvider.Mode = CipherMode.ECB; MemoryStream memStream = new MemoryStream(); CryptoStream crypStream = new CryptoStream(memStream, desProvider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write); crypStream.Write(inputByteArray, 0, inputByteArray.Length); crypStream.FlushFinalBlock(); string base64Str = Convert.ToBase64String(memStream.ToArray()); return base64Str; } public static string DEScryptKiaser(string decryptString, string sKey) { byte[] keyBytes = Encoding.UTF8.GetBytes(sKey); byte[] keyIV = keyBytes; byte[] inputByteArray = Convert.FromBase64String(decryptString); DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider(); // java 默认的是ECB模式,PKCS5padding;c#默认的CBC模式,PKCS7padding 所以这里我们默认使用ECB方式 desProvider.Mode = CipherMode.ECB; MemoryStream memStream = new MemoryStream(); CryptoStream crypStream = new CryptoStream(memStream, desProvider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write); crypStream.Write(inputByteArray, 0, inputByteArray.Length); crypStream.FlushFinalBlock(); string result = Encoding.UTF8.GetString(memStream.ToArray()); return result; }
大家好,我是新来的小白,文未佳,却已创。转载请声明(博客园-郎中令)出处,谢谢
---市人皆大笑,举手揶揄之(手动链接博客园)