1. 引言
在軟件開發(fā)中,數(shù)據(jù)的安全性是一個重要的考慮因素。為了保護(hù)敏感數(shù)據(jù),我們經(jīng)常需要對數(shù)據(jù)進(jìn)行加密和解密操作。為了簡化加密解密操作,提高開發(fā)效率,我們可以使用一個常用的加密解密工具類。本文將介紹一個常用的 Java 加密解密工具類,并提供詳細(xì)的使用說明和示例。
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;
}
}
/**
* 根據(jù)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;
}
}
/**
* 根據(jù)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);
}
/**
* 將字節(jié)數(shù)組轉(zhuǎn)換為十六進(jìn)制字符串
*
* @param bytes 字節(jié)數(shù)組
* @return 十六進(jìn)制字符串
*/
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 內(nèi)容
* @return 十六進(jìn)制字符串
*/
public static String encodeBase64(String plainText) {
byte[] plainBytes = plainText.getBytes(StandardCharsets.UTF_8);
return Base64.getEncoder().encodeToString(plainBytes);
}
/**
* Base64 解碼
*
* @param base64Text 十六進(jìn)制字符串
* @return 內(nèi)容
*/
public static String decodeBase64(String base64Text) {
byte[] base64Bytes = Base64.getDecoder().decode(base64Text);
return new String(base64Bytes, StandardCharsets.UTF_8);
}
}
4. 結(jié)論
通過使用上述的 EncryptionUtil 工具類,我們可以方便地進(jìn)行常見的加密解密操作,提高開發(fā)效率。
通過合理的使用示例和詳細(xì)的注釋,開發(fā)人員可以快速掌握該工具類的使用方法,并在實際項目中應(yīng)用它。
以下是 EncryptionUtil 工具類的使用示例:文章來源:http://www.zghlxwxcb.cn/news/detail-781984.html
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();
}
}
}
以上是關(guān)于常用的加密解密工具類的詳細(xì)介紹及使用示例。希望本文對你在日常開發(fā)中的加密解密需求有所幫助。如果你有任何問題或建議,歡迎在下方留言。文章來源地址http://www.zghlxwxcb.cn/news/detail-781984.html
到了這里,關(guān)于Java常用的加密解密工具類的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!