Java常用的加密解密工具类

1. 引言

在软件开发中,数据的安全性是一个重要的考虑因素。为了保护敏感数据,我们经常需要对数据进行加密和解密操作。为了简化加密解密操作,提高开发效率,我们可以使用一个常用的加密解密工具类。本文将介绍一个常用的 Java 加密解密工具类,并提供详细的使用说明和示例。

2. 工具类介绍

工具类的名称:EncryptionUtil

工具类的功能:提供常用的加密解密方法,包括对称加密、非对称加密、哈希算法等。

3. 工具类示例及使用说明

以下是 EncryptionUtil 工具类的代码示例:

package csdn;

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.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
/**
 * @author fanmengze
 * @date 2023/11/13 21:59
 **/
public class EncryptionUtil {

    /**
     * 生成AES密钥
     *
     * @param password 密码
     * @return 密钥
     * @throws NoSuchAlgorithmException 密钥生成算法不支持异常
     */
    private static SecretKey generateAESKey(String password) throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);
        byte[] passwordBytes = password.getBytes(StandardCharsets.UTF_8);
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] keyBytes = digest.digest(passwordBytes);
        return new SecretKeySpec(keyBytes, "AES");
    }

    /**
     * 对称加密算法AES加密
     *
     * @param plaintext 明文
     * @param password  密码
     * @return 加密后的密文
     * @throws Exception 加密异常
     */
    public static String encryptWithAES(String plaintext, String password) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        SecretKey secretKey = generateAESKey(password);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 对称加密算法AES解密
     *
     * @param ciphertext 密文
     * @param password   密码
     * @return 解密后的明文
     * @throws Exception 解密异常
     */
    public static String decryptWithAES(String ciphertext, String password) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        SecretKey secretKey = generateAESKey(password);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(ciphertext));
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    /**
     * 生成RSA密钥对
     *
     * @return 密钥对
     * @throws NoSuchAlgorithmException 密钥生成算法不支持异常
     */
    public static KeyPair generateRSAKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        return keyPairGenerator.generateKeyPair();
    }

    /**
     * 获取RSA公钥的Base64编码字符串
     *
     * @return RSA公钥Base64编码字符串
     */
    public static String getRSAPublicKeyString(PublicKey publicKey) {
        KeyFactory keyFactory;
        try {
            keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
            return Base64.getEncoder().encodeToString(keyFactory.generatePublic(publicKeySpec).getEncoded());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据Base64编码的字符串还原为RSA公钥
     *
     * @param publicKeyString RSA公钥Base64编码字符串
     * @return RSA公钥
     */
    public static PublicKey getPublicKey(String publicKeyString) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyString));
            return keyFactory.generatePublic(publicKeySpec);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取RSA私钥的Base64编码字符串
     *
     * @return RSA私钥Base64编码字符串
     */
    public static String getRSAPrivateKeyString(PrivateKey privateKey) {
        KeyFactory keyFactory;
        try {
            keyFactory = KeyFactory.getInstance("RSA");
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
            return Base64.getEncoder().encodeToString(keyFactory.generatePrivate(privateKeySpec).getEncoded());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据Base64编码的字符串还原为RSA私钥
     *
     * @param privateKeyString RSA私钥Base64编码字符串
     * @return RSA私钥
     */
    public static PrivateKey getPrivateKey(String privateKeyString) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyString));
            return keyFactory.generatePrivate(privateKeySpec);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 非对称加密算法RSA加密
     *
     * @param plaintext 明文
     * @param publicKey 公钥
     * @return 加密后的密文
     * @throws Exception 加密异常
     */
    public static String encryptWithRSA(String plaintext, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        KeyPair keyPair = generateRSAKeyPair();
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 非对称加密算法RSA解密
     *
     * @param ciphertext 密文
     * @param privateKey 私钥
     * @return 解密后的明文
     * @throws Exception 解密异常
     */
    public static String decryptWithRSA(String ciphertext, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        KeyPair keyPair = generateRSAKeyPair();
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(ciphertext));
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    /**
     * 哈希算法SHA-256
     *
     * @param plaintext 明文
     * @return 哈希值
     * @throws NoSuchAlgorithmException 哈希算法不支持异常
     */
    public static String hashWithSHA256(String plaintext) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hashBytes = digest.digest(plaintext.getBytes(StandardCharsets.UTF_8));
        return bytesToHex(hashBytes);
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param bytes 字节数组
     * @return 十六进制字符串
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * Base64 编码
     *
     * @param plainText 内容
     * @return 十六进制字符串
     */
    public static String encodeBase64(String plainText) {
        byte[] plainBytes = plainText.getBytes(StandardCharsets.UTF_8);
        return Base64.getEncoder().encodeToString(plainBytes);
    }

    /**
     * Base64 解码
     *
     * @param base64Text 十六进制字符串
     * @return 内容
     */
    public static String decodeBase64(String base64Text) {
        byte[] base64Bytes = Base64.getDecoder().decode(base64Text);
        return new String(base64Bytes, StandardCharsets.UTF_8);
    }
}



