基于流的方式在传输或存取时进行加减密
java 代码片断 加解密    2018-03-09 16:59:03    0    0    0
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();
    }

}


上一篇: Protocol Buffers 2 简要用法

下一篇: Linux命令: ss

文档导航