java原生实现MD5加密

家电修理 2023-07-16 19:16www.caominkang.com电器维修

 java原生实现MD5  32位小写MD5加密,不借助任何三方依赖

import java.security.MessageDigest;
import java.security.SecureRandom;


public class Md5{
 
 public static String bytesToHex(byte[] bytes) {
  StringBuffer md5str = ne StringBuffer();
  //把数组每一字节换成16进制连成md5字符串
  int digital;
  for (int i = 0; i < bytes.length; i++) {
   digital = bytes[i];
   if (digital < 0) {
    digital += 256;
   }
   if (digital < 16) {
    md5str.append("0");
   }
   md5str.append(Integer.toHexString(digital));
  }
  return md5str.toString();
 }

 public static String GenerateSignature(String str){
  String signature = "";
  try{
   //创建一个提供信息摘要算法的对象,初始化为md5算法对象
   MessageDigest md = MessageDigest.getInstance("MD5");
   //计算后获得字节数组
   byte[] bytes = md.digest(str.getBytes("utf-8"));
   //把数组每一字节换成16进制连成md5字符串
   signature = bytesToHex(bytes);
  }catch (Exception e) {
   e.printStackTrace();
  }
  return signature;
 }


 public static void main(String[] args){
  //生成16进制随机字符串(16位)
  byte[] bytes = ne byte[8];
  //使用SecureRandom获取高强度安全随机数生成器
  SecureRandom sr = ne SecureRandom();
  sr.nextBytes(bytes);
  System.out.println(GenerateSignature("12345DFG"));
 }
}

Copyright © 2016-2025 www.caominkang.com 曹敏电脑维修网 版权所有 Power by