- import java.io.UnsupportedEncodingException;
- 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;
- public class AES {
- private static byte[] iv = { 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x38, 0x37,
- 0x36, 0x35, 0x34, 0x33, 0x32, 0x31 };
- static {
- Security.addProvider(new BouncyCastleProvider());
- }
- /**
- * 加密
- * @param content 需要加密的内容
- * @param password 加密密码
- * @return
- * @throws UnsupportedEncodingException
- */
- public static byte[] encrypt(byte[] content, String password) throws Exception {
- Key key = new SecretKeySpec(password.getBytes("utf-8"), "AES");
- Cipher in = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
- in.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
- byte[] enc = in.doFinal(content);
- return enc;
- }
- /**
- * 解密
- * @param content 待解密内容
- * @param password 解密密钥
- * @return
- * @throws UnsupportedEncodingException
- */
- public static byte[] decrypt(byte[] content, String password) throws Exception {
- Key key = new SecretKeySpec(password.getBytes("utf-8"), "AES");
- Cipher out = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
- out.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
- byte[] dec = out.doFinal(content);
- return dec;
- }
- public static void main(String[] args) throws Exception{
- String key = "11147169444463676897639210105259";
- byte[] result =encrypt("加密字符串".getBytes("utf-8"),key);
- System.out.println(new String(result,"utf-8"));
- result = decrypt(result,key);
- System.out.println(new String(result,"utf-8"));
- }
- }
2012年3月11日星期日
使用 bouncycastle实现 AES
订阅:
博文评论 (Atom)
没有评论:
发表评论