Differ result on byte array encoding+decoding with Bouncy Castle

心不动则不痛 提交于 2019-12-11 14:27:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!