中文加解密异常的问题

 在使用AES加密时要注意指定字符编码,要使用String.getBypes(String charsetName)而不能使用String.getBytes(),后者源码中有一句:

String csn = Charset.defaultCharset().name();

Charset.defaultCharset()返回此Java虚拟机的默认字符集。

默认字符集在虚拟机启动期间确定,通常取决于基础操作系统的区域设置和字符集。

如果在加密和解密过程中环境发生变化,就可能导致中文字符解密后出现乱码

import lombok.SneakyThrows;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.security.Key;
import java.security.SecureRandom;

public class AesUtil {

    /**
     * 加密算法名称
     */
    private static final String CIPHER_ALGORITHM = "AES";

    /**
     * 密钥
     */
    private static final String KEY = "123456";


    /**
    *获取密钥Key 
    */
    public static Key getKey(String strKey) {
        try {
            if (strKey == null) {
                strKey = "";
            }
            KeyGenerator generator = KeyGenerator.getInstance(CIPHER_ALGORITHM);
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(strKey.getBytes());
            generator.init(128, secureRandom);
            return generator.generateKey();
        } catch (Exception e) {
            throw new RuntimeException(" 密钥出现异常 ");
        }
    }


    /**
     * AES加密
     * @param data 原文
     * @return 密文
     */
    @SneakyThrows
    public static String encrypt(String data){
        if(StringUtils.isEmpty(data)){
            return data;
        }
        SecureRandom secureRandom = new SecureRandom();
        Key secureKey = getKey(KEY);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secureKey, secureRandom);
        
        //这里需要指定编码,否则可能因环境问题出现解密乱码
        byte[] bytes = data.getBytes("utf-8");
        byte[] bt = cipher.doFinal(bytes);
        
        //加密后以base64编码后存储,这里使用的是Spring的Base64Utils
        String string = Base64Utils.encodeToString(bt);
        return string;
    }


    /**
     * AES解密
     * @param message 密文
     * @return 原文
     */
    @SneakyThrows
    public static String decrypt(String message){
        if(StringUtils.isEmpty(message)){
            return message;
        }
        SecureRandom secureRandom = new SecureRandom();
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        Key secureKey = getKey(KEY);
        cipher.init(Cipher.DECRYPT_MODE, secureKey, secureRandom);
     
        //先base64解码,这里使用的是Spring的Base64Utils
        byte[] bytes = Base64Utils.decodeFromString(message);
        byte[] res = cipher.doFinal(bytes);
 
        //这里需要指定编码,否则可能因环境问题出现解密乱码
        String data = new String(res,"utf-8");
        return data;
    }

    /**
    *测试
    */
    public static void main(String[] args) {
        String message = "北京是中华人民共和国首都";
        System.out.println("原文信息:"+message);
        System.out.println("原文长度:"+message.length());
         
        //加密
        String encryptMsg = encrypt(message);
        System.out.println("加密信息:"+encryptMsg);
        System.out.println("密文长度:"+encryptMsg.length());
   
        //解密
        String decryptedMsg = decrypt(encryptMsg);
        System.out.println("解密信息:"+decryptedMsg);

        //验证解密信息和原文是否相等
        System.out.println(message.equals(decryptedMsg));
    }


}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值