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加密解密(j2se)
package com.albertsong.aes;
import java.security.Key;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
public class AESWithJCE {
/**
* @param args
*/
public static void main(String[] args) {
byte[] keybytes = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38 };
byte[] iv = { 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x38,
0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31 };
String content ="TEST1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("Original content:");
System.out.println(content);
try {
Security.addProvider(new BouncyCastleProvider());
Key key = new SecretKeySpec(keybytes, "AES");
Cipher in = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
in.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
byte[] enc = in.doFinal(content.getBytes());
System.out.println("Encrypted Content:");
System.out.println(new String(Hex.encode(enc)));
Cipher out = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");