AES256Encryption AES 256位加密算法

时间:2022-11-26 18:32:37

Java jce对aes算法有很好的支持,但是默认安装的JDK或者JRE是不能支持aes192bit密钥和aes256bit密钥两种算法的,需要到sun官方下载Java(TM) Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files以下是jce unilimited strength jurisdiction policy files 6的官方下载地址:
 http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html

下载后解压文件,将里面的文件拷贝到
 
                <java-home>/lib/security            [Unix]
                <java-home>/lib/security           [Win32]
 
覆盖原先的jar文件,请先备份原先的jar文件,以防你需要恢复密钥长度的限制,这里需要注意的是如果是安装的jdk,jdk目录中的jre下面的lib/security下的文件也需要覆盖。完成这个步骤之后就可以使用不限制密钥长度的aes算法了,简单的实现代码如下:



package com.ourpalm.pay.utils.openXLive;



import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.Security;
 
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.ourpalm.pay.utils.anzhi.Base64;
 
public class AES256Encryption{
     
         /**
         * 密钥算法
         * java6支持56位密钥,bouncycastle支持64位
         * */
        public static final String KEY_ALGORITHM="AES";
           
        /**
         * 加密/解密算法/工作模式/填充方式
         *
         * JAVA6 支持PKCS5PADDING填充方式
         * Bouncy castle支持PKCS7Padding填充方式
         * */
        public static final String CIPHER_ALGORITHM="AES/CBC/PKCS7Padding";
           
        /**
         *
         * 生成密钥,java6只支持56位密钥,bouncycastle支持64位密钥
         * @return byte[] 二进制密钥
         * */
        public static byte[] initkey() throws Exception{
               
//          //实例化密钥生成器
//          Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//          KeyGenerator kg=KeyGenerator.getInstance(KEY_ALGORITHM, "BC");
//          //初始化密钥生成器,AES要求密钥长度为128位、192位、256位
////            kg.init(256);
//          kg.init(128);
//          //生成密钥
//          SecretKey secretKey=kg.generateKey();
//          //获取二进制密钥编码形式
//          return secretKey.getEncoded();
            //为了便于测试,这里我把key写死了,如果大家需要自动生成,可用上面注释掉的代码
            return new byte[] { 0x08, 0x08, 0x04, 0x0b, 0x02, 0x0f, 0x0b, 0x0c,
                    0x01, 0x03, 0x09, 0x07, 0x0c, 0x03, 0x07, 0x0a, 0x04, 0x0f,
                    0x06, 0x0f, 0x0e, 0x09, 0x05, 0x01, 0x0a, 0x0a, 0x01, 0x09,
                    0x06, 0x07, 0x09, 0x0d };
        }
 
        /**
         * 转换密钥
         * @param key 二进制密钥
         * @return Key 密钥
         * */
        public static Key toKey(byte[] key) throws Exception{
            //实例化DES密钥
            //生成密钥
            SecretKey secretKey=new SecretKeySpec(key,KEY_ALGORITHM);
            return secretKey;
        }
           
        /**
         * 加密数据
         * @param data 待加密数据
         * @param key 密钥
         * @param ivStr 加密向量
         * @return byte[] 加密后的数据
         * */
        public static byte[] encrypt(byte[] data,byte[] key,String ivStr) throws Exception{
            //还原密钥
            Key k=toKey(key);
            /**
             * 实例化
             * 使用 PKCS7PADDING 填充方式,按如下方式实现,就是调用bouncycastle组件实现
             * Cipher.getInstance(CIPHER_ALGORITHM,"BC")
             */
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM, "BC");
            //初始化,设置为加密模式
            IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes("utf-8"));
            cipher.init(Cipher.ENCRYPT_MODE, k,iv);
            //执行操作
            return cipher.doFinal(data);
        }
        /**
         * 解密数据
         * @param data 待解密数据
         * @param key 密钥
         * @return byte[] 解密后的数据
         * */
        public static byte[] decrypt(byte[] data,byte[] key) throws Exception{
            //欢迎密钥
            Key k =toKey(key);
            /**
             * 实例化
             * 使用 PKCS7PADDING 填充方式,按如下方式实现,就是调用bouncycastle组件实现
             * Cipher.getInstance(CIPHER_ALGORITHM,"BC")
             */
            Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM);
            //初始化,设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, k);
            //执行操作
            return cipher.doFinal(data);
        }
        /**
         * @param args
         * @throws UnsupportedEncodingException
         * @throws Exception
         */
        public static void main(String[] args) throws UnsupportedEncodingException{
             
            String str="customerid=838f3fd0-b030-4c2e-9f00-aec4ff1ceb12&deviceid=202226209086055177097011149197069193223118190142182089140026&ipaddress=211.89.10.128&isanonymous=true&orderid=2012082900005&product_0_id=Y10000007&product_0_quantity=1&supplierid=100002&supplierorderid=201401201987&tag=test";
            System.out.println("原文:"+str);
 
            //初始化密钥
            byte[] key;
            try {
//                key = AES256Encryption.initkey();
                key = "QQDYpAZduJISYm7PowsSx+jsKfbZtb+f".getBytes("utf-8");
                System.out.print("密钥:");
                for(int i = 0;i<key.length;i++){
                    System.out.printf("%x", key[i]);
                }
                System.out.print("\n");
                //加密数据
                byte[] data=AES256Encryption.encrypt(str.getBytes(), key,"1000023f72bddc68");
                System.out.println(Base64.encodeToString(data));
                System.out.print("加密后:"+Base64.encodeToString(data).equals("rQAHdRlNkBpAZFOJt3Pw9Y1cfdyc+LETBh6+jmcLUZPzS8gRPQrEG5Up0mLJRxJLH82VBaRGqOWRekoCCi/l2Iqpa95MBkPELvgKSBiS84aZkZGSgD2dgL2uLwZ/NbiOIyJjOn7pfiDt03Aa8eqdMLZsTfIxKy56aEmlAHoOjQ2hpOH0dF5GVxW/wO+Ds1kYX4XoUm2rDMOYLcq8mvfKJ21x8kNDnQF028tCoKVZZovoZAFYE3e5zGug3RyrTys8TQL5i8xTmqVXU3bnAVswRFRFVSyDEbBJKB27A2h4TiQ1XXksRt35Mm6id1MAikVIUVieihDPZwnkcGNHeYMWW+Auq4aUnjL1X+IUV+rrG3G57GCVEbHtfS9Ofmwg6fOP"));
          /*      for(int i = 0;i<data.length;i++){
                    System.out.printf("%x", data[i]);
                }*/
             /*   System.out.print("\n");
                 
                //解密数据
                data=AES256Encryption.decrypt(data, key);
                System.out.println("解密后:"+new String(data));*/
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
              
        }
    }