在Java中使用AES进行加解密的时候,有时候会使用256位的key且摘要算法使用SHA1PRNG生成32字节(256位)的密钥。但是如果使用256位,那么在C#中就不能解密了。经过分析C#中的SHA1CryptoServiceProvider生成的key摘要只有160位(20字节)。
Java代码如下:
public static String aesDecrypt(byte[] content, String password) throws Exception{
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
secureRandom.setSeed(password.getBytes("UTF-8"));
kgen.init(256,secureRandom);
SecretKey originalKey = kgen.generateKey();
byte[] encoded = originalKey.getEncoded();
SecretKey secretKey = new SecretKeySpec(encoded, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] result = cipher.doFinal(content);
return new String(result, "UTF-8");
}
对应C#中进行解密
public static byte[] AesDecypt(byte[] contents, string secretKey)
{
try
{
byte[] keyBytes = null;
using (var sha1 = new SHA1CryptoServiceProvider())
{
byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(secretKey));
var rd = sha1.ComputeHash(hash);
keyBytes = rd.Take(16).ToArray();
}
RijndaelManaged rm = new RijndaelManaged
{
Key = keyBytes,
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};
ICryptoTransform cTransform = rm.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(contents, 0, contents.Length);
return resultArray;
}
catch
{
return contents;
}
}
如上面Java加密的用C#久不能解密,因为SHA1CryptoServiceProvider最多生成20字节160的摘要。
请问各位专家,C#中有对应的方法吗?非常感谢