当前位置: 首页 > news >正文

用java进行base64加密

首先定义一组密钥,加密和解密使用同一组密钥

private final String key = "hahahahahaha";

也可以随机生成密钥

/**

* 生成随机密钥

* @param keySize 密钥大小推荐128 256

* @return

* @throws NoSuchAlgorithmException

*/

public static String generateSecret(int keySize) throws NoSuchAlgorithmException {

KeyGenerator generator = KeyGenerator.getInstance("AES");

generator.init(keySize, new SecureRandom());

SecretKey key = generator.generateKey();

return byteToHexString(key.getEncoded());

}

加密

/**

* 加密

* @param strToEncrypt 待加密字符串

* @param secret 密钥

* @return 密文

* @throws UnsupportedEncodingException

* @throws NoSuchAlgorithmException

* @throws NoSuchPaddingException

* @throws InvalidKeyException

* @throws BadPaddingException

* @throws IllegalBlockSizeException

*/

public static String encrypt(String strToEncrypt, String secret) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {

SecretKeySpec secretKey = getKey(secret);

Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

cipher.init(Cipher.ENCRYPT_MODE, secretKey);

return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));

}

解密

/**

* 解密

* @param strToDecrypt 待解密字符串

* @param secret 密钥

* @return 明文

* @throws UnsupportedEncodingException

* @throws NoSuchAlgorithmException

* @throws NoSuchPaddingException

* @throws InvalidKeyException

* @throws BadPaddingException

* @throws IllegalBlockSizeException

*/

public static String decrypt(String strToDecrypt, String secret) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {

SecretKeySpec secretKey = getKey(secret);

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

cipher.init(Cipher.DECRYPT_MODE, secretKey);

return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));

}

http://www.lryc.cn/news/25003.html

相关文章:

  • torch函数合集
  • AcWing算法提高课-3.1.2信使
  • Paddle OCR Win 11下的安装和简单使用教程
  • 杂谈:数组index问题和对象key问题
  • 三天Golang快速入门—Slice切片
  • 腾讯会议演示者视图/演讲者视图
  • 【C++】类与对象(一)
  • JavaScript基本语法
  • OpenCV4.x图像处理实例-道路车辆检测(基于背景消减法)
  • pwnlab通关流程
  • 面向过程与面向对象的区别与联系
  • 主机状态(查看资源占用情况、查看网络占用情况)
  • 代码随想录算法训练营第四十一天 | 01背包问题-二维数组滚动数组,416. 分割等和子集
  • VMware NSX 4.1 发布 - 网络安全虚拟化平台
  • 计算理论 复杂度预备知识
  • 二叉树——二叉搜索树中的插入操作
  • C# if break,if continue,if return的区别和使用
  • 力扣-第二高的薪水
  • I - 太阳轰炸(组合数学Cnk n固定)
  • centos安装gitlab
  • 【洛谷 P1093】[NOIP2007 普及组] 奖学金 题解(结构体排序)
  • 【Hello Linux】进程优先级和环境变量
  • 日期:Date,SimpleDateFormat常见API以及包装类
  • 嵌入式之ubuntu终端操作与shell常用命令详解
  • 【Shell学习笔记】6.Shell 流程控制
  • 27k入职阿里测开岗那天,我哭了,这5个月付出的一切总算没有白费~
  • 服务端开发之Java备战秋招面试篇5
  • 有趣的 Kotlin 0x11: joinToString,你真的了解嘛?
  • 代码随想录算法训练营day46 | 动态规划之背包问题 139.单词拆分
  • DPDK中的无锁共享数据结构