AES对称加密算法

package com.dp;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.SecureRandom;

public class AESTest {
    public static void main(String[] args) throws Exception{
        //要加密的字符串
        String content = "hello world";
        //key
        String key = "123456";

        //加密
        byte [] cipherBytes = encrypt(content.getBytes(),key.getBytes());
        System.out.println("加密后:"+new String(cipherBytes));

        //解密
        byte [] plainBytes = decrypt(cipherBytes,key.getBytes());
        System.out.println("解密后:"+new String(plainBytes));
    }
	//解密算法
    private static byte[] decrypt(byte[] cipherBytes, byte[] key) throws Exception{
        //生成秘钥对象
        SecretKey secretKey = generateKey(key);
        //获取AES加密器
        Cipher cipher = Cipher.getInstance("AES");
        //初始化加密器
        cipher.init(Cipher.DECRYPT_MODE,secretKey);
        //解密
        return cipher.doFinal(cipherBytes);

    }

    //加密算法
    private static byte[] encrypt(byte[] plainBytes, byte[] key) throws  Exception{
        //生成秘钥对象
        SecretKey secretKey = generateKey(key);
        //获取AES加密器
        Cipher cipher = Cipher.getInstance("AES");
        //初始化加密器
        cipher.init(Cipher.ENCRYPT_MODE,secretKey);
        //加密数据,返回秘闻
        return cipher.doFinal(plainBytes);
    }

    //生成秘钥对象
    private static SecretKey generateKey(byte[] key) throws Exception{
        //根据指定的rng算法创建随机数生成器,注意是数字1
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        //秘钥key 作为随机数的种子
        random.setSeed(key);
        //创建AES算法生成器
        KeyGenerator gen = KeyGenerator.getInstance("AES");
        //初始化算法生成器,生成一个128位的随机源--128、192、256
        gen.init(64,random);
        //生成秘钥对象
        return  gen.generateKey();

    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值