Java中五种最常见加密算法
在Java中,最常见的加密算法包括:
- AES (Advanced Encryption Standard)
- DES (Data Encryption Standard)
- 3DES
- RSA
- MD5 (Message Digest 5)
以下是每种算法的简单示例代码:
- AES加密:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESEncryption {
public static String encrypt(String data, String key) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
}
}
- DES加密:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class DESEncryption {
public static String encrypt(String data, String key) throws Exception {
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), "DES"));
return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
}
}
- 3DES加密:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class TripleDESEncryption {
public static String encrypt(String data, String key) throws Exception {
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(), "DESede"));
return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
}
}
- RSA加密:
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Base64;
import javax.crypto.Cipher;
public class RSAEncryption {
public static String encrypt(String data, String publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, KeyPairGenerator.getInstance("RSA").generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey))));
return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
}
}
- MD5加密:
import java.security.MessageDigest;
public class MD5Encryption {
public static String encrypt(String data) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5
评论已关闭