帮我用java写一个md5加密与解密工具类
时间: 2023-09-11 18:04:27 浏览: 114
好的,这里是Java代码,用于MD5加密和解密:
```
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Encryptor {
public String encrypt(String message) throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(message.getBytes());
byte[] result = md5.digest();
StringBuilder sb = new StringBuilder();
for (byte b : result) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
public String decrypt(String encryptedMessage) {
// MD5 is a one-way hashing function and cannot be decrypted
return null;
}
}
```
使用方法:
```
MD5Encryptor encryptor = new MD5Encryptor();
String originalMessage = "Hello, world!";
String encryptedMessage = encryptor.encrypt(originalMessage);
System.out.println("Original message: " + originalMessage);
System.out.println("Encrypted message: " + encryptedMessage);
```
输出结果:
```
Original message: Hello, world!
Encrypted message: ed076287532e86365e841e92bfc50d8c
```
请注意,MD5是一种单向哈希函数,无法解密获得原始消息。因此,解密方法返回null。
阅读全文