码迷,mamicode.com
首页 > 编程语言 > 详细

java AES加密解密

时间:2017-01-12 12:29:21      阅读:46      评论:0      收藏:0      [点我收藏+]

标签:nop   except   import   blocks   java   color   instance   throws   block   

  近些年DES使用越来越少,原因就在于其使用56位密钥,比较容易被破解,近些年来逐渐被AES替代,AES已经变成目前对称加密中最流行算法之一;AES可以使用128、192、和256位密钥,并且用128位分组加密和解密数据。本文就简单介绍如何通过JAVA实现AES加密。
 
 
因为在做接口 webservice的时候接受穿过的数据 是xml 加密为二进制 byte[]   下面直接看代码 :

import java.io.UnsupportedEncodingException;

import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;

import java.security.SecureRandom;

 

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.SecretKeySpec;

 

public class AESUtil1 {

 

      /*

     * 算法/模式/填充 16字节加密后数据长度 不满16字节加密后长度

     * AES/CBC/NoPadding 16 不支持

     * AES/CBC/PKCS5Padding 32 16

     * AES/CBC/ISO10126Padding 32 16

     * AES/CFB/NoPadding 16 原始数据长度

     * AES/CFB/PKCS5Padding 32 16

     * AES/CFB/ISO10126Padding 32 16

     * AES/ECB/NoPadding 16 不支持

     * AES/ECB/PKCS5Padding 32 16

     * AES/ECB/ISO10126Padding 32 16

     * AES/OFB/NoPadding 16 原始数据长度

     * AES/OFB/PKCS5Padding 32 16

     * AES/OFB/ISO10126Padding 32 16

     * AES/PCBC/NoPadding 16 不支持

     * AES/PCBC/PKCS5Padding 32 16

     * AES/PCBC/ISO10126Padding 32 16

     *

     * 注:

     * 1、JCE中AES支持五中模式:CBC,CFB,ECB,OFB,PCBC;支持三种填充:NoPadding,PKCS5Padding,ISO10126Padding。 不带模式和填充来获取AES算法的时候,其默认使用ECB/PKCS5Padding。

     * 2、Java支持的密钥长度:keysize must be equal to 128, 192 or 256

     * 3、Java默认限制使用大于128的密钥加密(解密不受限制),报错信息:java.security.InvalidKeyException: Illegal key size or default parameters

     * 4、下载并安装JCE Policy文件即可突破128密钥长度的限制:覆盖jre\lib\security目录下local_policy.jar、US_export_policy.jar文件即可

     * 5、除ECB外,需提供初始向量(IV),如:Cipher.init(opmode, key, new IvParameterSpec(iv)), 且IV length: must be 16 bytes long

     */

 

 

      public static SecretKeySpec bulidKey(String password) throws NoSuchAlgorithmException {

            KeyGenerator kgen = KeyGenerator.getInstance("AES");     //AES 加密  默认的是这种  ECB/PKCS5Padding

            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");    //SHA1PRANG 就是一种算法的名称    这里使用据说有补位的作用可以适应不同机器 所以要用就用着这一种

        secureRandom.setSeed(password.getBytes());        //  根据种子password.getBytes() 获取随机值 可以单用     SecureRandom 继承 Random

            kgen.init(128, secureRandom);

            SecretKey secretKey = kgen.generateKey();               //下面就是生成加密的key了

            byte[] enCodeFormat = secretKey.getEncoded();

            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");

            return key;

      }

 

      /**

       * 加密

       *

       * @param content

       *            需要加密的内容

       * @param password

       *            加密密码

       * @return

       */

