加解密:AES/CBC/PKCS7Padding/Hex - JAVA代码
in 默认分类 with 0 comment 0 views

加解密:AES/CBC/PKCS7Padding/Hex - JAVA代码

in 默认分类 with 0 comment 0 views

按照网上的示例简单改了下,可使用该网站校验:https://www.ssleye.com/aes_cipher.html

maven依赖:

        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.55</version>
        </dependency>

代码:

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;
import java.util.Arrays;

/**
 * @author Admin
 */
@Component
public class AesUtil {
    private Key key;
    private Cipher cipher;

    @Value("${aes.key}")
    private String keyStr;
    @Value("${aes.vi}")
    private String ivStr;

    public void init() throws Exception{
        byte[] keyBytes = keyStr.getBytes();
        // 如果密钥不足16位,那么就补足.  这个if 中的内容很重要
        int base = 16;
        if (keyBytes.length % base != 0) {
            int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
            keyBytes = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        // 转化成JAVA的密钥格式
        key = new SecretKeySpec(keyBytes, "AES");
        // 初始化cipher
        cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
    }

    /**
     * 加密方法
     * @param content  要加密的字符串
     * @return
     */
    public String encrypt(String content) throws Exception {
        init();
        cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(ivStr.getBytes()));
        byte[] encryptedText = cipher.doFinal(content.getBytes());
        return new String(Hex.encode(encryptedText)).toUpperCase();
    }

    /**
     * 解密方法
     * @param content 要解密的字符串
     * @return
     */
    public String decrypt(String content) throws Exception{
        init();
        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivStr.getBytes()));
        byte[] encryptedText = cipher.doFinal(Hex.decode(content.getBytes()));
        return new String(encryptedText);
    }

}
Responses