一、MD5加密解密工具類
MD5加密演算法是一種常見的加密演算法,通常用於對密碼、數字簽名等敏感信息進行加密處理,以確保數據的安全性。在Java編程中,我們可以使用如下的工具類來實現MD5加密解密功能:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class EncryptUtil {
public static final String KEY_MD5 = "MD5";
public static String encryptMD5(String data) {
byte[] inputData = data.getBytes();
MessageDigest md;
String md5Str = "";
try {
md = MessageDigest.getInstance(KEY_MD5);
byte[] md5Bytes = md.digest(inputData);
md5Str = toHexString(md5Bytes);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return md5Str;
}
private static String toHexString(byte[] byteArray) {
StringBuilder hexString = new StringBuilder();
for (byte b : byteArray) {
String hex = Integer.toHexString(0xFF & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
}
首先,我們定義了一個常量KEY_MD5,表示使用MD5演算法進行加密;然後,通過encryptMD5()方法,傳入需要加密的數據進行處理;toHexString()方法將加密後的位元組數組以十六進位的形式返回。
在使用時,只需要將需要加密的原始數據傳入encryptMD5()方法中即可:
String encryptedStr = EncryptUtil.encryptMD5("password");
以上代碼將會把字元串”password”進行MD5加密,並返回加密後的字元串。
二、Base64編碼解碼工具類
Base64編碼是一種用於將任意二進位數據編碼成純文本的方法,通常用於在HTTP協議傳輸中發送明文字元串。在Java編程中,我們可以使用如下的Base64工具類來實現編碼解碼功能:
import java.util.Base64;
public class EncodeUtil {
public static String encode(String data) {
return Base64.getEncoder().encodeToString(data.getBytes());
}
public static String decode(String encodedStr) {
byte[] decodedBytes = Base64.getDecoder().decode(encodedStr);
return new String(decodedBytes);
}
}
以上代碼通過調用Java 8提供的Base64 API實現了編碼解碼功能。在encode()方法中,我們將字元串轉換為二進位數據後通過Base64.getEncoder()進行編碼,並將結果以字元串形式返回;在decode()方法中,對Base64編碼後的字元串進行解碼,並將結果轉換為字元串返回。以下是使用示例:
String encodedStr = EncodeUtil.encode("hello world");
String decodedStr = EncodeUtil.decode(encodedStr);
以上代碼將會對字元串”hello world”進行Base64編碼,並將結果轉換為字元串。接著再對編碼後的字元串進行解碼,得到原始的字元串。
三、AES加密解密工具類
AES(Advanced Encryption Standard)是一種常用的對稱加密演算法,通常用於加密敏感信息以保證數據的安全性。在Java編程中,我們可以使用如下的AES工具類來實現加密解密功能:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AESUtil {
private static final String AES = "AES";
private static SecretKeySpec generateKey(String password) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(AES);
keyGenerator.init(128);
SecretKey secretKey = keyGenerator.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
return new SecretKeySpec(enCodeFormat, AES);
}
public static String encrypt(String data, String password) throws Exception {
SecretKeySpec secretKeySpec = generateKey(password);
Cipher cipher = Cipher.getInstance(AES);// 創建密碼器
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);// 初始化
byte[] result = cipher.doFinal(data.getBytes("UTF-8"));
return toHexString(result); // 加密
}
public static String decrypt(String data, String password) throws Exception {
SecretKeySpec secretKeySpec = generateKey(password);
Cipher cipher = Cipher.getInstance(AES);// 創建密碼器
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);// 初始化
byte[] result = cipher.doFinal(hexStringToBytes(data)); // 加密
return new String(result,"UTF-8"); // 解密
}
private static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
private static String toHexString(byte[] byteArray) {
StringBuilder hexString = new StringBuilder();
for (byte b : byteArray) {
String hex = Integer.toHexString(0xFF & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
}
在AESUtil類中,我們定義了一個常量AES表示使用AES加密演算法進行加密;generateKey()方法用於生成加密密鑰;encrypt()方法將原始數據進行AES加密後返回加密結果;decrypt()方法用於將加密後的數據進行解密。使用示例:
String encryptedStr = AESUtil.encrypt("Hello World", "password");
String decryptedStr = AESUtil.decrypt(encryptedStr, "password");
這裡的encrypt()和decrypt()方法分別用於加密和解密原始數據。首先,我們將需要加密的數據和密鑰傳入encrypt()方法中,得到加密後的字元串;然後再將加密後的字元串和密鑰傳入decrypt()方法中,得到原始字元串。
四、RSA加密解密工具類
RSA(Rivest-Shamir-Adleman)是一種非對稱加密演算法,通常用於加密較小長度的文本或數據傳輸中的密鑰。在Java編程中,我們可以使用如下的RSA工具類來實現加密解密功能:
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
public class RSAUtil {
private static final String RSA = "RSA";
/**
* 生成密鑰對
*/
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA);
keyPairGenerator.initialize(1024);
return keyPairGenerator.generateKeyPair();
}
/**
* 從公鑰中獲取公鑰對象
*/
public static PublicKey getPublicKey(byte[] publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
return keyFactory.generatePublic(publicKeySpec);
}
/**
* 從私鑰中獲取私鑰對象
*/
public static PrivateKey getPrivateKey(byte[] privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKey);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
return keyFactory.generatePrivate(privateKeySpec);
}
/**
* 公鑰加密
*/
public static byte[] encrypt(byte[] data, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
}
/**
* 私鑰解密
*/
public static byte[] decrypt(byte[] data, PrivateKey privateKey) throws Exception {
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
}
/**
* 獲取公鑰密鑰字元串
*/
public static String getKeyString(Key key) {
byte[] keyBytes = key.getEncoded();
return toHexString(keyBytes);
}
private static String toHexString(byte[] byteArray) {
StringBuilder hexString = new StringBuilder();
for (byte b : byteArray) {
String hex = Integer.toHexString(0xFF & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
}
在RSAUtil類中,我們定義了一個常量RSA表示使用RSA非對稱加密演算法進行加密;generateKeyPair()方法用於生成公鑰和私鑰對;getPublicKey()方法使用公鑰的位元組數組獲取公鑰對象;getPrivateKey()方法使用私鑰的位元組數組獲取私鑰對象;encrypt()方法將原始數據使用公鑰進行加密後返回加密數據的位元組數組;encrypt()方法將加密後的數據使用私鑰進行解密後返回原始數據的位元組數組。使用示例:
//生成公鑰和私鑰
KeyPair keyPair = RSAUtil.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
//使用公鑰對數據進行加密
byte[] encryptedData = RSAUtil.encrypt("Hello World".getBytes(), publicKey);
//使用私鑰對加密後的數據進行解密
byte[] decryptedData = RSAUtil.decrypt(encryptedData, privateKey);
//將解密得到的位元組數組轉換為字元串
String decryptedStr = new String(decryptedData);
以上代碼將會生成RSA公鑰和私鑰,並使用公鑰對字元串”Hello World”進行加密,接著再使用私鑰對加密後的數據進行解密,得到原始數據的位元組數組,最後將位元組數組轉換為字元串形式輸出。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/232022.html