使用bouncycastle进行加密

BouncyCastle是一个开源的加解密解决方案,主页在http://www.bouncycastle.org/,下面写一个工具类对String加密和解密

/**
 * use bouncycastle to AES encrypt
 */
public class AESUtils {
	private static final AESUtils instance = new AESUtils();
	byte[] iv = { 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x38, 0x37,
			0x36, 0x35, 0x34, 0x33, 0x32, 0x31 };

	byte[] keybytes = { 0x70, 0x2F, 0x17, 0x7F, 0x6C, 0x3A, 0x22, 0x11, 0x3F,
			0x44, 0x5A, 0x66, 0x77, 0x1A, 0x12, 0x1C };

	private AESUtils() {

	}

	public static AESUtils getInstance() {
		return instance;
	}

	private Key key;
	private byte[] enc;

	public String encrypt(String msg) {
		String str;
		try {
			Security.addProvider(new BouncyCastleProvider());
			key = new SecretKeySpec(keybytes, "AES");
			Cipher in = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
			in.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
			enc = in.doFinal(msg.getBytes());
			str = new String(Hex.encode(enc));
			return str;
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public String decrypt(byte[] msg) {
		String str;
		try {
                                                Security.addProvider(new BouncyCastleProvider());
			key = new SecretKeySpec(keybytes, "AES");

			Cipher out = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
			out.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
			byte[] dec = out.doFinal(msg);
			str = new String(dec);
			return str;
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值