4. 结论

通过使用上述的 EncryptionUtil 工具类,我们可以方便地进行常见的加密解密操作,提高开发效率。

通过合理的使用示例和详细的注释,开发人员可以快速掌握该工具类的使用方法,并在实际项目中应用它。

以下是 EncryptionUtil 工具类的使用示例:

public class Main {

    public static void main(String[] args) {
        try {
            // AES 对称加密示例
            String plaintext = "Hello, world!";
            String password = "secretPassword";
            // AES 加密
            String encryptedAES = EncryptionUtil.encryptWithAES(plaintext, password);
            System.out.println("AES Encrypted: " + encryptedAES);
            // AES 解密
            String decryptedAES = EncryptionUtil.decryptWithAES(encryptedAES, password);
            System.out.println("AES Decrypted: " + decryptedAES);


            // RSA 非对称加密示例
            String plaintextRSA = "Hello, RSA!";
            // 生成RSA密钥对
            KeyPair keyPair = EncryptionUtil.generateRSAKeyPair();
            // RSA 加密
            String encryptedRSA = EncryptionUtil.encryptWithRSA(plaintextRSA, keyPair.getPublic());
            System.out.println("RSA Encrypted: " + encryptedRSA);
            // RSA 解密
            String decryptedRSA = EncryptionUtil.decryptWithRSA(encryptedRSA, keyPair.getPrivate());
            System.out.println("RSA Decrypted: " + decryptedRSA);
            // 补充 公钥/私钥字符串获取
            String publicKeyString = EncryptionUtil.getRSAPublicKeyString(keyPair.getPublic());
            System.out.println("RSA publicKeyString: " + publicKeyString);
            String privateKeyString = EncryptionUtil.getRSAPrivateKeyString(keyPair.getPrivate());
            System.out.println("RSA privateKeyString: " + privateKeyString);
            // 补充 公钥/私钥还原
            PublicKey publicKey = EncryptionUtil.getPublicKey(publicKeyString);
            PrivateKey privateKey = EncryptionUtil.getPrivateKey(privateKeyString);


            // 哈希算法示例
            String plaintextHash = "Hello Hash!";
            String hashValue = EncryptionUtil.hashWithSHA256(plaintextHash);
            System.out.println("SHA-256 Hash: " + hashValue);

            // Base64 编码解码示例
            // Base64 编码
            String base64Text = EncryptionUtil.encodeBase64("Hello Base64!");
            System.out.println("Base64 Encoded: " + base64Text);
            // Base64 解码
            String decodedText = EncryptionUtil.decodeBase64(base64Text);
            System.out.println("Base64 Decoded: " + decodedText);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

以上是关于常用的加密解密工具类的详细介绍及使用示例。希望本文对你在日常开发中的加密解密需求有所帮助。如果你有任何问题或建议,欢迎在下方留言。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值