将.Net解密转换为Java
问题描述
当前,我正在一个项目中,他们使用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.InvalidKeySpecException:找不到密钥长度
思路:
Java代码中存在一些问题:必须指定要生成的位数,除了必须导出IV的密钥,必须将IV应用于解密,密文必须经过Base64解码并且Utf-16LE必须在解码明文时使用。详细信息:
-
实例化
PBEKeySpec
时,必须在第4个参数中指定要生成的位数。由于密钥(256位)和IV(128位)都来自C#代码,因此必须应用384(= 256 + 128):PBEKeySpec
-
前256位是密钥,后128位是IV:
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); PBEKeySpec pbeKeySpec = new PBEKeySpec(encryptionKey.toCharArray(), salt, 1000, 384);
-
必须使用
byte[] derivedData = factory.generateSecret(pbeKeySpec).getEncoded(); byte[] key = new byte[32]; byte[] iv = new byte[16]; System.arraycopy(derivedData, 0, key, 0, key.length); System.arraycopy(derivedData, key.length, iv, 0, iv.length);
实例在Cipher#init
调用的第3个参数中传递IV:Cipher#init
-
密文必须先经过Base64解码,然后才能解密:
IvParameterSpec
-
必须从解密的字节数组使用Utf-16LE编码创建一个字符串(对应于C#中的
IvParameterSpec
:]SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); IvParameterSpec ivSpec = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivSpec);
请注意,对于byte[] result = cipher.doFinal(Base64.getDecoder().decode(userName));
模式,出于安全原因,一次键/ IV组合仅使用一次很重要。对于此处的C#(或Java)代码,这意味着对于相同的密码,每次加密都必须使用不同的盐,请参阅Encoding.Unicode
。