Java 函数实现字符串加密和解密
字符串加密和解密是现代密码学的基础,也是网络应用中常见的安全需求,Java 作为一门广泛应用于企业级应用的高级编程语言,提供了许多实现字符串加密和解密的函数。本文将简要介绍 Java 中常用的字符串加密和解密函数的实现原理和使用方法。
1. MD5 加密
MD5 是一种常用的密码加密算法,它将任意长度的消息作为输入,经过一系列复杂的运算,得到一个 128 位长的输出。Java 中提供了 java.security.MessageDigest 类来实现 MD5 加密功能。该类具有如下方法:
public static MessageDigest getInstance(String algorithm) throws NoSuchAlgorithmException; public void update(byte[] input); public void update(byte[] input, int offset, int len); public byte[] digest();
其中,getInstance 方法用于获取指定算法的 MessageDigest 实例,update 方法用于向实例中添加数据,digest 方法用于计算实例的摘要值并返回 byte 数组。以下是一个 MD5 加密的简单实现:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5 {
public static String encrypt(String plaintext) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(plaintext.getBytes("UTF-8"));
byte[] cipherBytes = md5.digest();
StringBuilder sb = new StringBuilder();
for (byte b : cipherBytes) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
System.out.println(encrypt("hello world"));
}
}
2. Base64 编码
Base64 编码是将任意二进制数据转换为可打印字符的一种编码方式,常用于在邮件、网页中传输数据。Java 中提供了 java.util.Base64 类来实现 Base64 编码和解码。该类具有如下方法:
public static Encoder getEncoder(); public static Decoder getDecoder();
其中,getEncoder 方法用于获取编码器实例,getDecoder 方法用于获取解码器实例。以下是一个 Base64 编码的简单实现:
import java.util.Base64;
public class Base64Demo {
public static String encrypt(String plaintext) {
byte[] plainBytes = plaintext.getBytes();
return Base64.getEncoder().encodeToString(plainBytes);
}
public static String decrypt(String ciphertext) {
byte[] cipherBytes = Base64.getDecoder().decode(ciphertext);
return new String(cipherBytes);
}
public static void main(String[] args) {
String plaintext = "hello world";
String ciphertext = encrypt(plaintext);
System.out.println("ciphertext: " + ciphertext);
String plaintext2 = decrypt(ciphertext);
System.out.println("plaintext2: " + plaintext2);
}
}
3. DES 加密
DES 是一种对称加密算法,它使用相同的密钥进行加密和解密。Java 中提供了 javax.crypto.Cipher 类来实现 DES 加密和解密。该类具有如下方法:
public static Cipher getInstance(String transformation) throws NoSuchAlgorithmException, NoSuchPaddingException; public void init(int opmode, Key key) throws InvalidKeyException; public void init(int opmode, Key key, AlgorithmParameterSpec params) throws InvalidKeyException, InvalidAlgorithmParameterException; public byte[] doFinal(byte[] input) throws IllegalBlockSizeException, BadPaddingException;
其中,getInstance 方法用于获取 Cipher 实例,opmode 参数表示加密还是解密,key 参数表示密钥,AlgorithmParameterSpec 参数表示加密的参数。doFinal 方法用于加密或解密数据并返回 byte 数组。以下是一个 DES 加密的简单实现:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class DESDemo {
private static Cipher cipher;
private static SecretKey key;
static {
try {
cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
keyGenerator.init(56);
key = keyGenerator.generateKey();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static byte[] encrypt(String plaintext) {
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(plaintext.getBytes());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static byte[] decrypt(byte[] ciphertext) {
try {
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(ciphertext);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
String plaintext = "hello world";
byte[] ciphertext = encrypt(plaintext);
System.out.println("ciphertext: " + new String(ciphertext));
byte[] plaintext2Bytes = decrypt(ciphertext);
String plaintext2 = new String(plaintext2Bytes);
System.out.println("plaintext2: " + plaintext2);
}
}
4. RSA 加密
RSA 是一种非对称加密算法,它使用公钥加密数据,私钥解密数据。Java 中提供了 java.security.KeyPairGenerator、java.security.KeyPair、java.security.Key、javax.crypto.Cipher 类来实现 RSA 加密和解密。下面是一个 RSA 加密的简单实现:
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
public class RSADemo {
private static KeyPair keyPair;
private static PublicKey publicKey;
private static PrivateKey privateKey;
static {
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
keyPair = keyPairGenerator.generateKeyPair();
publicKey = keyPair.getPublic();
privateKey = keyPair.getPrivate();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static byte[] encrypt(String plaintext) {
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(plaintext.getBytes());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static byte[] decrypt(byte[] ciphertext) {
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(ciphertext);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
String plaintext = "hello world";
byte[] ciphertext = encrypt(plaintext);
System.out.println("ciphertext: " + new String(ciphertext));
byte[] plaintext2Bytes = decrypt(ciphertext);
String plaintext2 = new String(plaintext2Bytes);
System.out.println("plaintext2: " + plaintext2);
}
}
总结:本文主要介绍了 Java 中常用的字符串加密和解密函数的实现原理和使用方法,分别介绍了 MD5 加密、Base64 编码、DES 加密、RSA 加密。这些函数在企业级应用中有着广泛的应用,是保障数据安全的基础。
