原文链接:常见的加密算法 – 每天进步一点点
0.前言
日常开发中,经常能用到加密解密算法,最常见的就是用户的密码了,登录过程中,类似用户密码这种肯定不能明文传输。除此之外,还有一些银行卡号,身份证号,还有一些敏感接口的数据等也要加密。
那么,我们就需要一些方法对上面的内容进行加密和解密。
1.常见的加密算法
常见的加密算法可以分为不可逆加密和可逆加密。
可逆加密又分对称加密和非对称加密。
不可逆加密算法包括:MD5、HMAC、SHA1、SHA-224、SHA-256…
可逆中的对称加密:DES、AES…
可逆中的非对称加密:RSA…
2.不可逆加密
不可逆加密的算法的加密是不可逆的,密文无法被还原成原文。
散列算法,就是一种不可逆算法。散列算法中,明文通过散列算法生成散列值,散列值是长度固定的数据,和明文长度无关。

散列算法的具体实现有很多种,常见的包括MD5、SHA1、SHA-224、SHA-256等等。
散列算法常用于数字签名、消息认证、密码存储等场景。
散列算法是不需要密钥的,当然也有一些不可逆算法,需要密钥,例如HMAC算法。
MD5:
MD5,全称为“Message-Digest Algorithm 5”,翻译过来叫“信息摘要算法”。它可以将任意长度的数据通过散列算法,生成一个固定长度的散列值。MD5算法的输出长度为128位,通常用32个16进制数表示。
MD5算法的Java代码实现:
private static final String MD5_ALGORITHM = "MD5";
public static String encrypt(String data) throws Exception {
MessageDigest messageDigest = MessageDigest.getInstance(MD5_ALGORITHM);
byte[] digest = messageDigest.digest(data.getBytes());
Formatter formatter = new Formatter();
formatter.format("%02x", b);
return formatter.toString();
public static void main(String[] args) throws Exception {
String data = "Hello World";
String encryptedData = encrypt(data);
System.out.println("加密后的数据:" + encryptedData);
MD5有一些优点,比如计算速度快、输出长度固定、应用广泛等等。
但是作为一个加密算法,它有一个天大的缺点,那就是不安全
。
MD5算法已经被攻破,而且MD5算法的输出长度有限,攻击者可以通过暴力破解或彩虹表攻击等方式,找到与原始数据相同的散列值(“撞库”),从而破解数据。
虽然可以通过加盐,也就是对在原文里再加上一些不固定的字符串来缓解,但是完全可以用更安全的SHA系列算法替代。
SHA-256
SHA(Secure Hash Algorithm)系列算法是一组密码散列函数,用于将任意长度的数据映射为固定长度的散列值。SHA系列算法由美国国家安全局(NSA)于1993年设计,目前共有SHA-1、SHA-2、SHA-3三种版本。
其中SHA-1系列存在缺陷,已经不再被推荐使用。
SHA-2算法包括SHA-224
、SHA-256
、SHA-384
和SHA-512
四种散列函数,分别将任意长度的数据映射为224位、256位、384位和512位的散列值。
最常用的SHA-256
的Java代码实现
private static final String SHA_256_ALGORITHM = "SHA-256";
public static String encrypt(String data) throws Exception {
MessageDigest messageDigest = MessageDigest.getInstance(SHA_256_ALGORITHM);
byte[] digest = messageDigest.digest(data.getBytes());
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(Integer.toHexString((b & 0xFF) | 0x100), 1, 3);
return stringBuilder.toString();
public static void main(String[] args) throws Exception {
String data = "Hello World";
String encryptedData = encrypt(data);
System.out.println("加密后的数据:" + encryptedData);
SHA-2算法之所以比MD5强,主要有两个原因:
- 散列值长度更长:例如SHA-256算法的散列值长度为256位,而MD5算法的散列值长度为128位,这就提高了攻击者暴力破解或者彩虹表攻击的难度。
- 更强的碰撞抗性:SHA算法采用了更复杂的运算过程和更多的轮次,使得攻击者更难以通过预计算或巧合找到碰撞。
当然,SHA-2也不是绝对安全的,散列算法都有被暴力破解或者彩虹表攻击的风险,所以,在实际的应用中,加盐还是必不可少的。
3.对称加密算法
对称加密算法,使用同一个密钥进行加密和解密。

加密和解密过程使用的是相同的密钥,因此密钥的安全性至关重要。如果密钥泄露,攻击者可以轻易地破解加密数据。
常见的对称加密算法包括DES、3DES、AES等。其中,AES算法是目前使用最广泛的对称加密算法之一,具有比较高的安全性和加密效率。
DES:
DES(Data Encryption Standard)算法是一种对称加密算法,由IBM公司于1975年研发,是最早的一种广泛应用的对称加密算法之一。
DES算法使用56位密钥对数据进行加密,加密过程中使用了置换、替换、异或等运算,具有较高的安全性。
ES算法的Java代码实现:
private static final String DES_ALGORITHM = "DES";
* @return 加密后的数据,使用Base64编码
public static String encrypt(String data, String key) throws Exception {
KeySpec keySpec = new DESKeySpec(key.getBytes());
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(DES_ALGORITHM);
SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
Cipher cipher = Cipher.getInstance(DES_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedData = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedData);
* @param encryptedData 加密后的数据,使用Base64编码
public static String decrypt(String encryptedData, String key) throws Exception {
KeySpec keySpec = new DESKeySpec(key.getBytes());
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(DES_ALGORITHM);
SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
byte[] decodedData = Base64.getDecoder().decode(encryptedData);
Cipher cipher = Cipher.getInstance(DES_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedData = cipher.doFinal(decodedData);
return new String(decryptedData);
public static void main(String[] args) throws Exception {
String data = "Hello World";
String encryptedData = encrypt(data, key);
System.out.println("加密后的数据:" + encryptedData);
String decryptedData = decrypt(encryptedData, key);
System.out.println("解密后的数据:" + decryptedData);
DES的算法速度较快,但是在安全性上面并不是最优选择,因为DES算法的密钥长度比较短,被暴力破解和差分攻击的风险比较高,一般推荐用一些更安全的对称加密算法,比如3DES、AES。
AES:
AES(Advanced Encryption Standard)即高级加密标准,是一种对称加密算法,被广泛应用于数据加密和保护领域。AES算法使用的密钥长度为128位、192位或256位,比DES算法的密钥长度更长,安全性更高。
AES算法的Java代码实现:
private static final String AES_ALGORITHM = "AES";
// AES加密模式为CBC,填充方式为PKCS5Padding
private static final String AES_TRANSFORMATION = "AES/CBC/PKCS5Padding";
private static final String AES_KEY = "1234567890123456";
private static final String AES_IV = "abcdefghijklmnop";
* @return 加密后的数据,使用Base64编码
public static String encrypt(String data) throws Exception {
// 将AES密钥转换为SecretKeySpec对象
SecretKeySpec secretKeySpec = new SecretKeySpec(AES_KEY.getBytes(), AES_ALGORITHM);
// 将AES初始化向量转换为IvParameterSpec对象
IvParameterSpec ivParameterSpec = new IvParameterSpec(AES_IV.getBytes());
Cipher cipher = Cipher.getInstance(AES_TRANSFORMATION);
// 初始化加密器,设置加密模式、密钥和初始化向量
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedData);
* @param encryptedData 加密后的数据,使用Base64编码
public static String decrypt(String encryptedData) throws Exception {
// 将AES密钥转换为SecretKeySpec对象
SecretKeySpec secretKeySpec = new SecretKeySpec(AES_KEY.getBytes(), AES_ALGORITHM);
// 将AES初始化向量转换为IvParameterSpec对象
IvParameterSpec ivParameterSpec = new IvParameterSpec(AES_IV.getBytes());
Cipher cipher = Cipher.getInstance(AES_TRANSFORMATION);
// 初始化解密器,设置解密模式、密钥和初始化向量
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decodedData = Base64.getDecoder().decode(encryptedData);
byte[] decryptedData = cipher.doFinal(decodedData);
return new String(decryptedData, StandardCharsets.UTF_8);
public static void main(String[] args) throws Exception {
String data = "Hello World";
String encryptedData = encrypt(data);
System.out.println("加密后的数据:" + encryptedData);
String decryptedData = decrypt(encryptedData);
System.out.println("解密后的数据:" + decryptedData);
AES算法采用的密钥长度更长,密钥空间更大,安全性更高,能够有效地抵抗暴力破解攻击。
当然,因为密钥长度较长,需要的存储也更多。
对于对称加密算法而言,最大的痛点就在于密钥管理困难,相比而言,非对称加密就没有这个担忧。
4.非对称加密
非对称加密算法需要两个密钥,这两个密钥互不相同,但是相互匹配,一个称为公钥,另一个称为私钥。
使用其中的一个加密,则使用另一个进行解密。例如使用公钥加密,则需要使用私钥解密。

RSA
RSA算法是是目前应用最广泛的非对称加密算法,由Ron Rivest、Adi Shamir和Leonard Adleman三人在1978年发明,名字来源三人的姓氏首字母。
RSA算法的Java实现:
private static final String RSA_ALGORITHM = "RSA";
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA_ALGORITHM);
keyPairGenerator.initialize(2048); // 密钥大小为2048位
return keyPairGenerator.generateKeyPair();
public static String encrypt(String data, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedData);
* @param encryptedData 加密后的数据
public static String decrypt(String encryptedData, PrivateKey privateKey) throws Exception {
byte[] decodedData = Base64.getDecoder().decode(encryptedData);
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedData = cipher.doFinal(decodedData);
return new String(decryptedData, StandardCharsets.UTF_8);
public static void main(String[] args) throws Exception {
KeyPair keyPair = generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
String data = "Hello World";
String encryptedData = encrypt(data, publicKey);
System.out.println("加密后的数据:" + encryptedData);
String decryptedData = decrypt(encryptedData, privateKey);
System.out.println("解密后的数据:" + decryptedData);
RSA算法的优点是安全性高,公钥可以公开,私钥必须保密,保证了数据的安全性;可用于数字签名、密钥协商等多种应用场景。
缺点是加密、解密速度较慢,密钥长度越长,加密、解密时间越长;密钥长度过短容易被暴力破解,密钥长度过长则会增加计算量和存储空间的开销。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具