简体   繁体   English

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

[英]AES/CBC/NoPadding between C# and Java

I'm using some encryption functions in C# and Java whose output doesn't seem to match. 我在C#和Java中使用了一些加密函数,它们的输出似乎不匹配。 I'm feeding in the same key and IV strings as a test. 我正在输入相同的键和IV字符串作为测试。

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

Java: 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

Output: 输出:

60f73a575b647263d75011bb974a90e85201b8dfeec6ec8ffba04c75ab5649b3

C#: 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);

Output: 输出:

4b6fd83c35565fc30a9ce56134c277cbea74d14886cf99e11f4951075d4f4505

I am using a Java decrypter to check and it decrypts the Java-encrypted string correctly but the C# string is read as "&app_version=1Q0.0.0" so it seems close but slightly off. 我正在使用Java解密程序进行检查,并且它正确地解密了Java加密的字符串,但是C#字符串被读取为“&app_version = 1Q0.0.0”,因此它看起来很接近,但略有偏离。

I have checked that the bytes of the key, input, and IV match before the encryption step. 我在加密步骤之前检查了密钥,输入和IV的字节是否匹配。 Are there any other differences that would cause a discrepancy? 还有其他差异会导致差异吗?

EDIT With all-zero key "00000000000000000000000000000000" and IV "0000000000000000" I got the same output for both Java and C#: 编辑使用全零键“ 00000000000000000000000000000000000000”和IV“ 0000000000000000”,对于Java和C#,我得到相同的输出:

081821ab6599650b4a31e29994cb130203e0d396a1d375c7d1c05af73b44a86f

So perhaps there is something wrong with the key or IV that one is reading... 因此,可能正在读取的键或IV出现了问题...

I feel like a fool...my IV contained a zero in one and a capital O in another!! 我觉得自己像个傻瓜...我的IV包含一个零,另一个包含一个大写的O! Well, at least I know this code is equivalent. 好吧,至少我知道这段代码是等效的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM