java AES工具类

41 篇文章 1 订阅
38 篇文章 0 订阅
package com.wjj.application.paysdk.crypt.tools;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;

/**
 * AES工具类
 * 参考: https://howtodoinjava.com/security/java-aes-encryption-example/
 * @author hank
 * @since 2020/3/3 0003 下午 18:00
 */
public class AesCryptTools {
    private static final String CHARSET = "utf-8";

    /**
     * 生成随机密钥
     * @param keySize 密钥大小推荐128 256
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String generateSecret(int keySize) throws NoSuchAlgorithmException {
        KeyGenerator generator = KeyGenerator.getInstance("AES");
        generator.init(keySize, new SecureRandom());
        SecretKey key = generator.generateKey();
       return byteToHexString(key.getEncoded());
    }

    public static String encrypt(String strToEncrypt, String secret) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        SecretKeySpec secretKey = getKey(secret);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
    }

    public static String decrypt(String strToDecrypt, String secret) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
            SecretKeySpec secretKey = getKey(secret);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
    }
    private static SecretKeySpec getKey(String myKey) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        byte[] key = myKey.getBytes(CHARSET);
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        key = sha.digest(key);
        key = Arrays.copyOf(key, 16);
        return new SecretKeySpec(key, "AES");
    }
    /**
     * byte数组转化为16进制字符串
     * @param bytes
     * @return
     */
    private static String byteToHexString(byte[] bytes){
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String strHex=Integer.toHexString(bytes[i]);
            if(strHex.length() > 3){
                sb.append(strHex.substring(6));
            } else {
                if(strHex.length() < 2){
                    sb.append("0" + strHex);
                } else {
                    sb.append(strHex);
                }
            }
        }
        return  sb.toString();
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchPaddingException, UnsupportedEncodingException {
        String key = generateSecret(256);
        String enData = encrypt("你好测试hello", key);
        System.out.println(enData);
        String deData = decrypt(enData, key);
        System.out.println(deData);
        enData = encrypt("你好测试", key);
        System.out.println(enData);
        deData = decrypt(enData, key);
        System.out.println(deData);
    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是使用Java实现AES加密的工具类: ``` import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.security.MessageDigest; import java.util.Base64; public class AESUtils { public static final String AES_CBC_NOPADDING = "AES/CBC/NoPadding"; /** * AES加密 * * @param data 待加密数据 * @param key 密钥 * @param iv 偏移量 * @param mode 加密模式 * @param encoding 编码方式 * @return 加密后的数据 * @throws Exception */ public static String encrypt(String data, String key, String iv, String mode, String encoding) throws Exception { Cipher cipher = Cipher.getInstance(mode); int blockSize = cipher.getBlockSize(); byte[] dataBytes = data.getBytes(encoding); int plaintextLength = dataBytes.length; if (plaintextLength % blockSize != 0) { plaintextLength += blockSize - (plaintextLength % blockSize); } byte[] plaintext = new byte[plaintextLength]; System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length); SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); byte[] encrypted = cipher.doFinal(plaintext); return Base64.getEncoder().encodeToString(encrypted); } /** * AES解密 * * @param data 待解密数据 * @param key 密钥 * @param iv 偏移量 * @param mode 加密模式 * @param encoding 编码方式 * @return 解密后的数据 * @throws Exception */ public static String decrypt(String data, String key, String iv, String mode, String encoding) throws Exception { Cipher cipher = Cipher.getInstance(mode); SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); byte[] encrypted = Base64.getDecoder().decode(data); byte[] original = cipher.doFinal(encrypted); return new String(original, encoding); } /** * 生成AES密钥 * * @param length 密钥长度 * @return 密钥 * @throws Exception */ public static String generateAESKey(int length) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] keyBytes = md.digest("my-secret-key".getBytes("UTF-8")); byte[] truncatedKey = new byte[length]; System.arraycopy(keyBytes, 0, truncatedKey, 0, length); return Base64.getEncoder().encodeToString(truncatedKey); } } ``` 使用示例: ``` public static void main(String[] args) throws Exception { String data = "Hello, world!"; String key = AESUtils.generateAESKey(16); // 生成16位密钥 String iv = "1234567890123456"; // 偏移量 String mode = AESUtils.AES_CBC_NOPADDING; // 加密模式 String encoding = "UTF-8"; // 编码方式 String encrypted = AESUtils.encrypt(data, key, iv, mode, encoding); System.out.println("加密后的数据:" + encrypted); String decrypted = AESUtils.decrypt(encrypted, key, iv, mode, encoding); System.out.println("解密后的数据:" + decrypted); } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值