Java如何加密string
使用Java内置的MessageDigest进行哈希加密
哈希加密(如MD5、SHA-256)适用于不可逆的场景,如密码存储。以下示例使用SHA-256:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class HashExample {
public static String encryptSHA256(String input) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = digest.digest(input.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : hashBytes) {
hexString.append(String.format("%02x", b));
}
return hexString.toString();
}
}
调用方法:encryptSHA256("yourString")返回16进制哈希值。
使用对称加密(AES)
AES加密需密钥,适用于可逆加密场景。需依赖javax.crypto包:

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.Base64;
public class AESExample {
public static SecretKey generateKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(256); // 密钥长度
return keyGenerator.generateKey();
}
public static String encryptAES(String input, SecretKey key) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(input.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
}
生成密钥后调用encryptAES("text", key),返回Base64编码的密文。
使用非对称加密(RSA)
RSA通过公钥加密、私钥解密,适用于安全传输场景:

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import javax.crypto.Cipher;
import java.util.Base64;
public class RSAExample {
public static KeyPair generateKeyPair() throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
return generator.generateKeyPair();
}
public static String encryptRSA(String input, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(input.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
}
调用encryptRSA("data", keyPair.getPublic())加密数据。
使用第三方库(如Bouncy Castle)
如需更多算法(如ChaCha20),可添加Bouncy Castle依赖:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.70</version>
</dependency>
示例代码:
import org.bouncycastle.crypto.engines.ChaChaEngine;
import org.bouncycastle.crypto.params.KeyParameter;
public class BouncyCastleExample {
public static byte[] encryptChaCha(byte[] input, byte[] key) {
ChaChaEngine cipher = new ChaChaEngine();
cipher.init(true, new KeyParameter(key));
byte[] output = new byte[input.length];
cipher.processBytes(input, 0, input.length, output, 0);
return output;
}
}
注意事项
- 哈希加密不可逆,适合存储密码(需加盐防彩虹表攻击)。
- AES密钥需安全存储,避免硬编码。
- RSA加密大数据时需分段处理(默认限制245字节)。
- 生产环境推荐使用TLS/SSL等协议替代手动加密。






