【发布时间】:2020-06-19 21:18:03
【问题描述】:
我正在尝试加密/解密一些文件,我将使用通过CipherIn/OutputStreams 传输的FileIn/OutputStreams 来读取/写入这些文件。概念上相当简单,我已经使用原始字节数组和Cipher.doFinal 让它工作。所以我知道我的加密参数(位大小、iv 大小等)是正确的。 (或者至少是功能性的?)
我可以通过CipherOutputStream 写入数据就好了。但是,当我尝试通过CipherInputStream 读回该数据时,它会无限期挂起。
我发现的唯一related problem 仍未得到答复,并且可能与我的问题有根本的不同,因为我的问题将始终在磁盘上提供所有数据,而不是相关问题依赖于Sockets。
我尝试了许多解决方案,最明显的一个是更改缓冲区大小 (data = new byte[4096];)。我尝试了许多值,包括明文的大小和加密数据的大小。这些值都不起作用。我发现的唯一解决方案是完全避免使用CipherInputStream,而是依赖Cipher.doFinal 和Cipher.update。
我错过了什么吗?能够使用CipherInputStream 会非常好,而不必使用Cipher.update 重新发明轮子。
SSCCE:
private static final String AES_ALG = "aes_256/gcm/nopadding";
private static final int GCM_TAG_SIZE = 128;
private static void doEncryptionTest() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException, FileNotFoundException, IOException
{
File f = new File("encrypted_random_data.dat");
// 12-byte long iv
byte[] iv = new byte[] {0x27, 0x51, 0x34, 0x14, -0x65, 0x4d, -0x67, 0x35, -0x63, 0x11, -0x02, -0x05};
// 256-bit long key
byte[] keyBytes = new byte[] {0x55, -0x7f, -0x17, -0x29, -0x68, 0x25, 0x29, 0x5f, -0x27, -0x2d, -0x4d, 0x1b,
0x25, 0x74, 0x57, 0x35, -0x23, -0x1b, 0x12, 0x7c, 0x1, -0xf, -0x60, -0x42, 0x1c, 0x61, 0x3e, -0x5,
-0x13, 0x31, -0x48, -0x6e};
SecretKey key = new SecretKeySpec(keyBytes, "AES");
OutputStream os = encryptStream(key, iv, f);
System.out.println("generating random data...");
// 24MB of random data
byte[] data = new byte[25165824];
new Random().nextBytes(data);
System.out.println("encrypting and writing data...");
os.write(data);
os.close();
InputStream is = decryptStream(key, iv, f);
System.out.println("reading and decrypting data...");
// read the data in 4096 byte packets
int n;
data = new byte[4096];
while ((n = is.read(data)) > 0)
{
System.out.println("read " + n + " bytes.");
}
is.close();
}
private static OutputStream encryptStream(SecretKey key, byte[] iv, File f) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, FileNotFoundException
{
GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_SIZE, iv);
Cipher enc = Cipher.getInstance(AES_ALG);
enc.init(Cipher.ENCRYPT_MODE, key, spec);
OutputStream os = new CipherOutputStream(new FileOutputStream(f), enc);
return os;
}
private static InputStream decryptStream(SecretKey key, byte[] iv, File f) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, FileNotFoundException
{
GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_SIZE, iv);
Cipher dec = Cipher.getInstance(AES_ALG);
dec.init(Cipher.DECRYPT_MODE, key, spec);
InputStream is = new CipherInputStream(new FileInputStream(f), dec);
return is;
}
【问题讨论】: