我们在工作中,会遇到各种加密,这里将最常见的加密方式通过工具类,对字符串进行加密。
public static void main(String[] args) {
System.out.println("加密之前:"+"123456789abcdf");
String indexMd5 = SignUtils.getMD5("123456789abcdf");
System.out.println("加密之后:"+indexMd5);
}
public class SignUtils {
private static final String MD_STR = "MD5";
private static final String CODING_UTF8 = "UTF-8";
public static String getMD5(String info) {
try {
//获取 messageDigst 对象,参数为 MD5 字符,
// 表示这是MD5 算法(其他还有 SHA1 算法)
MessageDigest md5 = MessageDigest.getInstance(MD_STR);
//update(byte[]) ,输入原数据
//类似stringBuilder 对象的append() 方法,追加模式,属于一个累计更改的过程
md5.update(info.getBytes(CODING_UTF8));
//disgest() 被调用,MessageDigest对象被重置,既不能联系再次调用该方法计算原数据的MD5
byte[] md5Array = md5.digest();
return bytesToHex1(md5Array);
} catch (UnsupportedEncodingException e) {
return "";
} catch (NoSuchAlgorithmException e) {
return "";
}
}
private static String bytesToHex1(byte[] md5Array) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < md5Array.length; i++) {
//防止转变int的前24位防止 负号反码,让24高位为0
int temp = 0xff & md5Array[i];
String hexString = Integer.toHexString(temp);
//如果是16进制的of,默认只显示f,此时要补0
if (hexString.length() == 1) {
stringBuilder.append("0").append(hexString);
} else {
stringBuilder.append(hexString);
}
}
return stringBuilder.toString();
}
//通过java提供的BigInteger 完成byte->HexString
private static String bytesToHex2(byte[] md5Array) {
BigInteger bigInt = new BigInteger(1, md5Array);
return bigInt.toString(16);
}
//通过为运算,将字节数据到16进制的转化
public static String bytesToHex3(byte[] byteArray) {
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
char[] resultArray = new char[byteArray.length * 2];
int index = 0;
for (byte b : byteArray) {
resultArray[index++] = hexDigits[b >> 4 & 0xf];
resultArray[index++] = hexDigits[b & 0xf];
}
return new String(resultArray);
}
}