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();
    }

}
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
AES-128-CBC是一种对称密钥密算法,其中AES代表高级密标准(Advanced Encryption Standard),128表示使用128位的密钥长度,CBC表示密码分组链接模式(Cipher Block Chaining)。 在AES-128-CBC中,数据被分为固定长度的块,并使用128位的密钥进行密和解密密时,每个数据块会与前一个密的数据块进行异或操作,以增安全性。初始块由初始化向量(IV)指定,IV必须是随机且不可预测的。 AES-128-CBC具有以下特点: 1. 强大的安全性:采用128位的密钥长度和CBC模式,可提供较高的安全性,抵御当前常用的攻击手段。 2. 快速的解密速度:AES算法基于矩阵运算,可以通过硬件优化和并行计算进行速,实现快速的解密操作。 3. 可逆性:密和解密操作使用相同的密钥,可以实现数据的可逆转换,保证数据的完整性和可读性。 4. 简单易用:Java提供了内置的密库,使得在Java使用AES-128-CBC算法变得简单方便。 然而,AES-128-CBC也存在一些不足之处: 1. 密钥管理:由于使用对称密钥,需要使用者妥善管理密钥的生成、传输和保存,以保证密钥的安全性。 2. 块长度有限:AES-128-CBC只能处理固定长度的数据块,如果数据长度不是块长度的整数倍,需要进行填充或截断操作。 3. CBC模式下的性能损耗:由于每个数据块都需要依赖前一个数据块的密结果,导致解密操作无法并行处理,可能造成一定的性能损耗。 总的来说,AES-128-CBC是一种安全性较高、速度较快的对称密钥密算法,适用于Java环境下的数据密和解密需求。使用时需要注意密钥管理和数据块长度限制等问题。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值