      public static byte[] encrypt(String content, String password) {

            try {

                  SecretKeySpec key = bulidKey(password);

                  Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器

                  cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化

 

                  byte[] byteContent = content.getBytes("gbk");    //这里是应编码了 可以不写gbk 就是用的默认编码这样的话 下面的解密gbk 也要去掉

                  byte[] result = cipher.doFinal(byteContent);

                  return result; // 加密

            } catch (NoSuchAlgorithmException e) {

                  e.printStackTrace();

            } catch (NoSuchPaddingException e) {

                  e.printStackTrace();

            } catch (InvalidKeyException e) {

                  e.printStackTrace();

            } catch (UnsupportedEncodingException e) {

                  e.printStackTrace();

            } catch (IllegalBlockSizeException e) {

                  e.printStackTrace();

            } catch (BadPaddingException e) {

                  e.printStackTrace();

            }

            return null;

      }

 

 

 

 

      //   进行加密 并返回16进制的内容

      public static String encrypt2Str(String content, String password) {

                  return parseByte2HexStr(encrypt(content,password)); // 加密

      }

 

      /**

       * 解密

       *

       * @param content

       *            待解密内容

       * @param password

       *            解密密钥

       * @return

       */

      public static byte[] decrypt(byte[] content, String password) {

            try {

                  SecretKeySpec key = bulidKey(password);

                  Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器

                  cipher.init(Cipher.DECRYPT_MODE, key);// 初始化

                  byte[] result = cipher.doFinal(content);

                  return result; // 解密

            } catch (NoSuchAlgorithmException e) {

                  e.printStackTrace();

            } catch (NoSuchPaddingException e) {

                  e.printStackTrace();

            } catch (InvalidKeyException e) {

                  e.printStackTrace();

            } catch (IllegalBlockSizeException e) {

                  e.printStackTrace();

            } catch (BadPaddingException e) {

                  e.printStackTrace();

            }

            return null;

      }

 

 

      public static String decryptString(byte[]content,String password) throws UnsupportedEncodingException {

            return new String(decrypt(content,password),"gbk");

 

 

      }

 

 

 

 

 

 

      //将加密后的16进制 转化为二进制 再解密  并编码为字符串

      public static String decryptStr(String content, String password) {

            byte[] decryptFrom = parseHexStr2Byte(content);

            byte[] decryptResult = decrypt(decryptFrom, password);

            String result = "--";

            try {

                  result = new String(decryptResult,"gbk");

            } catch (UnsupportedEncodingException e) {

                  e.printStackTrace();

            }

            return result;

      }

 

      /**

       * 将二进制转换成16进制

       *

       * @param buf

       * @return

       */

      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();

      }

 

      /**

       * 将16进制转换为二进制

       *

       * @param hexStr

       * @return

       */

      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;

      }

 

      public static void main(String[] args) throws UnsupportedEncodingException {

            String content = "山东省济南市槐荫区中大办事处裕华里";

            String password = "bc29c2f94e0e0355c346892a45bc2b42";

            // 加密971436EC53EED78C0A942FCA7900E1E7F13527CB29268B9B52DA3A6C7F804C1825AF87A0B8F550DE09055D42BED07EB7:长度:96

            System.out.println("加密前:" + content);

            byte[] encryptResult = encrypt(content, password);

            String encryptResultStr = parseByte2HexStr(encryptResult);

 

            System.out.println("加密后:" + encryptResultStr+":长度:"+encryptResultStr.length());

            // 解密

            String decryptResult = decryptStr(encryptResultStr, password);

            System.out.println("解密后:" + decryptResult);

 

            //--------------------------------------

 

            String aa=decryptString(encryptResult,password);

            System.out.println("===直接接受过来的二进制数据解密:"+aa);

 

      }

}
 
 
 
//第二种和第一种类似 加密方式由EBC 改成 CBC  增加了向量  每太明白可能就是增加复杂度吧  

//这个是写借口的时候 我用java 别人用的是别的语言 AES加密对应不上 别人提供的 如果没有汉字就对上了 ,有了汉字加密后的16进制也是不一样的 
//想到的办法是用  URLEncorder.encode("汉字")  进行转码  或者这里面提供的把汉字转换为二进制




import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

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;

public class AESUtil2 {

