Java中常用文本加解密工具类总结
更新时间:2024年11月15日 08:21:34 作者:一线大码
这篇文章主要为大家详细介绍了Java中常用的几种文本加解密工具类,包括AES对称加密、RSA非对称加密、哈希算法加密和Base64编解码,需要的可以参考下
1. AES 对称加解密
package com.example.demo.util; 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.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; /** * AES对称加密 * * @author wangbo * @date 2024/11/14 */ public class AesUtil { private AesUtil() { } /** * 生成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); } public static void main(String[] args) throws Exception { // AES 对称加密示例 String plaintext = "Hello, world!"; String password = "secretPassword"; // AES 加密 String encryptWithAes = encryptWithAes(plaintext, password); System.out.println("AES Encrypted: " + encryptWithAes); // AES 解密 String decryptWithAes = decryptWithAes(encryptWithAes, password); System.out.println("AES Decrypted: " + decryptWithAes); } }
2. RSA 非对称加解密
package com.example.demo.util; import javax.crypto.Cipher; import java.nio.charset.StandardCharsets; import java.security.*; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; /** * RSA非对称加密 * * @author wangbo * @date 2024/11/14 */ public class RsaUtil { private RsaUtil() { } /** * 生成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"); 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"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(ciphertext)); return new String(decryptedBytes, StandardCharsets.UTF_8); } public static void main(String[] args) throws Exception { //RSA非对称加密示例 String plaintext = "Hello, RSA!"; //生成RSA密钥对 KeyPair keyPair = generateRsaKeyPair(); //公钥字符串获取 String publicKeyString = getRsaPublicKeyString(keyPair.getPublic()); System.out.println("RSA publicKeyString: " + publicKeyString); //公钥还原 PublicKey publicKey = getPublicKey(publicKeyString); //私钥字符串获取 String privateKeyString = getRsaPrivateKeyString(keyPair.getPrivate()); System.out.println("RSA privateKeyString: " + privateKeyString); //私钥还原 PrivateKey privateKey = getPrivateKey(privateKeyString); // RSA公钥加密 String encryptedRSA = encryptWithRsa(plaintext, publicKey); System.out.println("RSA Encrypted: " + encryptedRSA); // RSA私钥解密 String decryptedRSA = decryptWithRsa(encryptedRSA, privateKey); System.out.println("RSA Decrypted: " + decryptedRSA); } }
3. 哈希算法加密
package com.example.demo.util; import lombok.extern.slf4j.Slf4j; import org.springframework.util.DigestUtils; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * 哈希算法加密 * * @author wangbo * @date 2024/11/14 */ @Slf4j public class HashUtil { private HashUtil() { } /** * 哈希算法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(); } /** * SHA密码加密 * * @param sourceStr 源字符串 * @return 加密字符串 */ public static String sha(String sourceStr) { try { MessageDigest sha = MessageDigest.getInstance("SHA"); sha.update(sourceStr.getBytes(StandardCharsets.UTF_8)); return new BigInteger(1, sha.digest()).toString(32); } catch (NoSuchAlgorithmException e) { log.error("SHA字符串加密异常", e); return null; } } /** * MD5密码加密 * * @param sourceStr 源字符串 * @return 加密字符串 */ public static String md5(String sourceStr) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(sourceStr.getBytes(StandardCharsets.UTF_8)); return new BigInteger(1, md5.digest()).toString(16); } catch (NoSuchAlgorithmException e) { log.error("MD5字符串加密异常", e); return null; } } public static void main(String[] args) throws NoSuchAlgorithmException { String plaintext = "Hello Hash!"; String hashValue = hashWithSha256(plaintext); System.out.println("SHA-256 Hash: " + hashValue); String sha = sha(plaintext); System.out.println("SHA: " + sha); String md5 = md5(plaintext); System.out.println("MD5: " + md5); //spring的工具类进行MD5加密 String md5Spring = DigestUtils.md5DigestAsHex(plaintext.getBytes(StandardCharsets.UTF_8)); System.out.println("MD5Spring: " + md5Spring); //commons-codec的工具类进行MD5加密 String md5Commons = org.apache.commons.codec.digest.DigestUtils.md5Hex(plaintext); System.out.println("MD5Commons: " + md5Commons); } }
如果使用 commons-codec 的工具类进行 MD5 加密,可能需要引入下面的依赖:
<dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>${commons.codec.version}</version> </dependency>
4. Base64 编解码
package com.example.demo.util; import java.nio.charset.StandardCharsets; import java.util.Base64; /** * Base64 * * @author wangbo * @date 2024/11/14 */ public class Base64Util { private Base64Util() { } /** * 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); } public static void main(String[] args) { // Base64 编码 String base64Text = Base64Util.encodeBase64("Hello Base64!"); System.out.println("Base64 Encoded: " + base64Text); // Base64 解码 String decodedText = Base64Util.decodeBase64(base64Text); System.out.println("Base64 Decoded: " + decodedText); } }
到此这篇关于Java中常用文本加解密工具类总结的文章就介绍到这了,更多相关Java加解密工具类内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
SpringBoot RestTemplate GET POST请求的实例讲解
这篇文章主要介绍了SpringBoot RestTemplate GET POST请求的实例讲解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-09-09spring boot application properties配置实例代码详解
本文通过代码给大家介绍了spring boot application properties配置方法,需要的的朋友参考下吧2017-07-07
最新评论