AES

一:简介

高级加密标准(英语:Advanced Encryption Standard,缩写:AES)是一种对称加密算法,加密时需要使用密钥,密钥长度则可以是128,192或256比特,高级加密标准已然成为对称密钥加密中最流行的算法之一。AES是DES的代替品,用于传输敏感敏感的铭文,如常见的密码不能明文传输

二:AESUtil

public class AESUtil {

    /**
     * @param key 密钥
     *
     * @param content 需要加密的字符串
     * @return 密文字节数组
     */
    public static byte[] encrypt(String key, String content) {
        byte[] rawKey = genKey(key.getBytes());
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(rawKey, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] encypted = cipher.doFinal(content.getBytes());
            return encypted;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @param encrypted 密文字节数组
     * @param key 密钥
     * @return 解密后的字符串
     */
    public static String decrypt(byte[] encrypted, String key) {
        byte[] rawKey = genKey(key.getBytes());
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(rawKey, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] decrypted = cipher.doFinal(encrypted);
            return new String(decrypted);
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * @param seed 种子数据
     * @return 密钥数据
     */
    private static byte[] genKey(byte[] seed) {
        byte[] rawKey = null;
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(seed);
            // AES加密数据块分组长度必须为128比特,密钥长度可以是128比特、192比特、256比特中的任意一个
            kgen.init(128, secureRandom);
            SecretKey secretKey = kgen.generateKey();
            rawKey = secretKey.getEncoded();
        } catch (NoSuchAlgorithmException e) {
        }
        return rawKey;
    }


    public static void main(String[] args) {
        // 密钥的种子,可以是任何形式,本质是字节数组
        String key = UUID.randomUUID().toString();

        // 密码的明文
        String clearPwd = "123456";

        // 密码加密后的密文
        byte[] encryptedByteArr = encrypt(key, clearPwd);
        String encryptedPwd = new String(encryptedByteArr);
        System.out.println(encryptedPwd);

        // 解密后的字符串
        String decryptedPwd = decrypt(encryptedByteArr, key);
        System.out.println(decryptedPwd);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风流 少年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值