使用 bouncycastle实现 AES

2 篇文章 0 订阅
1 篇文章 0 订阅


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

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值