java使用 AES-128-cbc 加解密

首先介绍相关的几个重要的类:
(一)KeyGenerator
Java提供了一个名称为KeyGenerator的类,该类用于生成密钥,此类的对象是可重用的。
要使用KeyGenerator类生成密钥,请按照以下步骤操作
第1步:创建KeyGenerator对象
KeyGenerator类提供getInstance()方法,该方法接受表示所需密钥生成算法的String变量,并返回生成密钥的KeyGenerator对象。

第2步:创建SecureRandom对象java.Security包的SecureRandom类提供了一个强大的随机数生成器,用于在Java中生成随机数

第3步:第初始化KeyGeneratorKeyGenerator类提供了一个名为init()的方法,此方法接受SecureRandom对象并初始化当前的KeyGenerator。

第4步:利用KeyGenerator.generateKey() 生成一个密钥。返回的是一个SecretKey ,SecretKey key = KeyGenerator.generateKey()

第5步:得到密钥的字节数组,byte[] keys = key.getEncoded();

private static void createKey(){
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(128,new SecureRandom());
            SecretKey secretKey = keyGenerator.generateKey();
            key = secretKey.getEncoded();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

也可以使用SecretKeySpec 类创造密钥:

SecretKeySpec keySpec = new SecretKeySpec(IV.getBytes(StandardCharsets.UTF_8),"AES");

(二)Cipher
此类为加密和解密提供密码功能。
(1)为创建 Cipher 对象,应用程序调用 Cipher 的 getInstance 方法并将所请求转换 的名称传递给它。
(2)初始化cipher.init(字段,密钥,new IvParameterSpec(string.getBytes()) ) ,最后一个参数为初始化向量,并且string为16字节
(三)CipherInputStream
读取字节流时调用的cipher.update()方法进行流部分加密, 当加密到最后一段时,会调用 doFinal() 方法。

  CipherInputStream cipherInputStream = new CipherInputStream(inputFile, cipher);

加密代码:

/*
     *加密
     */
    private static void encodeFile(String path, String encodePath) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IOException {
        SecretKeySpec keySpec = new SecretKeySpec(key,"AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE,keySpec,new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8)));
        FileInputStream inputStream = new FileInputStream(path);
        CipherInputStream cipherInputStream = new CipherInputStream(inputStream,cipher);
        FileOutputStream outputStream = new FileOutputStream(encodePath);
        int length;
        byte[] b = new byte[1024];
        while ((length = cipherInputStream.read(b)) != -1){
            outputStream.write(b);
            outputStream.flush();
        }
        cipherInputStream.close();
        outputStream.close();
    }

解密:

 /*
     * 解密
     */
    private static void decoder(String encode,String decoder) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IOException {
        SecretKeySpec keySpec = new SecretKeySpec(key,"AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE,keySpec,new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8)));

        FileInputStream inputStream = new FileInputStream(encode);
        FileOutputStream outputStream = new FileOutputStream(decoder);
        CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream,cipher);
        int length;
        byte[] bytes = new byte[1024];
        while ((length = inputStream.read(bytes)) != -1){
            cipherOutputStream.write(bytes,0,length);
        }
        inputStream.close();
        cipherOutputStream.close();
    }

完整示例代码:(对文件进行加解密)

public class MyClass {
    private static byte[] key;
    private static String IV = "ikldokiujujikijo";

    public static void main(String[] args) {
        createKey();
        try {
            encodeFile("C:\\Users\\zhaol\\Desktop\\SerurityUtil.java","C:\\Users\\zhaol\\Desktop\\1.java");
            decoder("C:\\Users\\zhaol\\Desktop\\1.java","C:\\Users\\zhaol\\Desktop\\2.java");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void createKey() {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
            keyGenerator.init(128, new SecureRandom());
            SecretKey secretKey = keyGenerator.generateKey();
            key = secretKey.getEncoded();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    /*
     *加密
     */
    private static void encodeFile(String path, String encodePath) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IOException {
        SecretKeySpec keySpec = new SecretKeySpec(key,"AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE,keySpec,new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8)));
        FileInputStream inputStream = new FileInputStream(path);
        CipherInputStream cipherInputStream = new CipherInputStream(inputStream,cipher);
        FileOutputStream outputStream = new FileOutputStream(encodePath);
        int length;
        byte[] b = new byte[1024];
        while ((length = cipherInputStream.read(b)) != -1){
            outputStream.write(b,0,length);
            outputStream.flush();
        }
        cipherInputStream.close();
        outputStream.close();
    }

    /*
     * 解密
     */
    private static void decoder(String encode,String decoder) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IOException {
        SecretKeySpec keySpec = new SecretKeySpec(key,"AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE,keySpec,new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8)));

        FileInputStream inputStream = new FileInputStream(encode);
        FileOutputStream outputStream = new FileOutputStream(decoder);
        CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream,cipher);
        int length;
        byte[] bytes = new byte[1024];
        while ((length = inputStream.read(bytes)) != -1){
            cipherOutputStream.write(bytes,0,length);
        }
        inputStream.close();
        cipherOutputStream.close();
    }

}

你可能感兴趣的:(java)