AESUtis.java 1.75 KB
package com.lhcredit.common.utils.oss;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Base64;

public class AESUtis {
    private static final String ALGORITHM = "AES";
    private static final byte[] keyValue ="Lhzx1234Lhzx1234".getBytes();
    public static String encrypt(String valueToEnc)  {
        try{
            Key key = generateKey();
            Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.ENCRYPT_MODE, key);
            byte[] encValue = c.doFinal(valueToEnc.getBytes(StandardCharsets.UTF_8));
            // 可选地,对加密后的字节进行Base64编码以便于文本显示和传输
            String encryptedValue = Base64.getEncoder().encodeToString(encValue);
            return encryptedValue;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String encryptedValue)   {
        try{
            Key key = generateKey();
            Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.DECRYPT_MODE, key);
            // 先将Base64编码的字符串解码回字节数组
            byte[] decordedValue = Base64.getDecoder().decode(encryptedValue);
            byte[] decValue = c.doFinal(decordedValue);
            String decryptedValue = new String(decValue, StandardCharsets.UTF_8);
            return decryptedValue;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    private static Key generateKey()   {
        try{
            Key key = new SecretKeySpec(keyValue, ALGORITHM);
            return key;
        }catch (Exception e){

        }
        return null;
    }
}