【发布时间】:2019-01-04 14:38:32
【问题描述】:
我创建了一个简单的 java 方法,它使用 bouncy castle 库加密和解密文本。加密按预期工作,但是当我解密某些内容时,最后会得到这些额外的方形符号:
我认为这可能与填充有关,但我关注了充气城堡网站上的 the example,所以我真的不明白为什么我会得到这种输出。这是我正在使用的代码:
[主要]
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);
}
[加密解码器]
// 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);
}
}
请记住,我仍在学习密码学,很想听听任何关于为什么会发生这种情况的解释。提前致谢。
【问题讨论】:
标签: java encryption cryptography aes bouncycastle