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

java实现加密解密

AES加密/解密核心步骤

参考

https://flying-fish.blog.csdn.net/article/details/142688630?fromshare=blogdetail&sharetype=blogdetail&sharerId=142688630&sharerefer=PC&sharesource=weixin_48616345&sharefrom=from_link

工具类

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Base64;

public class EncryptUtils {

    // MD5 加密
    public static String md5(String data) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digest = md.digest(data.getBytes(StandardCharsets.UTF_8));
        return bytesToHex(digest);
    }

    // SHA-256 加密
    public static String sha256(String data) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] digest = md.digest(data.getBytes(StandardCharsets.UTF_8));
        return bytesToHex(digest);
    }

    // AES 加密
    public static String aesEncrypt(String data, String key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encrypted);
    }

    // AES 解密
    public static String aesDecrypt(String encryptedData, String key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        byte[] decoded = Base64.getDecoder().decode(encryptedData);
        byte[] decrypted = cipher.doFinal(decoded);
        return new String(decrypted, StandardCharsets.UTF_8);
    }

    // RSA 公钥加密
    public static String rsaEncrypt(String data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encrypted);
    }

    // RSA 私钥解密
    public static String rsaDecrypt(String encryptedData, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decoded = Base64.getDecoder().decode(encryptedData);
        byte[] decrypted = cipher.doFinal(decoded);
        return new String(decrypted, StandardCharsets.UTF_8);
    }

    // 生成 RSA 密钥对
    public static KeyPair generateRsaKeyPair(int keySize) throws NoSuchAlgorithmException {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(keySize);
        return keyGen.generateKeyPair();
    }

    // 辅助方法:字节数组转十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}

使用方法

EncryptUtils 方法详解
MD5 和 SHA-256 加密:

md5(String data):对输入字符串进行 MD5 哈希处理,返回十六进制字符串。
sha256(String data):对输入字符串进行 SHA-256 哈希处理,返回十六进制字符串。
这些方法用于生成数据的哈希值,适用于数据完整性校验和密码存储(需要加盐)。
AES 加密和解密:

aesEncrypt(String data, String key):使用 AES 对称算法加密数据,密钥长度为 16 字节。
aesDecrypt(String encryptedData, String key):使用 AES 对称算法解密数据。
AES 加密适用于对数据进行高效、快速的对称加密,通常用于敏感信息的存储和传输。
RSA 加密和解密:

rsaEncrypt(String data, PublicKey publicKey):使用 RSA 非对称算法和公钥加密数据。
rsaDecrypt(String encryptedData, PrivateKey privateKey):使用 RSA 非对称算法和私钥解密数据。
generateRsaKeyPair(int keySize):生成 RSA 密钥对,支持 1024、2048、4096 等密钥长度。
RSA 加密常用于数据传输中的密钥交换和数字签名。

相关文章:

  • 01_JDBC
  • 集合 Collection、Map
  • Qt炫酷仪表盘
  • 计算机网络:流量控制与可靠传输机制
  • Streamlit 最新进展分析
  • C++蓝桥杯实训篇(四)
  • Excel VBA 运行时错误1004’:方法‘Open’作用于对象‘Workbooks’时失败 的解决方法
  • openwrt软路由配置4--文件共享
  • ISIS路由引入
  • 【C++游戏引擎开发】第15篇:OpenGL中的纹理加载
  • 《组合优于继承:构建高内聚低耦合模块的最佳实践》
  • 如何把pdf的内容转化成结构化数据进行存储到mysql数据库
  • 【KWDB创作者计划】_KWDB应用之实战案例
  • java面试题带答案2025最新整理
  • 【动手学强化学习】番外7-MAPPO应用框架2学习与复现
  • 编译构建 WSO2 产品时的一些注意事项
  • Spring事务同步器在金融系统中的应用:从风控计算到交易投递
  • 车载通信架构 --- DOIP系统机制初入门
  • 五款AI论文工具,助力完成论文写作
  • Konga密码重置
  • 王励勤谈国乒备战洛杉矶奥运会:要对六块金牌制定新的战略
  • 中汽协:杜绝虚假宣传与过度营销,确保用户清晰区别驾驶辅助与自动驾驶
  • 一季度浙江实现生产总值22300亿元,同比增长6.0%
  • 海南医科大学继续开展部门正职竞聘上岗,致力营造“谁有本事谁来”
  • 学者建议:引入退休教师、青少年宫参与课后服务,为教师“减负”
  • 多元布局、抱团取暖……上海这个区和外向型企业坐到一起聊了什么