您好,欢迎访问三七文档
当前位置:首页 > 电子/通信 > 数据通信与网络 > 对主机的mac地址MD5加密
Java实现主机mac地址加密,使用MD5加密算法。一、代码1.LOCALMAC类packagecom.tydic.encr;importjava.net.InetAddress;importjava.net.NetworkInterface;importjava.net.SocketException;importjava.net.UnknownHostException;publicclassLOCALMAC{privateStringlocalMac;privatestaticLOCALMAClm;privateLOCALMAC(){try{InetAddressia=InetAddress.getLocalHost();this.localMac=Ip2LocalMac(ia);}catch(SocketExceptione){e.printStackTrace();}catch(UnknownHostExceptione){e.printStackTrace();}}publicstaticLOCALMACgetInstance(){if(lm==null){lm=newLOCALMAC();}returnlm;}privatestaticStringIp2LocalMac(InetAddressia)throwsSocketException{//获取网卡,获取地址byte[]mac=NetworkInterface.getByInetAddress(ia).getHardwareAddress();StringBuffersb=newStringBuffer();for(inti=0;imac.length;i++){if(i!=0){sb.append(-);}//字节转换为整数inttemp=mac[i]&0xff;Stringstr=Integer.toHexString(temp);if(str.length()==1){sb.append(0+str);}else{sb.append(str);}}returnsb.toString().toUpperCase();}publicStringgetLocalMac(){returnlocalMac;}}2.Password类packagecom.tydic.encr;importjava.security.MessageDigest;publicclassPassword{privatefinalstaticString[]hexDigits={0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f};//十六进制下数字到字符的映射数组/**把inputString加密*/publicstaticStringcreatePassword(StringinputString){returnencodeByMD5(inputString);}/**对字符串进行MD5编码*/privatestaticStringencodeByMD5(StringoriginString){if(originString!=null){try{//创建具有指定算法名称的信息摘要MessageDigestmd=MessageDigest.getInstance(MD5);//使用指定的字节数组对摘要进行最后更新,然后完成摘要计算byte[]results=md.digest(originString.getBytes());//将得到的字节数组变成字符串返回StringresultString=byteArrayToHexString(results);returnresultString.toUpperCase();}catch(Exceptionex){ex.printStackTrace();}}returnnull;}/***字节数组转为十六进制字符串**@paramb*字节数组*@return十六进制字符串*/privatestaticStringbyteArrayToHexString(byte[]b){StringBufferresultSb=newStringBuffer();for(inti=0;ib.length;i++){resultSb.append(byteToHexString(b[i]));}returnresultSb.toString();}/***将一个字节转化成十六进制形式的字符串*/privatestaticStringbyteToHexString(byteb){intn=b;if(n0)n=256+n;intd1=n/16;intd2=n%16;returnhexDigits[d1]+hexDigits[d2];}publicstaticvoidmain(String[]args){Stringlocalmac=LOCALMAC.getInstance().getLocalMac();Stringpassword=Password.createPassword(localmac);System.out.println(本机mac地址:+localmac);System.out.println(对本机mac地址用MD5摘要后的字符串:+password);}}二、结果
本文标题:对主机的mac地址MD5加密
链接地址:https://www.777doc.com/doc-2465625 .html