java加密类_java加密类Cipher的使用

public classEncryptUtils {private static final String SECRET_KEY_1 = "YIORGA4dBYp6y7u8";private static final String SECRET_KEY_2 = "C6B8r5y7u7Uh37Sy";privateIvParameterSpec ivParameterSpec;privateSecretKeySpec secretKeySpec;privateCipher cipher;public EncryptUtils() throwsUnsupportedEncodingException, NoSuchPaddingException, NoSuchAlgorithmException {

ivParameterSpec= new IvParameterSpec(SECRET_KEY_1.getBytes("UTF-8"));

secretKeySpec= new SecretKeySpec(SECRET_KEY_2.getBytes("UTF-8"), "AES");

cipher= Cipher.getInstance("AES/CBC/PKCS5PADDING");

}/*** Encrypt the string with this internal algorithm.

*

*@paramtoBeEncrypt string object to be encrypt.

*@returnreturns encrypted string.

*@throwsNoSuchPaddingException

*@throwsNoSuchAlgorithmException

*@throwsInvalidAlgorithmParameterException

*@throwsInvalidKeyException

*@throwsBadPaddingException

*@throwsIllegalBlockSizeException*/

public String encrypt(String toBeEncrypt) throwsNoSuchPaddingException, NoSuchAlgorithmException,

InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {

cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);byte[] encrypted =cipher.doFinal(toBeEncrypt.getBytes());returnBase64.encodeBase64String(encrypted);

}/*** Decrypt this string with the internal algorithm. The passed argument should be encrypted using

* {@link#encrypt(String) encrypt} method of this class.

*

*@paramencrypted encrypted string that was encrypted using {@link#encrypt(String) encrypt} method.

*@returndecrypted string.

*@throwsInvalidAlgorithmParameterException

*@throwsInvalidKeyException

*@throwsBadPaddingException

*@throwsIllegalBlockSizeException*/

public String decrypt(String encrypted) throwsInvalidAlgorithmParameterException, InvalidKeyException,

BadPaddingException, IllegalBlockSizeException {

cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);byte[] decryptedBytes =cipher.doFinal(Base64.decodeBase64(encrypted));return newString(decryptedBytes);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值