Public classSigndatautil {/*** Default password string combination to convert bytes to 16 binary characters * Apache verifies the correctness of downloaded files is the default combination*/ protected Static CharHexdigits[] = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' d ', ' e ', ' F ' }; protected StaticMessageDigest messagedigest =NULL; /*** Generate MD5/SHA1 checksum for string *@paramType * Secure channel types (Sctype in ifpub) *@parambuffer * Stitching MD5/SHA1 strings *@return */ Publicstring Getsigndata (string type, StringBuffer buffer) {Try { if(Constant.MD5TYPE.equals (type)) {MessageDigest=messagedigest.getinstance (CONSTANT.MD5); } Else if(Constant.SHA1TYPE.equals (type)) {MessageDigest=messagedigest.getinstance (Constant.sha1type); } //MessageDigest object for obtaining the MD5 digest algorithm byte[] inputbytearray; Inputbytearray= Buffer.tostring (). GetBytes ("Utf-8"); Messagedigest.update (Inputbytearray); byte[] Resultbytearray =messagedigest.digest (); return This. Bytearraytohex (Resultbytearray); } Catch(nosuchalgorithmexception e) {System.err.println (signdatautil.class. GetName ()+ "Initialization failed, MessageDigest does not support Md5util. "); E.printstacktrace (); return NULL; } Catch(unsupportedencodingexception e) {//TODO auto-generated Catch blockE.printstacktrace (); return NULL; } } /*** Convert character array to signature String *@paramByteArray *@return */ PrivateString Bytearraytohex (byte[] byteArray) { //new A character array, which is used to compose the result string (explanation: A byte is a eight-bit binary, which is the 2-bit hexadecimal character (2 of 8 is equal to 16 of the 2-second party)) Char[] Resultchararray =New Char[Bytearray.length * 2]; //iterates through byte arrays, converts characters into character arrays by bitwise operations (high efficiency of bitwise operations) intindex = 0; for(byteB:bytearray) {Resultchararray[index+ +] = hexdigits[b >>> 4 & 0xf]; Resultchararray[index+ +] = hexdigits[b & 0xf]; } //character array group composition string returnSystem.out.println (NewString (Resultchararray)); return NewString (Resultchararray); } /*** Determine if the MD5/SHA1 check code of the string matches a known signature *@paramType * Secure channel types (Sctype in ifpub) *@paramSignData * Known MD5/SHA1 check code *@paramresult * The string to validate *@return */ Public Booleanchecksigndata (String type, string signdata, StringBuffer buffer) {string result= This. Getsigndata (type, buffer); returnsigndata.equals (Result); } }
Generating and verifying the MD5 of a string