2012年3月11日星期日

使用 bouncycastle实现 AES


  1. import java.io.UnsupportedEncodingException;  
  2. import java.security.Key;  
  3. import java.security.Security;  
  4.   
  5. import javax.crypto.Cipher;  
  6. import javax.crypto.spec.IvParameterSpec;  
  7. import javax.crypto.spec.SecretKeySpec;  
  8.   
  9. import org.bouncycastle.jce.provider.BouncyCastleProvider;  
  10.   
  11. public class AES {  
  12.   
  13.     private static byte[] iv = { 0x380x370x360x350x340x330x320x310x380x37,  
  14.             0x360x350x340x330x320x31 };  
  15.     static {  
  16.         Security.addProvider(new BouncyCastleProvider());  
  17.     }  
  18.       
  19.     /** 
  20.      * 加密 
  21.      * @param content  需要加密的内容 
  22.      * @param password  加密密码 
  23.      * @return 
  24.      * @throws UnsupportedEncodingException  
  25.      */  
  26.     public static byte[] encrypt(byte[] content, String password) throws Exception {  
  27.         Key key = new SecretKeySpec(password.getBytes("utf-8"), "AES");  
  28.         Cipher in = Cipher.getInstance("AES/CBC/PKCS7Padding""BC");  
  29.         in.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));  
  30.         byte[] enc = in.doFinal(content);  
  31.         return enc;  
  32.     }  
  33.   
  34.     /** 
  35.      * 解密 
  36.      * @param content 待解密内容 
  37.      * @param password 解密密钥 
  38.      * @return 
  39.      * @throws UnsupportedEncodingException  
  40.      */  
  41.     public static byte[] decrypt(byte[] content, String password) throws Exception {  
  42.         Key key = new SecretKeySpec(password.getBytes("utf-8"), "AES");  
  43.         Cipher out = Cipher.getInstance("AES/CBC/PKCS7Padding""BC");  
  44.         out.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));  
  45.         byte[] dec = out.doFinal(content);  
  46.         return dec;  
  47.     }  
  48.   
  49.     public static void main(String[] args) throws Exception{  
  50.         String key = "11147169444463676897639210105259";  
  51.         byte[] result =encrypt("加密字符串".getBytes("utf-8"),key);  
  52.         System.out.println(new String(result,"utf-8"));  
  53.         result = decrypt(result,key);  
  54.         System.out.println(new String(result,"utf-8"));  
  55.     }  
  56.   
  57. }  

没有评论:

发表评论