目前我正在做一个项目,他们使用AES加密RFC2898派生字节。这是我提供的解密方法。现在我需要在java中实现它。
private string Decrypt(string cipherText)
{
string EncryptionKey = "MAKV2SPBNI657328B";
cipherText = cipherText.Replace(" ", "+");
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] {
0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76
});
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
这就是我目前所做的:
String EncryptionKey = "MAKV2SPBNI657328B";
String userName="5L9p7pXPxc1N7ey6tpJOla8n10dfCNaSJFs%2bp5U0srs0GdH3OcMWs%2fDxMW69BQb7";
byte[] salt = new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76};
try {
userName = java.net.URLDecoder.decode(userName, StandardCharsets.UTF_8.name());
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec pbeKeySpec = new PBEKeySpec(EncryptionKey.toCharArray(), salt, 1000);
Key secretKey = factory.generateSecret(pbeKeySpec);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] result = cipher.doFinal(userName.getBytes("UTF-8"));
System.out.println(result.toString());
} catch (Exception e) {
System.out.println(e.getMessage());
}
但我得到如下错误:
找不到密钥长度java.security.spec。密钥规范无效异常:找不到密钥长度
1条答案
按热度按时间qhhrdooz1#
Java代码中存在一些问题:必须指定要生成的比特数,除了IV必须导出的密钥外,IV必须用于解密,密文必须是Base64解码,明文解码时必须使用Utf-16 LE,具体如下:
PBEKeySpec
时,必须在第4个参数中指定要生成的位数。由于key(256位)和IV(128位)都是在C#代码中派生的,因此必须应用384(= 256 + 128):IvParameterSpec
示例在Cipher#init
-call的第3个参数中传递IV:Encoding.Unicode
)从解密的字节数组创建字符串:注意,对于CBC模式,出于安全原因,密钥/IV组合只使用一次是很重要的。对于这里的C#(或Java)代码,这意味着对于相同的密码,每次加密必须使用不同的salt,请参见here。