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

Raj*_*ain 2 java encryption jce

我一直在尝试用AES编写加密文件,然后使用JCA中提供的密码流解密它.但是,我在阅读文件时遇到了问题,因为解密会变得混乱.

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);
        FileOutputStream fs = new FileOutputStream("Encrypyed.txt");
        CipherOutputStream out = new CipherOutputStream(fs, aes);
        out.write("[Hello:Okay]\nOkay".getBytes());
        out.close();

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

        FileInputStream fis = new FileInputStream("Encrypyed.txt");
        CipherInputStream in = new CipherInputStream(fis,aes2);
        byte[] b = new byte[8];
        int i = in.read(b);
        while(i!=-1) {
            System.out.print((char)i);
            i = in.read(b);
        }
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IOException ex) {
        Logger.getLogger(CipherStreams.class.getName()).log(Level.SEVERE, null, ex);
    }
}
}
Run Code Online (Sandbox Code Playgroud)

我收到的单字节输出为5.有人可以帮忙指出问题吗?

JB *_*zet 10

你没有写入读取的字节,你正在写入正在读取的字节数.

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

只需执行与编写时相反的操作:读取所有内容,并将读取的字节数组转换为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]\nOkay".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();
            ;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 有效,但可以通过 `BufferedReader d = new BufferedReader(new InputStreamReader(new CipherInputStream(fis, cipher))); 在读取部分进行简化 解密的字符串 = d.readLine();` (2认同)