Java 加密 (Encrypt) 指南
Java 提供了多种加密方式,以下是一些常见的加密实现方法:

对称加密 (AES)
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESEncryption {
private static final String ALGORITHM = "AES";
// 生成AES密钥
public static String generateKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
keyGenerator.init(256); // 256位密钥
SecretKey secretKey = keyGenerator.generateKey();
return Base64.getEncoder().encodeToString(secretKey.getEncoded());
}
// 加密
public static String encrypt(String data, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encrypted = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
// 解密
public static String decrypt(String encryptedData, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decoded = Base64.getDecoder().decode(encryptedData);
byte[] decrypted = cipher.doFinal(decoded);
return new String(decrypted);
}
public static void main(String[] args) throws Exception {
String originalData = "这是一个秘密消息";
String key = generateKey();
String encrypted = encrypt(originalData, key);
System.out.println("加密后: " + encrypted);
String decrypted = decrypt(encrypted, key);
System.out.println("解密后: " + decrypted);
}
}
非对称加密 (RSA)
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class RSAEncryption {
public static KeyPair generateKeyPair() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
}
public static String encrypt(String data, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encrypted = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
public static String decrypt(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);
}
public static String publicKeyToString(PublicKey publicKey) {
return Base64.getEncoder().encodeToString(publicKey.getEncoded());
}
public static String privateKeyToString(PrivateKey privateKey) {
return Base64.getEncoder().encodeToString(privateKey.getEncoded());
}
public static PublicKey stringToPublicKey(String publicKeyStr) throws Exception {
byte[] decoded = Base64.getDecoder().decode(publicKeyStr);
X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(spec);
}
public static PrivateKey stringToPrivateKey(String privateKeyStr) throws Exception {
byte[] decoded = Base64.getDecoder().decode(privateKeyStr);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePrivate(spec);
}
public static void main(String[] args) throws Exception {
String originalData = "这是一个秘密消息";
KeyPair keyPair = generateKeyPair();
String publicKeyStr = publicKeyToString(keyPair.getPublic());
String privateKeyStr = privateKeyToString(keyPair.getPrivate());
System.out.println("公钥: " + publicKeyStr);
System.out.println("私钥: " + privateKeyStr);
String encrypted = encrypt(originalData, stringToPublicKey(publicKeyStr));
System.out.println("加密后: " + encrypted);
String decrypted = decrypt(encrypted, stringToPrivateKey(privateKeyStr));
System.out.println("解密后: " + decrypted);
}
}
哈希加密 (SHA-256)
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHA256Hash {
public static String hash(String input) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = md.digest(input.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : hashBytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
String originalString = "这是一个需要哈希的字符串";
String hashedString = hash(originalString);
System.out.println("原始字符串: " + originalString);
System.out.println("SHA-256哈希: " + hashedString);
}
}
PBKDF2 密码哈希
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
public class PBKDF2Hash {
private static final int ITERATIONS = 10000;
private static final int KEY_LENGTH = 256;
private static final String ALGORITHM = "PBKDF2WithHmacSHA256";
public static String hashPassword(String password, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), ITERATIONS, KEY_LENGTH);
SecretKeyFactory skf = SecretKeyFactory.getInstance(ALGORITHM);
byte[] hash = skf.generateSecret(spec).getEncoded();
return Base64.getEncoder().encodeToString(hash);
}
public static String generateSalt() {
SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);
return Base64.getEncoder().encodeToString(salt);
}
public static boolean verifyPassword(String originalPassword, String storedHash, String salt)
throws NoSuchAlgorithmException, InvalidKeySpecException {
String newHash = hashPassword(originalPassword, salt);
return newHash.equals(storedHash);
}
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException {
String password = "mySecurePassword123";
String salt = generateSalt();
String hashedPassword = hashPassword(password, salt);
System.out.println("密码哈希: " + hashedPassword);
System.out.println("盐值: " + salt);
boolean isValid = verifyPassword(password, hashedPassword, salt);
System.out.println("密码验证结果: " + isValid);
}
}
注意事项
- 密钥管理:在实际应用中,密钥的安全存储和管理非常重要,不要硬编码密钥在代码中
- 算法选择:根据安全需求选择合适的加密算法和密钥长度
- 异常处理:加密操作可能抛出各种异常,需要妥善处理
- 性能考虑:对称加密比非对称加密快,通常用于大量数据加密
- IV向量:对于某些加密模式(如CBC),需要使用初始化向量(IV)
代码示例提供了基本的加密功能,实际应用中可能需要根据具体需求进行调整。

