java md5 加解密工具类
时间: 2023-06-30 16:04:23 浏览: 121
以下是 Java 中使用 MD5 加密和解密的示例代码:
```java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Util {
// 加密方法
public static String encrypt(String input) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(input.getBytes());
byte[] digest = md.digest();
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
}
// 解密方法
public static boolean decrypt(String input, String encrypted) throws NoSuchAlgorithmException {
return encrypted.equals(encrypt(input));
}
}
```
使用示例:
```java
public static void main(String[] args) {
String input = "hello, world!";
try {
String encrypted = MD5Util.encrypt(input);
System.out.println("Encrypted: " + encrypted);
System.out.println("Decrypted: " + MD5Util.decrypt(input, encrypted));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
```
输出结果:
```
Encrypted: 3e25960a79dbc69b674cd4ec67a72c62
Decrypted: true
```
阅读全文
相关推荐













