자바 대칭 암호 화(AES)

/**
 * AESHelper.java
 * cn.com.songjy.test
 *
 * Function: TODO 
 *
 *   ver     date      		author
 * ──────────────────────────────────
 *   		 2012-6-29 		songjianyong
 *
 * Copyright (c) 2012, TNT All Rights Reserved.
*/

package cn.com.songjy.test;

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;

/**
 * ClassName:AESHelper
 *
 * @author   songjianyong
 * @version  1.0
 * @since    v1.0
 * @Date	 2012-6-29   2:06:07 
 */
public class AESHelper {

	/**
	 * @method main
	 * @param args
	 * @throws 
	 * @since v1.0
	 */

	public static void main(String[] args) {

		String content = "   ";
		String password = "12345678";
		byte[] encryptResult = encrypt(content, password);//  
		byte[] decryptResult = decrypt(encryptResult,password);//  
		System.out.println("   :" + new String(decryptResult));
		
		/*       ,      */
		System.out.println("***********************************************");
		try {
			String encryptResultStr = new String(encryptResult,"utf-8");
			decryptResult = decrypt(encryptResultStr.getBytes("utf-8"),password);
			System.out.println("   :" + new String(decryptResult));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			// TODO: handle exception
		}
		/* ,         :javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
	at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
	at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
	at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
	at javax.crypto.Cipher.doFinal(DashoA13*..)
	at cn.com.songjy.test.ASCHelper.decrypt(ASCHelper.java:131)
	at cn.com.songjy.test.ASCHelper.main(ASCHelper.java:58)
		 * */
		/*          byte              ,    ,    byte             ,
		 *        ,         ,                   ,
		 *        :       16  (   parseByte2HexStr)   16        (   parseHexStr2Byte)*/
		
		/*  ,           */
		System.out.println("***********************************************");
		String encryptResultStr = parseByte2HexStr(encryptResult);
		System.out.println("   :" + encryptResultStr);
		byte[] decryptFrom = parseHexStr2Byte(encryptResultStr);
		decryptResult = decrypt(decryptFrom,password);//  
		System.out.println("   :" + new String(decryptResult));
	}

	/**
	 *   
	 * @method encrypt
	 * @param content	       
	 * @param password	    
	 * @return
	 * @throws 
	 * @since v1.0
	 */
	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 (UnsupportedEncodingException e) {
			e.printStackTrace();
		}catch (InvalidKeyException e) {
			e.printStackTrace();
		}catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		}catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 *   
	 * @method decrypt
	 * @param content	     
	 * @param password	    
	 * @return
	 * @throws 
	 * @since v1.0
	 */
	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;
	}
	
	/**
	 *        16  
	 * @method parseByte2HexStr
	 * @param buf
	 * @return
	 * @throws 
	 * @since v1.0
	 */
	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        
	 * @method parseHexStr2Byte
	 * @param hexStr
	 * @return
	 * @throws 
	 * @since v1.0
	 */
	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;
	}
	
	/**
	 *         --           
	 * 1、     16  
	 * 2、           16   ,    16   ,       
	 * javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes
        at com.sun.crypto.provider.SunJCE_f.a(DashoA13*..)
        at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
        at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
        at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
        at javax.crypto.Cipher.doFinal(DashoA13*..)
		       ,                   。
	 * @method encrypt2
	 * @param content	       
	 * @param password	    
	 * @return
	 * @throws 
	 * @since v1.0
	 */
	public static byte[] encrypt2(String content, String password){
		try {
			SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
			Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
			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 (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
}


테스트 효과:
복호화 후:송 건 용
***********************************************
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
at cn.com.songjy.test.ASCHelper.decrypt(ASCHelper.java:141)
at cn.com.songjy.test.ASCHelper.main(ASCHelper.java:58)
java.lang.NullPointerException
at java.lang.String.(String.java:594)
at cn.com.songjy.test.ASCHelper.main(ASCHelper.java:59)
***********************************************
암호 화 후:961000 B09BDDA1F81E81EF3EFDC3A 926
복호화 후:송 건 용
인용:
http://www.2cto.com/kf/201112/114046.html

좋은 웹페이지 즐겨찾기