【发布时间】:2021-02-06 03:05:38
【问题描述】:
我试图在 C# 中模仿 java 加密例程,因为端点是基于 java 的,并且将解密 C# 生成的值。
我已经尝试使用来自 SO 和网络周围的几个示例中的 AesCryptoServiceProvider 和 AesManaged 的不同实现,但我仍然无法让 java 端点成功解密该值,它与 {"message":"AUTHENTICATION_ERROR: Error while decrypting the cipher.","status":"Error"} 出错。
使用邮递员,我能够调用 java 端点并使用 由下面发布的java代码生成的加密文本,因此该部分得到了肯定的验证。
端点使用标头值解密文本并验证内容,以下是相关代码片段:
java 加密
private static Cipher generateCipher(int mode, String password, String salt, String iv, Integer iterations, Integer keySize) throws Exception {
byte[] saltBytes = salt.getBytes("UTF-8"); byte[]ivBytes = iv.getBytes("UTF-8");
// Derive the key
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes, iterations, keySize);
SecretKey secretKey = factory.generateSecret(spec);
SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
//encrypt the message
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(mode, secret, new IvParameterSpec(ivBytes));
return cipher;
}
public static String AES_encrypt(String plainText, String password, String salt, String iv, Integer iterations, Integer keySize) throws Exception {
Cipher cipher = generateCipher(Cipher.ENCRYPT_MODE, password, salt, iv, iterations, keySize);
byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
Base64.Encoder encoder = Base64.getEncoder();
return encoder.encodeToString(encryptedTextBytes);
}
标题
interface_name: interfaceName
strength: 256
salt: salt_sixteen1234
iterate: 100
iv: sixteen_value_12
ciphertext: ECtKO7VluxCPFS/D8LVsb2bOQjhViIZm+O3zfMqSwJOLLTpDL4xdgwmIWr+41n5j
C# 加密
...
using (var csp = new AesCryptoServiceProvider())
{
ICryptoTransform e = GetCryptoTransform(csp, true, key, salt, iv);
byte[] inputBuffer = Encoding.UTF8.GetBytes(plainText);
byte[] output = e.TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);
string encrypted = Convert.ToBase64String(output);
return encrypted;
}
...
private static ICryptoTransform GetCryptoTransform(AesCryptoServiceProvider csp, bool encrypting, string password, string salt, string iv, int iterations)
{
csp.Mode = CipherMode.CBC;
csp.Padding = PaddingMode.PKCS7;
var spec = new Rfc2898DeriveBytes(Encoding.UTF8.GetBytes(password), Encoding.UTF8.GetBytes(salt), iterations);
byte[] key = spec.GetBytes(16);
csp.IV = Encoding.UTF8.GetBytes(iv);
csp.Key = key;
if (encrypting)
{
return csp.CreateEncryptor();
}
return csp.CreateDecryptor();
}
【问题讨论】:
-
你如何通过静脉注射?它通常预先添加到消息中,我看不到它已完成。
-
@JonasH:看起来像静态 iv 就位,因此无需通过 iv。顺便提一句。 静态 iv 和 salt 的使用是不安全的。
-
您可能使用不同的密钥大小(因此 AES 变体)。 Java 代码应用
keySize位密钥(如果strength等于keySize256 位密钥),C# 代码应用128 位密钥。因此,在GetCryptoTransform()的C# 代码中,您还应该传递keySize参数并使用byte[] key = spec.GetBytes(keySize / 8);确定该方法中的密钥。顺便说一句:在发布的 C# 代码中,GetCryptoTransform调用中缺少iterations参数。另外iterations参数一般太小了100。
标签: java c# encryption aes