    /*
     * 算法/模式/填充 16字节加密后数据长度 不满16字节加密后长度
     * AES/CBC/NoPadding 16 不支持
     * AES/CBC/PKCS5Padding 32 16
     * AES/CBC/ISO10126Padding 32 16
     * AES/CFB/NoPadding 16 原始数据长度
     * AES/CFB/PKCS5Padding 32 16
     * AES/CFB/ISO10126Padding 32 16
     * AES/ECB/NoPadding 16 不支持
     * AES/ECB/PKCS5Padding 32 16
     * AES/ECB/ISO10126Padding 32 16
     * AES/OFB/NoPadding 16 原始数据长度
     * AES/OFB/PKCS5Padding 32 16
     * AES/OFB/ISO10126Padding 32 16
     * AES/PCBC/NoPadding 16 不支持
     * AES/PCBC/PKCS5Padding 32 16
     * AES/PCBC/ISO10126Padding 32 16
     *
     * 注:
     * 1、JCE中AES支持五中模式:CBC,CFB,ECB,OFB,PCBC;支持三种填充:NoPadding,PKCS5Padding,ISO10126Padding。 不带模式和填充来获取AES算法的时候,其默认使用ECB/PKCS5Padding。
     * 2、Java支持的密钥长度:keysize must be equal to 128, 192 or 256
     * 3、Java默认限制使用大于128的密钥加密(解密不受限制),报错信息:java.security.InvalidKeyException: Illegal key size or default parameters
     * 4、下载并安装JCE Policy文件即可突破128密钥长度的限制:覆盖jre\lib\security目录下local_policy.jar、US_export_policy.jar文件即可
     * 5、除ECB外,需提供初始向量(IV),如:Cipher.init(opmode, key, new IvParameterSpec(iv)), 且IV length: must be 16 bytes long
     */
    private static String ALGORITHM = "AES";
    private static int keySize = 128;
    private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";

    public static SecretKeySpec bulidKey(String password) throws NoSuchAlgorithmException {
        KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM);
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); 
        secureRandom.setSeed(password.getBytes());
        kgen.init(keySize, secureRandom);
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
        return key;
    }

    /**
     * 加密
     *
     * @param content
     *            需要加密的内容
     * @param password
     *            加密密码
     * @return
     */
    public static byte[] encrypt(String content, String password) {
        try {
            SecretKeySpec key = bulidKey(password);
            String iv = "jssjbyfkzzxsyjcs";//初始化向量参数,AES 为16bytes. DES 为8bytes.
            IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());     //增加了向量 这就是上面一个不用的地方
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);// 创建密码器
            cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);// 初始化
            byte[] byteContent = content.getBytes("gbk");
            byte[] result = cipher.doFinal(byteContent);
            return result; // 加密
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 加密
     *
     * @param content
     *            需要加密的内容
     * @param password
     *            加密密码
     * @return
     */
    public static String encrypt2Str(String content, String password) {
            return parseByte2HexStr(encrypt(content,password)); // 加密
    }

    /**
     * 解密
     *
     * @param content
     *            待解密内容
     * @param password
     *            解密密钥
     * @return
     */
    public static byte[] decrypt(byte[] content, String password) {
        try {
            SecretKeySpec key = bulidKey(password);
            String iv = "jssjbyfkzzxsyjcs";//初始化向量参数,AES 为16bytes. DES 为8bytes.
            IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);// 初始化
            byte[] result = cipher.doFinal(content);
            return result; // 解密
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     *
     * @param content
     *            待解密内容
     * @param password
     *            解密密钥
     * @return
     */
    public static String decryptStr(String content, String password) {
        byte[] decryptFrom = parseHexStr2Byte(content);
        byte[] decryptResult = decrypt(decryptFrom, password);
        String result = "--";
        try {
            result = new String(decryptResult,"gbk");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    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();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    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;
    }


    public static void main(String[] args) {
        String content = "山东省济南市槐荫区中大办事处裕华里";
        String password = "bc29c2f94e0e0355c346892a45bc2b42";
        // 加密971436EC53EED78C0A942FCA7900E1E7F13527CB29268B9B52DA3A6C7F804C1825AF87A0B8F550DE09055D42BED07EB7:长度:96
        System.out.println("加密前:" + content);
        byte[] encryptResult = encrypt(content, password);
        String encryptResultStr = parseByte2HexStr(encryptResult);
        System.out.println("加密后:" + encryptResultStr+":长度:"+encryptResultStr.length());
        // 解密
        String decryptResult = decryptStr(encryptResultStr, password);
        System.out.println("解密后:" + decryptResult);
    }
}

  

 

//第三种   就是key的生成不同了  不是用  SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); 她生成的


import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class AESTest {

    public static void main(String args[]){
        System.out.println(System.getProperty("file.encoding"));
        String content = "123456781234567812345678";
        String password = "12345678";

        System.out.println("加密前" + content);
        byte[] encryptResult = encrypt(content, password,16);
        System.out.println("加密后的16进制" + parseByte2HexStr(encryptResult));

        byte[] decryptResult = decrypt(encryptResult,password,16);
        System.out.println("解密后" + new String(decryptResult));


    }

  //加密
    public static byte[] encrypt(String content, String password, int keySize) {
            try {                             
                SecretKeySpec key = new SecretKeySpec(ZeroPadding(password.getBytes(), keySize), "AES");
                Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
                byte[] byteContent = content.getBytes();
                cipher.init(Cipher.ENCRYPT_MODE, key);
                byte[] result = cipher.doFinal(byteContent);
                return result;
            } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                    e.printStackTrace();
            } catch (InvalidKeyException e) {
                    e.printStackTrace();
            } catch (IllegalBlockSizeException e) {
                    e.printStackTrace();
            } catch (BadPaddingException e) {
                    e.printStackTrace();
            }
            return null;
    }

 //解密
    public static byte[] decrypt(byte[] content, String password, int keySize) {
            try {
                SecretKeySpec key = new SecretKeySpec(ZeroPadding(password.getBytes(), keySize), "AES");
                Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
                cipher.init(Cipher.DECRYPT_MODE, key);
                byte[] result = cipher.doFinal(content);
                return result;
            } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                    e.printStackTrace();
            } catch (InvalidKeyException e) {
                    e.printStackTrace();
            } catch (IllegalBlockSizeException e) {
                    e.printStackTrace();
            } catch (BadPaddingException e) {
                    e.printStackTrace();
            }
            return null;
    }



    //16进制转化为二进制
    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();
    }

   //二进制转化为16进制
    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;
    }


    //最上方key生成需要的东西 这里是种子一定补全到128位   在下面个例子 password密码就不能随便写 就是因为没有这个
    public static byte[] ZeroPadding(byte[] in,Integer blockSize){
        Integer copyLen = in.length;
        if (copyLen > blockSize) {
            copyLen = blockSize;
        }
        byte[] out = new byte[blockSize];
        System.arraycopy(in, 0, out, 0, copyLen);
        return out;
    }

}
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

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.SecretKeySpec;

public class AESTest {

    /**
     * 加密
     *
     * @param content
     *            需要加密的内容
     * @param password
     *            加密密码
     * @return
     */
    public static byte[] encrypt(String content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(password.getBytes()));
            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 result; // 加密
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     *
     * @param content
     *            待解密内容
     * @param password
     *            解密密钥
     * @return
     */
    public static byte[] decrypt(byte[] content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(password.getBytes()));
            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[] result = cipher.doFinal(content);
            return result; // 加密
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String args[]) {

        String content = "te大st";
        String password = "12345678";
        // 加密
        System.out.println("加密前:" + content);
        byte[] encryptResult = encrypt(content, password);
        // 解密
        byte[] decryptResult = decrypt(encryptResult, password);
        System.out.println("解密后:" + new String(decryptResult));

    }

}

  

java AES加密解密

标签:nop   except   import   blocks   java   color   instance   throws   block   

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!