java1.8 使用AES/DES加密算法,打包运行后加密算法不可用的解决方案

java1.8 使用AES/DES加密算法,打包运行后加密算法不可用的解决方案

问题描述:

项目中使用了AES/DES算法,本地调试没有问题,结果使用maven打包运行后,报异常:java.security.NoSuchAlgorithmException: AES SecretKeyFactory not available
网上找了很久一直没找到满意的解决方案,最终自己结合多篇文章自己写了一个工具类。

问题根源:

JDK自带的AES、DES等加密算法在使用时需要额外引入jar包进行实例化。

代码:

依赖:

		<dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>com.springsource.org.bouncycastle.jce</artifactId>
            <version>1.46.0</version>
        </dependency>
 
 

代码:

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.Arrays;

public class AesEncoder {
    /**
     * init AES Cipher
     *
     * @param aesKey     加密解密需要的key
     * @param cipherMode 初始化 Cipher 的类型(加密/解密)
     * @return 返回初始化的对象
     */
    private static Cipher initAESCipher(String aesKey, int cipherMode) {
		Cipher cipher = null;
        try {
            SecretKey key = getKey(aesKey);
            cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            cipher.init(cipherMode, key);
        } catch (NoSuchAlgorithmException e) {
			e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (InvalidKeyException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return cipher;
    }

	private static SecretKey getKey(String password) {
        int keyLength = 256;
        byte[] keyBytes = new byte[keyLength / 8];
        SecretKeySpec key = null;
        try {
            Arrays.fill(keyBytes, (byte) 0x0);
            //这里是核心,需要额外引入jar包提供 Provider 否则加密算法在打成jar包后会报错
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            byte[] passwordBytes = password.getBytes("UTF-8");
			int length = passwordBytes.length < keyBytes.length ? passwordBytes.length : keyBytes.length;
            System.arraycopy(passwordBytes, 0, keyBytes, 0, length);
            key = new SecretKeySpec(keyBytes, "AES");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return key;
    }

	/**
     * 加密
     *
     * @param content 需要加密的内容
     * @param aesKey  加密密码
     * @return 返回加密结果
     */
    public static byte[] encrypt(String content, String aesKey) {
        try {
            Cipher cipher = initAESCipher(aesKey, Cipher.ENCRYPT_MODE);
            byte[] byteContent = content.getBytes("utf-8");
			byte[] result = cipher.doFinal(byteContent);
            return result; // 加密
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
	/**
     * 解密
     *
     * @param content 待解密内容
     * @param aesKey  解密密钥
     * @return
     */
    public static byte[] decrypt(byte[] content, String aesKey) {
        try {
            Cipher cipher = initAESCipher(aesKey, Cipher.DECRYPT_MODE);
            byte[] result = cipher.doFinal(content);
            return result;
		} catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String bytesToHexString(byte[] src) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < src.length; i++) {
 			String hex = Integer.toHexString(src[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }
    
	/**
     * 加密 成字符串形式
     *
     * @param content 需要加密的内容
     * @param aesKey  加密密码
     * @return 返回加密结果
     */
    public static String encryptToStr(String content, String aesKey) {
        return bytesToHexString(encrypt(content, aesKey));
    }
    
	/**
     * 字符串类型 解密
     *
     * @param content 待解密内容
     * @param keyWord 解密密钥
     * @return
     */
    public static byte[] decrypt(String content, String keyWord) {
        return decrypt(hexStringToBytes(content), keyWord);
    }

	public static byte[] hexStringToBytes(String hexString) {
        if (hexString.length() < 1)
            return null;
        byte[] result = new byte[hexString.length() / 2];
        for (int i = 0; i < hexString.length() / 2; i++) {
            int high = Integer.parseInt(hexString.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexString.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
    
	public static void main(String[] args) {
        String s = encryptToStr("123456", "@12345");
        System.out.println("加密:");
        System.out.println(s);
        byte[] decrypt = decrypt(s, "@12345");
        System.out.println(new String(decrypt));
    }
}

解决方法二:

运行jar包时使用 “-Djava.ext.dirs=” 参数时,请额外指定“%JAVA_HOME%/jre/lib/ext”目录,例:-Djava.ext.dirs="%JAVA_HOME%/jre/lib/ex";config (config为项目运行需要指定的额外依赖目录)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
DES加密算法是一种对称加密算法JAVA提供了DES加密算法的实现。下面是一个使用DES加密算法JAVA代码示例: ```java import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import java.security.SecureRandom; public class DESUtil { //加密算法 private static final String ALGORITHM = "DES"; //加密方法 private static final String ENCRYPT_MODE = "DES/ECB/PKCS5Padding"; /** * DES加密 * * @param data 待加密数据 * @param key 密钥 * @return 加密后的数据 */ public static byte[] encrypt(byte[] data, byte[] key) throws Exception { //生成密钥 DESKeySpec desKeySpec = new DESKeySpec(key); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); //加密 Cipher cipher = Cipher.getInstance(ENCRYPT_MODE); cipher.init(Cipher.ENCRYPT_MODE, secretKey, new SecureRandom()); return cipher.doFinal(data); } /** * DES解密 * * @param data 待解密数据 * @param key 密钥 * @return 解密后的数据 */ public static byte[] decrypt(byte[] data, byte[] key) throws Exception { //生成密钥 DESKeySpec desKeySpec = new DESKeySpec(key); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); //解密 Cipher cipher = Cipher.getInstance(ENCRYPT_MODE); cipher.init(Cipher.DECRYPT_MODE, secretKey, new SecureRandom()); return cipher.doFinal(data); } } ``` 使用示例: ```java public class Main { public static void main(String[] args) throws Exception { String str = "Hello, World!"; byte[] key = "12345678".getBytes(); byte[] data = str.getBytes(); //加密 byte[] encrypted = DESUtil.encrypt(data, key); System.out.println("加密后:" + new String(encrypted)); //解密 byte[] decrypted = DESUtil.decrypt(encrypted, key); System.out.println("解密后:" + new String(decrypted)); } } ``` 注意:使用DES加密算法时,密钥长度必须为8字节。如果需要更高的安全性,可以使用3DESAES加密算法

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值