java.security.InvalidKeyException Illegal key size
博客专区 > sg4567 的博客 > 博客详情
java.security.InvalidKeyException Illegal key size
sg4567 发表于8个月前
java.security.InvalidKeyException Illegal key size
  • 发表于 8个月前
  • 阅读 19
  • 收藏 0
  • 点赞 0
  • 评论 1

【腾讯云】如何购买服务器最划算?>>>   

项目中使用aes加密算法,密钥只有16位可以通过,32位报错java.security.InvalidKeyException Illegal key size。

解决方案:http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html 下载两个jar包,替换D:\Java\jre7\lib\security下同名的文件即可。

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AesEncodeUtil {

    private final static Logger logger = LoggerFactory.getLogger(AesEncodeUtil.class.getName());
    public final String VIPARA = "0200010700020204"; // 偏移量
    public final String bm = "UTF-8";
    public String ASE_PASSWORD = "";

    public AesEncodeUtil(String key) {
        ASE_PASSWORD = key;
    }

    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 加密
     *
     * @param cleartext
     * @return
     * @throws NoSuchPaddingException
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     * @throws InvalidAlgorithmParameterException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     */
    public String encrypt(String cleartext) throws Exception {

        /**
         * 实例化 使用 PKCS7PADDING 填充方式,按如下方式实现,就是调用bouncycastle组件实现
         * Cipher.getInstance(CIPHER_ALGORITHM,"BC")
         */
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        // 防止linux下 随机生成key
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(ASE_PASSWORD.getBytes());
        kgen.init(128, secureRandom);
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        // SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        SecretKeySpec key = new SecretKeySpec(ASE_PASSWORD.getBytes("utf-8"), "AES");
        IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes());
        // SecretKeySpec key = new SecretKeySpec(
        // ASE_PASSWORD.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
        byte[] encryptedData = cipher.doFinal(cleartext.getBytes(bm));

        return parseByte2HexStr(Base64.encodeBase64(encryptedData));
    }

    /**
     * 解密
     *
     * @param encrypted
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     * @throws NoSuchPaddingException
     * @throws InvalidAlgorithmParameterException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     */
    public String decrypt(String encrypted) throws Exception {

        /**
         * 实例化 使用 PKCS7PADDING 填充方式,按如下方式实现,就是调用bouncycastle组件实现
         * Cipher.getInstance(CIPHER_ALGORITHM,"BC")
         */
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        // 防止linux下 随机生成key
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(ASE_PASSWORD.getBytes());
        kgen.init(128, secureRandom);
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        encrypted = URLDecoder.decode(encrypted, "utf-8");
        byte[] byteMi = Base64.decodeBase64(parseHexStr2Byte(encrypted));
        logger.debug("aes decrypt base64:{}", new String(byteMi));
        IvParameterSpec zeroIv = new IvParameterSpec(VIPARA.getBytes("utf-8"));
        // SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        SecretKeySpec key = new SecretKeySpec(ASE_PASSWORD.getBytes("utf-8"), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
        byte[] decryptedData = cipher.doFinal(byteMi);
        return new String(decryptedData, bm);
    }
}

 

标签: java aes
共有 人打赏支持
粉丝 0
博文 12
码字总数 1290
评论 (1)
sg4567
properties-〉libraries->jre system library->更新后的jre
×
sg4567
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: