AES加密解密

Posted freeLife

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AES加密解密相关的知识,希望对你有一定的参考价值。

AES是一种对称加密,简单理解为秘钥只有一个,加密解密都用它,安全性不是很好

package com.aisino.qysds.common.util;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;

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;
import org.apache.commons.codec.binary.Base64;


public class AESUtil {

    private static final String charset = "UTF-8";
    private final static int length=128;
    private final static String base = "abcdefghijklmnopqrstuvwxyz0123456789"; 
    private static final String KEY_AES = "AES";
    
    /**
     * aes ECB 模式加密
     * @param encryptStr
     * @param decryptKey
     * @return
     */
    public static String encryptECB(String encryptStr, String decryptKey){
        try{
             return parseByte2HexStr(encrypt_ECB(encryptStr, decryptKey)); 
        }catch(Exception e) {
                return null;
        }
    }

    /**
     * aes ECB 模式解密
     * @param encryptStr
     * @param decryptKey
     * @return
     * @throws Exception
     */
    public static String decryptECB(String encryptStr, String decryptKey)throws Exception{
        return decrypt_ECB(parseHexStr2Byte(encryptStr), decryptKey);  
    }
    /**
     * 加密 ECB
     * @param content
     * 需要加密的内容
     * @param password
     * 加密密码
     * @return
     */
    private static byte[] encrypt_ECB(String content, String encryptKey) throws Exception {
        try {
            Cipher aesECB = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), KEY_AES);
            aesECB.init(Cipher.ENCRYPT_MODE, key);
            byte[] result = aesECB.doFinal(content.getBytes(charset));
            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 (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 解密 ECB
     * @param content 待解密内容
     * @param password 解密密钥
     * @return
     */
    private static String decrypt_ECB(byte[] encryptBytes, String decryptKey) throws Exception {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
            SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), KEY_AES);
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
            //byte[] result = parseHexStr2Byte(content);
            return new String(cipher.doFinal(encryptBytes)); // 解密
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
        
    }
    
    
    
    /**
     * aes 默认加密
     * @param content
     * 需要加密的内容
     * @param password
     * 加密密码
     * @return
     */
    private static byte[] encrypt(String content, String password) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance(KEY_AES);
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); 
        secureRandom.setSeed(password.getBytes());
        kgen.init(length, secureRandom);
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat,KEY_AES);
        Cipher cipher = Cipher.getInstance(KEY_AES);// 创建密码器
        byte[] byteContent = content.getBytes(charset);
        cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
        byte[] result = cipher.doFinal(byteContent);
        return result; // 加密
    }


    /**
     * aes 默认解密
     * @param content 待解密内容
     * @param password 解密密钥
     * @return
     */
    private static byte[] decrypt(byte[] content, String password) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance(KEY_AES);
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); 
        secureRandom.setSeed(password.getBytes());
        kgen.init(length, secureRandom);
        SecretKey secretKey = kgen.generateKey();
        byte[] enCodeFormat = secretKey.getEncoded();
        SecretKeySpec key = new SecretKeySpec(enCodeFormat,KEY_AES);
        Cipher cipher = Cipher.getInstance(KEY_AES);// 创建密码器
        cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
        byte[] result = cipher.doFinal(content);
        return result; // 加密
    }


    /**
     * aes 默认加密
     * @param content
     * @param password
     * @return
     */
    public static String encryptAES(String content, String password){
        try{
            byte[] encryptResult = encrypt(content, password);
            return encode(encryptResult);
        }catch(Exception e) {
                return null;
        }
    }

    /**
     * aes 默认解密
     * @param content
     * @param password
     * @return
     */
    
    public static String decryptAES(String content, String password){
        try{
            byte[] decryptResult = decrypt(decode(content.getBytes()), password);
            return new String(decryptResult,charset);
        }catch(Exception e) {
                return null;
        }
    }


    /**
     * 获得随机数
     * @param len
     * @return
     */
    public static String randomStr(int len) {
        Random random = new Random();     
        StringBuffer sb = new StringBuffer();     
        for (int i = 0; i < len; i++) {     
            int number = random.nextInt(base.length());     
            sb.append(base.charAt(number));     
        }     
        return sb.toString();  
    }

    /**将二进制转换成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进制转换成2进制 
     * @param buf 
     * @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;  
    }
    
    /**
     * 数据编码为BASE64字符串 转为 二进制
     * @param bytes
     * @return
     */
    public static byte[] decode(final byte[] bytes) {  
        return Base64.decodeBase64(bytes);  
    }  
    /** 
     * 二进制数据编码为BASE64字符串 
     * 
     * @param bytes 
     * @return 
     * @throws Exception 
     */  
    public static String encode(final byte[] bytes) {  
        return new String(Base64.encodeBase64(bytes));  
    }  
    /** 
     * 字符串转换unicode 
     */  
    public static String string2Unicode(String string) {  
        StringBuffer unicode = new StringBuffer();  
        for (int i = 0; i < string.length(); i++) {  
            // 取出每一个字符  
            char c = string.charAt(i);  
            // 转换为unicode  
            unicode.append("\\u" + Integer.toHexString(c));  
        }  
        return unicode.toString();  
    } 
    /** 
     * unicode 转字符串 
     */  
    public static String unicode2String(String unicode) {  
        StringBuffer string = new StringBuffer();  
        String[] hex = unicode.split("\\\\u");  
        for (int i = 1; i < hex.length; i++) {  
            // 转换出每一个代码点  
            int data = Integer.parseInt(hex[i], 16);  
            // 追加成string  
            string.append((char) data);  
        }  
        return string.toString();  
    } 
    
    public static void main(String[] args) throws Exception {
        String content ="1231";
        String key = "AAAAAAAAAAAAAAAA";
        // 加密
        System.out.println("加密前:"+content );
        String tt4 = encryptECB(content, key);
        System.out.println(new String(tt4));

        // 解密
        String d = decryptECB(tt4, key);
        System.out.println("解密后:"+ d);
    }
    
}

结果输出

加密前:1231
15428541F01951FF4F0A2990535F2C81
解密后:1231

 

以上是关于AES加密解密的主要内容,如果未能解决你的问题,请参考以下文章

更新实现代码对称加密与解密剖析:AES,高级加密标准(Advanced Encryption Standard,缩写AES)

AES加密解密代码

QT:AES-256-CBC 根据 PHP 代码在 C++ 中加密/解密

Java aes加密C#解密的取巧方法

Android通过AES128加密解密字符串的代码

基于AES对称加密解密的代码块