在 GSTR7 中使用填充密码解密时,输入长度必须是 16 的倍数



运行以下代码时如何解决此错误?

String decrypted_appkey = "41+sD/gm9DWQeZbJm98qb3ss9Eu96XkClU5a4hyfaAw=";
String receivedSEK = "0x5D112907B134B9CE30E30745F48A536845521B04F6B912552AAA65B563F01CC0";
decryptedSek = NICEncrypt.decrypt(receivedSEK, decodeBase64StringTOByte(decrypted_appkey));
public static String decrypt(String plainText, byte[] secret)
throws InvalidKeyException, IOException, IllegalBlockSizeException,
BadPaddingException, Exception {
SecretKeySpec sk = new SecretKeySpec(secret, AES_ALGORITHM);
DECRYPT_CIPHER.init(Cipher.DECRYPT_MODE, sk);
byte[] bytes = DECRYPT_CIPHER.doFinal(Base64.getDecoder().decode(plainText));
return Base64.getEncoder().encodeToString(bytes);
}
private static byte[] decodeBase64StringTOByte(String stringData) throws Exception {
return java.util.Base64.getDecoder().decode(stringData.getBytes(CHARACTER_ENCODING));
}

输出:

javax.crypto.IllegalBlockSizeException:使用填充密码解密时,输入长度必须是 16 的倍数 com.sun.crypto.provider.CipherCore.prepareInputBuffer(CipherCore.java:1005) at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:848) at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446) at javax.crypto.Cipher.doFinal(Cipher.java:2164)

通常所谓的包装密钥根本不填充。您收到的很可能是一个加密的 256 位 (AES) 密钥。通常你会使用"AES/ECB/NoPadding",但没有协议规范,这只是一个有根据的猜测。请注意,对于标准提供程序,"AES"字符串默认为"AES/ECB/PKCS5Padding",并将尝试取消填充。

此外,您的包装密钥显然不是以 64 为基数,而是十六进制。您首先需要解码十六进制,并排除包装密钥前面的"0x"

receivedSEK

不在Base64中,但似乎是一些"十六进制"字符串。

String receivedSEK = "0x5D112907B134B9CE30E30745F48A536845521B04F6B912552AAA65B563F01CC0";
int n = (receivedSEK.length() - 2) / 2;
byte[] bytes = new byte[n];
for (int i = 0; i < n; ++i) {
bytes[i] = (byte) Integer.parseInt(receivedSEK.substring(2 + 2*i, 4 + 2*i), 16);
}
decryptedSek = NICEncrypt.decrypt(bytes, decodeBase64StringTOByte(decrypted_appkey));
public static String decrypt(byte[] bytes, byte[] secret)
throws InvalidKeyException, IOException, IllegalBlockSizeException,
BadPaddingException, Exception {
SecretKeySpec sk = new SecretKeySpec(secret, AES_ALGORITHM);
DECRYPT_CIPHER.init(Cipher.DECRYPT_MODE, sk);
byte[] bytes = DECRYPT_CIPHER.doFinal(bytes);
return Base64.getEncoder().encodeToString(bytes);
}
private static byte[] decodeBase64StringTOByte(String stringData) throws Exception {
return Base64.getDecoder().decode(stringData);
}

此外,Base64解码更简单。

最新更新