且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 CipherInputStream 和 CipherOutputStream 加密和解密文件

更新时间:2023-09-25 22:11:34

您不是在写入读取的字节数,而是写入正在读取的字节数.

You're not writing the bytes read, you're writing the number of bytes being read.

您还假设默认平台编码只是将每个字符转换为一个字节.

You're also assuming that the default platform encoding just transforms each character to a byte.

只需执行与写入时相反的操作:读取所有内容,并将读取的字节数组转换为字符串,然后打印该字符串:

Just do the reverse of what you did when writing: read everything, and transform the read byte array to a String, then print that string:

public class CipherStreams {
    public static void main(String[] args) {
        try {
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            Key k = keygen.generateKey();

            Cipher aes = Cipher.getInstance("AES/ECB/PKCS5Padding");
            aes.init(Cipher.ENCRYPT_MODE, k);
            String fileName = "Encrypted.txt";
            FileOutputStream fs = new FileOutputStream(fileName);
            CipherOutputStream out = new CipherOutputStream(fs, aes);
            out.write("[Hello:Okay]
Okay".getBytes());
            out.flush();
            out.close();

            Cipher aes2 = Cipher.getInstance("AES/ECB/PKCS5Padding");
            aes2.init(Cipher.DECRYPT_MODE, k);

            FileInputStream fis = new FileInputStream(fileName);
            CipherInputStream in = new CipherInputStream(fis, aes2);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte[] b = new byte[1024];
            int numberOfBytedRead;
            while ((numberOfBytedRead = in.read(b)) >= 0) {
                baos.write(b, 0, numberOfBytedRead);
            }
            System.out.println(new String(baos.toByteArray()));
        }
        catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IOException ex) {
            ex.printStackTrace();
            ;
        }
    }
}