问题
Using Java BouncyCastle library for encrypting and decrypting byte arrays. Noticed problem that after encrypting-decrypting cycle result arrays contatins redundant zero bytes at the end.
public static void main(String[] args) throws IOException {
Security.addProvider(new BouncyCastleProvider());
File f = new File("C:/~Test/a.txt");
byte[] bytes = FileUtils.readFileToByteArray(f);
byte[] encrypt = encrypt(bytes, "3".getBytes());
byte[] decrypt = decrypt(encrypt, "3".getBytes());
boolean equals = Arrays.equals(bytes, decrypt);
}
public static byte[] processEncoding(boolean isEncrypt, byte[] inBytes, byte[] key) {
PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(
new AESEngine()));
cipher.init(isEncrypt, new KeyParameter(key));
byte[] outBytes = new byte[cipher.getOutputSize(inBytes.length)];
int len = cipher.processBytes(inBytes, 0, inBytes.length, outBytes, 0);
try {
cipher.doFinal(outBytes, len);
} catch (CryptoException e) {
System.out.println("Exception: " + e.toString());
}
return outBytes;
}
public static byte[] encrypt(byte[] inBytes, byte[] key) {
String hash = getHash(key);
byte[] bytes = Arrays.copyOfRange(hash.getBytes(), 0, 32);
return processEncoding(true, inBytes, bytes);
}
public static byte[] decrypt(byte[] inBytes, byte[] key) {
String hash = getHash(key);
byte[] bytes = Arrays.copyOfRange(hash.getBytes(), 0, 32);
return processEncoding(false, inBytes, bytes);
}
Does anyone know how to solve this problem? Thanks.
来源:https://stackoverflow.com/questions/47743860/differ-result-on-byte-array-encodingdecoding-with-bouncy-castle