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

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章