使用Java BouncyCastle库加密和解密字节数组。注意到加密 - 解密循环结果数组在结束时占用冗余零字节的问题。
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);
}
有谁知道如何解决这个问题?感谢。