Bouncy Castle Crypto APIs 是一个开源的轻量级Java 加密解密包,实现了JCE/JCA的provider,支持AES等多种加密解密算法。
详情请见主页:http://www.bouncycastle.org/java.html
本文的示例代码使用了 http://www.bouncycastle.org/download/bcprov-jdk16-139.jar
1)使用JCE的 AES-128-CBC加密解密
下载: AESWithJCE.java
1. package com.albertsong.aes;
2.
3. import java.security.Key;
4. import java.security.Security;
5.
6. import javax.crypto.Cipher;
7. import javax.crypto.spec.IvParameterSpec;
8. import javax.crypto.spec.SecretKeySpec;
9.
10. import org.bouncycastle.jce.provider.BouncyCastleProvider;
11. import org.bouncycastle.util.encoders.Hex;
12.
13. /**
14. * @author Albert
15. * @version 1.0
16. *
17. */
18. public class AESWithJCE {
19.
20. /**
21. * @param args
22. */
23. public static void main(String[] args) {
24. byte[] keybytes = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
25. 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 };
26. byte[] iv = { 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x38,
27. 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31 };
28. String content ="TEST1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
29. System.out.println("Original content:");
30. System.out.println(content);
31. try {
32. Security.addProvider(new BouncyCastleProvider());
33. Key key = new SecretKeySpec(keybytes, "AES");
34. Cipher in = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
35. in.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
36. byte[] enc = in.doFinal(content.getBytes());
37. System.out.println("Encrypted Content:");
38. System.out.println(new String(Hex.encode(enc)));
39.
40. Cipher out = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
41. out.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
42. byte[] dec = out.doFinal(enc);
43. System.out.println("Decrypted Content:");
44. System.out.println(new String(dec));
45. } catch (Exception ex) {
46. ex.printStackTrace();
47. }
48.
49. }
50.
51. }