为什么在用充气城堡解密后附加这些方形符号?

我创建了一个简单的java方法,使用充气城堡库加密和解密文本。 加密按预期工作,但是当我解密某些内容时,我会在最后得到这些额外的方形符号:

安慰 测试

我认为这可能与填充有关,但我已经按照bouncy castle网站上的例子进行了操作,所以我真的不明白为什么我会得到这种输出。 这是我正在使用的代码:

[主要]

public static void main(String[] argv) { String ciphertext = "PlJR5pzbowsuzHIc9iTKHg=="; String decrypted; CryptoCodec codec = new CryptoCodec(); decrypted = codec.exec("AES", "xxxxooooxxxxoooo", ciphertext, false); System.out.println("Ciphertext: " + ciphertext); System.out.println("Decrypted: " + decrypted); } 

[CryptoCodec]

 // Eod: (true) Encrypt or (false) decrypt. public String exec(String algorithm, String key, String data, boolean eod) { // Using AESEngine(); BlockCipher engine = CipherEngine.getBlockCipher(algorithm); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine)); byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); byte[] dataBytes; if(eod) { dataBytes = data.getBytes(StandardCharsets.UTF_8); } else { dataBytes = Base64.decode(data); } cipher.init(eod, new KeyParameter(keyBytes)); byte[] outputText = new byte[cipher.getOutputSize(dataBytes.length)]; int outputTextLen = cipher.processBytes(dataBytes, 0, dataBytes.length, outputText, 0); try { cipher.doFinal(outputText, outputTextLen); } catch (CryptoException err) { err.printStackTrace(); } if(eod) { return new String(Base64.encode(outputText)); } else { return new String(outputText); } } 

请记住,我仍在学习密码学,并希望听到任何解释为什么会发生这种情况。 提前致谢。

在解密期间, cipher.getOutputSize(dataBytes.length)不知道它将从填充中删除多少字节(它甚至不知道你告诉它有关数据的最后部分)。 所以它告诉你最大可能

因此,您的目标arrays比它需要的大,您需要考虑填充的数据量。

你怎么知道填写了多少? 从doFinal捕获返回值。 那你怎么办呢? 告诉String构造函数何时停止读取。

然后你最终得到类似的东西

 try { outputTextLen += cipher.doFinal(outputText, outputTextLen); } catch (CryptoException err) { err.printStackTrace(); } if(eod) { return new String(Base64.encode(outputText)); } else { return new String(outputText, 0, outputTextLen); } 

这也解决了你的错误,如果你现在加密16字节的数据,你将无法成功解密。