本文提供了基于MD5加密16位和32位的方法,具体内容如下
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import sun.misc.base64Decoder;
import sun.misc.base64Encoder;
public class EncodeUtil
{
public static void main(String[] args) throws Exception
{
System.out.println(md5Encrypt16("需要进行MD5加密的字符串"));
}
public static String md5Encrypt16(String encryptStr)
{
return md5Encrypt32(encryptStr).substring(8, 24);
}
public static String md5Encrypt32(String encryptStr)
{
MessageDigest md5;
try
{
md5 = MessageDigest.getInstance("MD5");
byte[] md5Bytes = md5.digest(encryptStr.getBytes());
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++)
{
int val = (md5Bytes[i]) & 0xff;
if (val < 16)
{
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString().toLowerCase();
} catch (Exception e)
{
throw new RuntimeException(e);
}
}
public static String md5Encryptbase64(String msg) throws Exception
{
return msg == null ? null : base64Encode(md5(msg));
}
public static String binary(byte[] bytes, int radix)
{
return new BigInteger(1, bytes).toString(radix);// 这里的1代表正数
}
public static String base64Encode(byte[] bytes)
{
return new base64Encoder().encode(bytes);
}
public static byte[] base64Decode(String base64Code)
{
try
{
return base64Code == null ? null : new base64Decoder().decodeBuffer(base64Code);
} catch (IOException e)
{
throw new RuntimeException("报错内容", e);
}
}
public static byte[] md5(byte[] bytes)
{
MessageDigest md;
try
{
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e)
{
throw new RuntimeException("报错内容", e);
}
md.update(bytes);
return md.digest();
}
public static byte[] md5(String msg)
{
return msg == null ? null : md5(msg.getBytes());
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



