我想用 Java 解密 AES 加密消息。我一直在尝试来自标准库和BouncyCastle的各种算法/模式/填充选项。没运气 :-(
加密实体是用 Python 编写的,并且已经投入生产。加密的消息已经出去了,所以我不能轻易改变那部分。Python 代码如下所示:
from Crypto.Cipher import AES
import base64
import os
import sys
BLOCK_SIZE = 16
PADDING = '\f'
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
secret = 'XXXXXXXXXXXXXXXX'
cipher = AES.new(secret)
clear='test'
encoded = EncodeAES(cipher, clear)
print 'Encrypted string:>>{}<<'.format(encoded)
decoded = DecodeAES(cipher, encoded)
print 'Decrypted string:>>{}<<'.format(decoded)
显然使用了AES,我发现我必须使用ECB模式。但我还没有找到适用于 Java 端的填充模式。如果输入适合块大小并且没有发生填充,我可以用 Java 解密消息。如果需要填充消息,则解密失败。
要解密的 Java 代码如下所示:
public class AESPaddingTest {
private enum Mode {
CBC, ECB, CFB, OFB, PCBC
};
private enum Padding {
NoPadding, PKCS5Padding, PKCS7Padding, ISO10126d2Padding, X932Padding, ISO7816d4Padding, ZeroBytePadding
}
private static final String ALGORITHM = "AES";
private static final byte[] keyValue = new byte[] { 'X', 'X', 'X', 'X',
'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X' };
@BeforeClass
public static void configBouncy() {
Security.addProvider(new BouncyCastleProvider());
}
@Test
public void testECBPKCS5Padding() throws Exception {
decrypt("bEpi03epVkSBTFaXlNiHhw==", Mode.ECB,
Padding.PKCS5Padding);
}
private String decrypt(String valueToDec, Mode modeOption,
Padding paddingOption) throws GeneralSecurityException {
Key key = new SecretKeySpec(keyValue, ALGORITHM);
Cipher c = Cipher.getInstance(ALGORITHM + "/" + modeOption.name() + "/" + paddingOption.name());
c.init(Cipher.DECRYPT_MODE, key);
byte[] decValue = c.doFinal(valueToDec.getBytes());
String clear = new String(Base64.encodeBase64(decValue));
return clear;
}
}
抛出的错误是:
javax.crypto.IllegalBlockSizeException:使用填充密码解密时,输入长度必须是 16 的倍数
有任何想法吗?