如何从 android 中的 AES 加密字符串中删除 PKCS7 填充?

How to remove PKCS7 padding from an AES encrypted string in android?

我正在使用我自己的自定义加密方法开发安全应用程序,但在消息解密方面遇到问题。

这是我的代码

private static void myCryptography(){

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
byte[] input = "Hitesh Dhamshaniya".getBytes();
byte[] keyBytes = "ABCD657865BHNKKK".getBytes();
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");

// encryption pass

cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
ctLength += cipher.doFinal(cipherText, ctLength);
Log.e("==> ", " == > Encode " + Base64.encodeToString(cipherText, Base64.DEFAULT));
String encodedStr = Base64.encodeToString(cipherText, Base64.DEFAULT);
// decryption pass

cipherText = Base64.decode(encodedStr, Base64.DEFAULT);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] plainText = new byte[cipher.getOutputSize(ctLength)];
int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0);
ptLength += cipher.doFinal(plainText, ptLength);
Log.e("==> ", " == > Decoded " + new String(plainText, "UTF-8"));

}

低于输出

== > 编码 TteNmufoa5AWWmEPBmQ3N8fdqRpahvwUR7CSclAcsjM=

== > 已解码 Hitesh Dhamshaniya����������������������

如何从解码字符串中删除不需要的字符,如 '��'。

密码自动删除填充。你在这里看到的来自字节数组 plainText 到字符串的转换。您应该只使用前 ptLength 个字节而不是整个数组:

new String(plainText, 0, ptLength, "UTF-8")