AES加密

笔记:


import org.junit.Test;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AES {

    public static String ALGGORITHM = "AES";

    public static byte[] encory(String content,String password) throws Exception{
       KeyGenerator kgen = KeyGenerator.getInstance(ALGGORITHM);
       //用户密码作为随机数初始化
        kgen.init(128,new SecureRandom(password.getBytes()));
        //得到一个密钥
        SecretKey secretKey = kgen.generateKey();

        //对密钥进行基本的编码
        byte[] encodedFormat = secretKey.getEncoded();
        //转换成AES专用密钥
        SecretKeySpec key = new SecretKeySpec(encodedFormat,ALGGORITHM);
        //创建一个密码器
        Cipher cipher = Cipher.getInstance(ALGGORITHM);

        byte[] byteContent = content.getBytes();
        //开始加密了
        cipher.init(Cipher.ENCRYPT_MODE,key);
        byte[] result = cipher.doFinal(byteContent);
        return result;
    }

    public static byte[] decrypt(byte[] content,String password) throws Exception{
        //创建AES的key生产者
        KeyGenerator kgen = KeyGenerator.getInstance(ALGGORITHM);
        //利用用户密码最为随机数初始化
        kgen.init(128,new SecureRandom(password.getBytes()));
        //根据用户密码,生成英特密钥 (所有对称算法通用)
        SecretKey secretKeySpec = kgen.generateKey();
        //对密钥进行基本的编码
        byte[] enCodeFormat = secretKeySpec.getEncoded();
        //转换成AES专用的密钥 RoundKey
        SecretKeySpec key = new SecretKeySpec(enCodeFormat,ALGGORITHM);
        //创建一个密码器
        Cipher cipher = Cipher.getInstance(ALGGORITHM);

        //解密
        cipher.init(Cipher.DECRYPT_MODE,key);
        byte[] result = cipher.doFinal(content);
        return result;
    }

    @Test
    public void testAES() throws Exception{
        String content = "wwy";
        String password = "123dsad";
        byte[] encory = encory(content,password);
        System.out.println("加密数据: " + new String(encory));

        byte[] decory = decrypt(encory,password);
        System.out.println("解密的数据: " + new String(decory));
    }

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值