用java写一个MD5加密和解密的工具类
时间: 2024-03-25 11:41:44 浏览: 225
以下是Java编写的MD5加密和解密的工具类:
```java
import java.security.MessageDigest;
public class MD5Util {
/**
* 将字符串进行MD5加密
*
* @param plainText 需要加密的字符串
* @return 加密后的字符串
*/
public static String encrypt(String plainText) {
String result = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(plainText.getBytes());
byte[] bytes = md.digest();
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xFF & b);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* MD5解密无法实现,因为MD5是单向加密的,只能加密,不能解密
*/
public static void main(String[] args) {
String str = "Hello World";
String md5Str = encrypt(str);
System.out.println("加密前:" + str);
System.out.println("加密后:" + md5Str);
}
}
```
以上是一个简单的MD5加密工具类,可以将任意字符串进行MD5加密,但无法实现MD5解密,因为MD5是单向加密的。
阅读全文
相关推荐












