C#和Java之间的AES / CBC / NoPadding

我在C#和
Java中使用了一些加密函数,其输出似乎不匹配.我正在用相同的键和IV字符串作为测试.

输入字符串:“& app_version = 1.0.0.0”

Java的:

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有问题……

最佳答案 我觉得自己像个傻瓜……我的IV包含一个零和一个大写O在另一个!好吧,至少我知道这段代码是等价的.

点赞