Java实现SHA1加密代码实例
微信接入中需要用到SHA1的算法。Java版的SHA1加密如下:
/* *微信公众平台(JAVA)SDK * *Copyright(c)2016,AnsitechNetworkTechnologyCo.,LtdAllrightsreserved. *http://www.ansitech.com/weixin/sdk/ * *LicensedundertheApacheLicense,Version2.0(the"License"); *youmaynotusethisfileexceptincompliancewiththeLicense. *YoumayobtainacopyoftheLicenseat * *http://www.apache.org/licenses/LICENSE-2.0 * *Unlessrequiredbyapplicablelaworagreedtoinwriting,software *distributedundertheLicenseisdistributedonan"ASIS"BASIS, *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied. *SeetheLicenseforthespecificlanguagegoverningpermissionsand *limitationsundertheLicense. */ packagecom.levi.utils; importjava.security.MessageDigest; /** *Title:SHA1算法
* *@authorlevi */ publicfinalclassSHA1{ privatestaticfinalchar[]HEX_DIGITS={'0','1','2','3','4','5', '6','7','8','9','a','b','c','d','e','f'}; /** *Takestherawbytesfromthedigestandformatsthemcorrect. * *@parambytestherawbytesfromthedigest. *@returntheformattedbytes. */ privatestaticStringgetFormattedText(byte[]bytes){ intlen=bytes.length; StringBuilderbuf=newStringBuilder(len*2); //把密文转换成十六进制的字符串形式 for(intj=0;j>4)&0x0f]); buf.append(HEX_DIGITS[bytes[j]&0x0f]); } returnbuf.toString(); } publicstaticStringencode(Stringstr){ if(str==null){ returnnull; } try{ MessageDigestmessageDigest=MessageDigest.getInstance("SHA1"); messageDigest.update(str.getBytes()); returngetFormattedText(messageDigest.digest()); }catch(Exceptione){ thrownewRuntimeException(e); } } }
如果需要做微信接入,直接把上面的复制新建一个类即可使用,我自己做好的,测试微信接入成功。