首页>代码>java实现DES/AES/RSA加密解密算法>/DES_AES_RSA/src/security/AESCoder.java
package security;

import util.HexUtil;
import util.KeyUtil;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.io.UnsupportedEncodingException;

/*
* 1.使用KeyUtil第一种Factory方式生成key 会异常
* 2.使用KeyUtil第二种Generator方式生成key init参数必须设置128位(key参数可任意长,Generator后生成128位)
* 3.使用KeyUtil第三种SecretKeySpec方式生成key key初始长度必须128位
*
* */

public class AESCoder {
    private static final String AES_KEY_ALGORITHM = "AES";
    private static final String AES_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
    private static String IV = "PCNXSJYHJSNXSJYH";

    public static byte[] encrypt(byte[] content, byte[] keyBytes){
        SecretKey key = KeyUtil.getKeyByGenerator(keyBytes,AES_KEY_ALGORITHM,128);
        byte[] result = null;
        try {
            Cipher cipher = Cipher.getInstance(AES_CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
            result = cipher.doFinal(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static byte[] decrypt(byte[] content, byte[] keyBytes){
        SecretKey key = KeyUtil.getKeyByGenerator(keyBytes,AES_KEY_ALGORITHM, 128);
        byte[] result = null;
        try {
            Cipher cipher = Cipher.getInstance(AES_CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
            result = cipher.doFinal(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String content = "风一evolf";
        String key = "01234567012345670";//AES:SecretKeySpec生成key 必须为128位否则异常
        System.out.println("加密原文:"+ HexUtil.byte2HexStr(content.getBytes()));
        System.out.println("加密前16进制:"+HexUtil.byte2HexStr(content.getBytes()));
        byte[] encryptedCont = encrypt(content.getBytes(),key.getBytes());
        System.out.println("加密后16进制:"+HexUtil.byte2HexStr(encryptedCont));
        byte[] decryptedCont = decrypt(encryptedCont, key.getBytes());
        System.out.println("解密后16进制:"+HexUtil.byte2HexStr(decryptedCont));
        System.out.println("解密原文:"+HexUtil.hexStr2Str(HexUtil.byte2HexStr(decryptedCont)));
    }
}
最近下载更多
except I  LV2 2023年11月5日
pfilwy  LV1 2023年2月18日
ljpljpljp  LV2 2022年4月19日
gshnlj  LV15 2022年4月16日
mianhuatang  LV1 2022年3月22日
杂回事类丶  LV11 2022年3月10日
a5366869  LV7 2021年9月20日
liujianliu  LV1 2021年4月13日
缘------  LV9 2021年3月12日
xiaom1211  LV1 2020年11月29日
最近浏览更多
except I  LV2 2023年11月5日
pfilwy  LV1 2023年2月18日
yymmdm  LV6 2022年8月10日
四季夏目  LV7 2022年6月19日
Claire--  LV1 2022年5月2日
wapslnmsl  LV1 2022年4月28日
ljpljpljp  LV2 2022年4月19日
gshnlj  LV15 2022年4月16日
小白鱼 2022年4月11日
暂无贡献等级
许文欣  LV2 2022年3月26日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友