cqc3073
12/20/2017 - 3:04 AM

加减密方式

基于流的方式在传输或存取时进行加减密

public static void main(String[] args) {
        Path path = Paths.get(StandardSystemProperty.JAVA_IO_TMPDIR.value(), "cipher");
        String s = "基于流的方式,在传输或存取时进行加减密";

        try {
            KeyGenerator keyGen = KeyGenerator.getInstance("AES");
            keyGen.init(256);
            SecretKey secretKey = keyGen.generateKey();

            Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);

            try(OutputStream out = new CipherOutputStream(Files.newOutputStream(path, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE), cipher)) {
                out.write(s.getBytes(StandardCharsets.UTF_8));
                out.flush();
            }

            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            try(InputStream in = new CipherInputStream(Files.newInputStream(path), cipher)) {
                byte[] bytes = ByteStreams.toByteArray(in);
                String s1 = new String(bytes, StandardCharsets.UTF_8);
                System.out.println("s1 = " + s1);
                System.out.println(s.equals(s1));
            }

        } catch (IOException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) {
            e.printStackTrace();
        }

    }