MD5 加密
MD5(Message-Digest Algorithm 5)是一种常用的哈希函数,可以将任意长度的数据转换为固定长度的哈希值。Java 中可以使用 java.security.MessageDigest 类来实现 MD5 加密,具体代码如下:
```c
```java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Util {
public static String encrypt(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : messageDigest) {
hexString.append(String.format("%02x", b & 0xff));
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("MD5 encryption failed: " + e.getMessage());
}
}
}
SHA 加密
SHA(Secure Hash Algorithm)是一种安全哈希算法,可以将任意长度的数据转换为固定长度的哈希值。Java 中可以使用 java.security.MessageDigest 类来实现 SHA 加密,具体代码如下:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHAUtil {
public static String encrypt(String input) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] messageDigest = md.digest(input.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : messageDigest) {
hexString.append(String.format("%02x", b & 0xff));
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA-256 encryption failed: " + e.getMessage());
}
}
}
AES 加密
AES(Advanced Encryption Standard)是一种高级加密标准,可以用来加密和解密数据。Java 中可以使用 javax.crypto.Cipher 类来实现 AES 加密,具体代码如下:
public class AESUtils {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
private static final String KEY = "mysecretkey12345"; // 密钥,长度为16字节
//字符串加密
public static String encrypt(String plainText) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] encrypted = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encrypted);
}
//字符串解密
public static String decrypt(String cipherText) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(cipherText));
return new String(decrypted);
}
}
以上是 Java 中常用的加密方法之一。请注意,加密算法并不是万能的,不同的加密算法适用于不同的场景,需要根据具体情况选择合适的加密算法。同时,在实际应用中,还需要注意加密算法的安全性,避免出现加密被破解的情况。