AES加解密

package com.uns.mpos.ins.common;


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;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class AESEncrypt
{
    private static String hexStr =  "0123456789ABCDEF"; 


    private static String privateKey = "areyouok";
    
    private static final Logger log = LoggerFactory.getLogger(AESEncrypt.class);
    /**
     * 加密
     *
     * @param content 需要加密的内容
     * @return
     */
    public static String encrypt(String content)
    {
        try
        {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );   
            secureRandom.setSeed(privateKey.getBytes()); 
            
            kgen.init(128, secureRandom);
            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);
            String strResult = BinaryToHexString(result);
            return strResult; // 加密
        }
        catch (NoSuchAlgorithmException e)
        {
            log.error("Invalid Algorith.");
            //e.printStackTrace();
        }
        catch (NoSuchPaddingException e)
        {
            log.error(e.getMessage(),e);
        }
        catch (InvalidKeyException e)
        {
            log.error(e.getMessage(),e);
        }
        catch (UnsupportedEncodingException e)
        {
            log.error(e.getMessage(),e);
        }
        catch (IllegalBlockSizeException e)
        {
            log.error(e.getMessage(),e);
        }
        catch (BadPaddingException e)
        {
            log.error(e.getMessage(),e);
        }
        return null;
    }
   
    /**解密
     * @param content  待解密内容
     * @return
     */
    public static String decrypt(String content)
    {
        try
        {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );   
            secureRandom.setSeed(privateKey.getBytes());   
            kgen.init(128, secureRandom);
            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[] byteContent = HexStringToBinary(content);


            byte[] result = cipher.doFinal(byteContent);
            return new String(result); // 加密
        }
        catch (NoSuchAlgorithmException e)
        {
            log.error("Invalid Algorith.");
            //e.printStackTrace();
        }
        catch (NoSuchPaddingException e)
        {
            log.error("Invalid Padding.");
        }
        catch (InvalidKeyException e)
        {
            log.error("Invalid key.");
        }
        catch (IllegalBlockSizeException e)
        {
            log.error("Illegal Block Size.");
        }
        catch (BadPaddingException e)
        {
            e.printStackTrace();
            log.error("bad  Paddin.");
        }
        return null;
    }
    /**
     * 
     * @param bytes
     * @return 将二进制转换为十六进制字符输出
     */ 
    public static String BinaryToHexString(byte[] bytes)
    {
        
        StringBuilder  result = new StringBuilder();
        StringBuilder  hex = new StringBuilder();
        for (int i = 0; i < bytes.length; i++)
        {
            hex.delete(0, hex.length());
            // 字节高4位
            hex.append(String.valueOf(hexStr.charAt((bytes[i] & 0xF0) >> 4)));
            // 字节低4位
            hex.append(String.valueOf(hexStr.charAt(bytes[i] & 0x0F)));
            result.append(hex);


        }
        return result.toString();
    } 
    /**
     * 
     * @param hexString
     * @return 将十六进制转换为字节数组
     */ 
    public static byte[] HexStringToBinary(String hexString)
    {
        // hexString的长度对2取整,作为bytes的长度
        int len = hexString.length() / 2;
        byte[] bytes = new byte[len];
        byte high = 0;// 字节高四位
        byte low = 0;// 字节低四位
        
        for (int i = 0; i < len; i++)
        {
            // 右移四位得到高位
            high = (byte)((hexStr.indexOf(hexString.charAt(2 * i))) << 4);
            low = (byte)hexStr.indexOf(hexString.charAt(2 * i + 1));
            bytes[i] = (byte)(high | low);// 高地位做或运算
        }
        return bytes;
    }   
    
    
    /**
* 加密
*
* @param content
*            需要加密的内容
* @return
*/
public static String encrypt(String content, String privateKey) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(privateKey.getBytes());


kgen.init(128, secureRandom);
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);
String strResult = BinaryToHexString(result);
return strResult; // 加密
} catch (NoSuchAlgorithmException e) {
log.error("Invalid Algorith.");
// e.printStackTrace();
} catch (NoSuchPaddingException e) {
log.error(e.getMessage(), e);
} catch (InvalidKeyException e) {
log.error(e.getMessage(), e);
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
} catch (IllegalBlockSizeException e) {
log.error(e.getMessage(), e);
} catch (BadPaddingException e) {
log.error(e.getMessage(), e);
}
return null;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值