Java AES 加密在Windows和linux不同

Java AES 加密在Windows和linux不同

原因
1. SecureRandom 类中 setSeed()底层调用的是 native 方法.所以造成了不同环境之间随机数出现了差别。导致解密不一致问题。
2. 由于linux和window的内核不同造成的!

解决:对加密程序 添加如下两行 代码控制 随机数即可解决问题。然后初始化,就能解决这个问题!

SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(PASSWORD.getBytes());

示例如下

package com.lyh;


import java.security.SecureRandom;


import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


import org.apache.axis.encoding.Base64;
import org.apache.commons.lang.StringUtils;


import lombok.extern.slf4j.Slf4j;


@Slf4j
public class AESUtils {


    /**
     * 加密
     * 
     * @param content 需要加密的内容
     * @param secureKey 加密秘钥
     * @return
     */
    public static String encrypt(String content, String secureKey) {
        try {
            if (StringUtils.isEmpty(content) 
                        || StringUtils.isEmpty(secureKey)) {
                return null;
            }


            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            /*
             * 问题我已自己解决,这个是由于linux和window的内核不同造成的!
             * SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
             * secureRandom.setSeed(PASSWORD.getBytes());
             * 然后初始化,就能解决这个问题!
             */
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(secureKey.getBytes());
            kgen.init(128, secureRandom);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器 
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化 
            byte[] result = cipher.doFinal(byteContent);
            return encodeBASE64(result); // 加密 
        } catch (Exception e) {
            log.error("加密错误.", e);
        }
        return null;
    }


    /**
     * 解密
     * 
     * @param content 待解密内容
     * @param password secureKey
     * @return
     */
    public static String decrypt(String content, String secureKey) {
        try {
            if (StringUtils.isEmpty(content) || StringUtils.isEmpty(secureKey)) {
                return null;
            }

            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(secureKey.getBytes());
            kgen.init(128, secureRandom);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器 
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化 
            byte[] base64Dec = Base64.decode(content);
            byte[] result = cipher.doFinal(base64Dec);
            return new String(result);
        } catch (Exception e) {
            log.warn("解密错误,错误信息是:{}", e);
        }
        return null;
    }

    public static String encodeBASE64(byte[] content) throws Exception {
        if (content == null || content.length == 0)
            return null;
        try {
            return Base64.encode(content);
        } catch (Exception e) {
            log.error("Base64 encode error.", e);
            return null;
        }
    }

}
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Java程序在Linux服务器上运行时,如果使用AES加密并使用256位密钥,则可能会出现“java.security.InvalidKeyException: Illegal key size or default parameters”的异常。这是因为默认情况下,Java不允许使用256位密钥进行加密。要解决此问题,需要执行以下步骤: 1.下载Java Cryptography Extension (JCE) Unlimited Jurisdiction Policy Files。这些文件包含允许使用256密钥的策略文件。 2.解压缩下载的文件,并将其中的两个JAR文件(local_policy.jar和US_export_policy.jar)复制到$JAVA_HOME/jre/lib/security目录中。如果该目录中已经存在这些文件,请备份它们并替换为新文件。 3.重新启动Java应用程序并尝试使用256位密钥进行AES加密。 下面是一个示例代码,演示如何使用256位密钥进行AES加密: ```java import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class AesEncryptionExample { private static final String ALGORITHM = "AES"; private static final String KEY = "0123456789abcdef0123456789abcdef"; public static String encrypt(String value) throws Exception { SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, keySpec); byte[] encryptedValue = cipher.doFinal(value.getBytes()); return Base64.getEncoder().encodeToString(encryptedValue); } public static String decrypt(String value) throws Exception { SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, keySpec); byte[] decodedValue = Base64.getDecoder().decode(value); byte[] decryptedValue = cipher.doFinal(decodedValue); return new String(decryptedValue); } public static void main(String[] args) throws Exception { String originalValue = "Hello World!"; String encryptedValue = encrypt(originalValue); String decryptedValue = decrypt(encryptedValue); System.out.println("Original Value: " + originalValue); System.out.println("Encrypted Value: " + encryptedValue); System.out.println("Decrypted Value: " + decryptedValue); } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值