我在 C# 和 Java 中使用了一些加密函数,其输出似乎不匹配。我正在输入与测试相同的键和 IV 字符串。
输入字符串:“&app_version=1.0.0.0”
爪哇:
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes("UTF-8"));
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(input.getBytes("UTF-8"));
// Then I convert encrypted to hex by building a string of encrypted[i] & 0xFF
输出:
60f73a575b647263d75011bb974a90e85201b8dfeec6ec8ffba04c75ab5649b3
C#:
SymmetricKeyAlgorithmProvider alg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbc);
BinaryStringEncoding encoding = BinaryStringEncoding.Utf8;
// Create key and IV buffers
IBuffer keyBuffer = CryptographicBuffer.ConvertStringToBinary(key, encoding);
CryptographicKey cKey = alg.CreateSymmetricKey(keyBuffer);
IBuffer ivBuffer = CryptographicBuffer.ConvertStringToBinary(iv, encoding);
// Create input text buffer
IBuffer inputBuffer = CryptographicBuffer.ConvertStringToBinary(input, encoding);
// Do the encryption
IBuffer encryptedBuffer = CryptographicEngine.Encrypt(cKey, inputBuffer, ivBuffer);
// Convert encrypted back to hex
string encryptedStr = CryptographicBuffer.EncodeToHexString(encryptedBuffer);
输出:
4b6fd83c35565fc30a9ce56134c277cbea74d14886cf99e11f4951075d4f4505
我正在使用 Java 解密器进行检查,它正确解密了 Java 加密的字符串,但 C# 字符串被读取为“&app_version=1Q0.0.0”,所以它看起来很接近但略有偏差。
我在加密步骤之前检查了密钥、输入和 IV 的字节是否匹配。是否有任何其他差异会导致差异?
编辑 使用全零键“00000000000000000000000000000000”和IV“0000000000000000”我得到Java和C#的相同输出:
081821ab6599650b4a31e29994cb130203e0d396a1d375c7d1c05af73b44a86f
所以也许人们正在阅读的钥匙或IV有问题......