首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

运用 bouncycastle实现 AES

2012-10-15 
使用 bouncycastle实现 AESimport java.io.UnsupportedEncodingExceptionimport java.security.Keyimpor

使用 bouncycastle实现 AES

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"));}}

热点排行