加密解密

package org.xm.com.security;

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;


public class AES {
	private  static final String KEY_ALGORITHM="AES";
	/**
	 * 加密/解密算法 / 工作模式 / 填充方式 
	 * Java 6支持PKCS5Padding填充方式 
	 * Bouncy Castle支持PKCS7Padding填充方式
	 */
	public static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
	
	private static final String SEED="seed";
	private static SecretKey secretKey;
	
	static {
		init();
	}
	public static void main(String args[]){
		try {
			String inputStr ="dsd12";
			byte[] inputData = inputStr.getBytes();
			System.err.println("原文:\t" + inputStr);

			// 初始化密钥
			byte[] key = AESCoder.initKey();
			System.err.println("密钥:\t" + parseByte2HexStr(secretKey.getEncoded()));

			// 加密
			inputData =encrypt(inputStr);
			System.err.println("加密后:\t" +parseByte2HexStr(encrypt(inputStr)));

			// 解密
			byte[] outputData = decrypt(inputData);

			String outputStr = new String(outputData);
			System.err.println("解密后:\t" + outputStr);

			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	
	public static void init() {
		
		try {
			 // 实例化
			 KeyGenerator  kgen = KeyGenerator.getInstance(KEY_ALGORITHM);
			 /*
			  * AES 要求密钥长度为 128位、192位或 256位
			  */
			 kgen.init(128, new SecureRandom(SEED.getBytes()));
			 // 初始化秘密密钥
			  secretKey = kgen.generateKey();

		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
        
        
	}
	
    /**
     * 加密
     * 
     * @param content 需要加密的内容
     * @param password  加密密码
     * @return
     * @throws NoSuchPaddingException 
     * @throws NoSuchAlgorithmException 
     * @throws InvalidKeyException 
     * @throws BadPaddingException 
     * @throws IllegalBlockSizeException 
     * @throws UnsupportedEncodingException 
     */
    public static byte[] encrypt(String content) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        byte[] byteContent = content.getBytes("utf-8");
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
 		// 初始化,设置为加密模式
 		cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        //cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
        byte[] result = cipher.doFinal(byteContent);
        return result; // 加密   
    }
    
    /**解密
     * @param content  待解密内容
     * @param password 解密密钥
     * @return
     * @throws BadPaddingException 
     * @throws IllegalBlockSizeException 
     * @throws InvalidKeyException 
     * @throws NoSuchPaddingException 
     * @throws NoSuchAlgorithmException 
     */
    public static byte[] decrypt(byte[] content) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {    
       Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);// 创建密码器
       cipher.init(Cipher.DECRYPT_MODE, secretKey);// 初始化
       byte[] result = cipher.doFinal(content);
       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;
    }
}

你可能感兴趣的:(加密解密)