tomcat中的加密程序需要换到iis中,用起了 C#中的 DESCryptoServiceProvider,上网找了些相关流程写了个类,感觉比java的程序精简。
但测试中发现异常,同一次测试中,加密,解密都正常。但把加密的base64字符串,再另外测试就出现“不正确的数据”的提示。
然后再上网对比了很多,没看到什么不对的地方。程序如下:
using System;
using System.Security.Cryptography;
using System.Text;
namespace Cproject.capp
{
public static class Crypt
{
private static DESCryptoServiceProvider crypt = new DESCryptoServiceProvider();
private static bool bInit = false;
public static void init()
{
if (bInit == false)
{
bInit = true;
//crypt.IV = Encoding.UTF8.GetBytes("87654321"); //这里需要添加一行
crypt.Key = Encoding.UTF8.GetBytes("12345678");
crypt.Mode = CipherMode.CBC;
crypt.Padding = PaddingMode.PKCS7;
}
}
public static String encrypt(String str)
{
init();
//用UTF-8编码,转为byte[]
byte[] bysData = Encoding.UTF8.GetBytes(str);
//因為PaddingMode.None的關係, byte[]的長度要是8的倍數
//byte[] bysFixSizeData = new byte[(int)Math.Ceiling(bysData.Length / 8.0) * 8];
//將資料複製到長度為8的倍數的byte[]
//Array.Copy(bysData, bysFixSizeData, bysData.Length);
//进行加密
byte[] bysEncrypted = crypt.CreateEncryptor().TransformFinalBlock(bysData, 0, bysData.Length);
//將byte[]轉為Base64的字串
return Convert.ToBase64String(bysEncrypted);
}
public static String decrypt(String str)
{
init();
byte[] bysData = Convert.FromBase64String(str);
//进行解密
byte[] bysDecrypted = crypt.CreateDecryptor().TransformFinalBlock(bysData, 0, bysData.Length);
return Encoding.UTF8.GetString(bysDecrypted);
}
}
}
若要解密使用其中一个 SymmetricAlgorithm 类加密的数据,必须将 Key 属性和 IV 属性设置为用于加密的相同值。
测试终于成功通过。