Java Base64加密与MD5加密
程序员文章站
2024-03-20 10:12:04
...
今天遇到一个项目需求,发送出的字符串要用Base64和MD5加密。
Java的实现如下:
//调用
String username = base64Encode("test1");
String password = toMD5("1");
System.out.println("username:" + username);
System.out.println("password:" + password);
//定义
public static String base64Encode(String str) {
Base64.Encoder encoder = Base64.getEncoder();
byte[] textByte = new byte[0];
try {
textByte = str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String encodedText = encoder.encodeToString(textByte);
return encodedText;
}
public static String toMD5(String str) {
byte[] secretBytes = null;
try {
secretBytes = MessageDigest.getInstance("md5").digest(str.getBytes());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
String md5code = new BigInteger(1, secretBytes).toString(16);
for (int i = 0; i < 32 - md5code.length(); i++) {
md5code = "0" + md5code;
}
return md5code;
}
加密后的输出: