Java工具类,对字符串加解密生成12位包含大写字母和数字的字符串,相同字符串加密后值相同
时间: 2023-04-12 08:01:30 浏览: 306
可以使用Java的MessageDigest类和Base64编码实现字符串加解密,以下是示例代码:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
public class StringUtil {
private static final String ALGORITHM = "MD5";
private static final String CHARSET = "UTF-8";
private static final int LENGTH = 12;
public static String encrypt(String str) {
try {
MessageDigest md = MessageDigest.getInstance(ALGORITHM);
byte[] bytes = md.digest(str.getBytes(CHARSET));
return Base64.encode(bytes).substring(0, LENGTH);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String generateRandomString() {
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < LENGTH; i++) {
int index = random.nextInt(chars.length());
sb.append(chars.charAt(index));
}
return sb.toString();
}
}
其中,encrypt方法用于加密字符串,generateRandomString方法用于生成随机字符串。使用方法如下:
String str = "hello";
String encryptedStr = StringUtil.encrypt(str);
String randomStr = StringUtil.generateRandomString();
System.out.println(encryptedStr);
System.out.println(randomStr);
输出结果类似于:
5DQ8ZJ5UJn5x
7FJ8K6L9M2N0
每次加密相同的字符串,得到的结果都是相同的。
阅读全文