Use the digest stream to obtain the MD5 of an object

Source: Internet
Author: User

Abstract stream is a type of stream filtering. It can be used to read and write the digest information (MD5/Sha) of the stream ).

When packaging a stream using a digest stream, an additional messagedigest object needs to be passed,

 
Messagedigest MD = messagedigest. getinstance ("MD5"); Digestinputstream dis=NewDigestinputstream (in, MD );

The Digest stream rewrites the Read and Write methods of the stream. The method internally calls the Upate () of the messagedigest object to update the digest information.

Public IntRead ()ThrowsIoexception {IntCh =In. Read ();If(On & Ch! =-1) {Digest. Update ((Byte) CH );}ReturnCh ;}

CallGetdigest ()Bytes [] that can obtain the digest information. Generally, we need to obtain the MD5 value in string form, so we need to convert it.

 /**  * Convert the byte array into a hexadecimal string **  @ Param Bytes *  @ Return  Returns a hexadecimal string.  */      Public   Static String bytearraytohex ( Byte  [] Bytes ){  //  Character array, used to store hexadecimal characters          Char [] Hexreferchars = {'0', '1', '2', '3', '4', '5', '6', '7', '8' , '9', 'A', 'B', 'C', 'D', 'E', 'F' }; //  One byte occupies 8 digits and one hexadecimal character occupies 4 digits. The length of the hexadecimal character array is twice the length of the byte array.          Char [] Hexchars = New   Char [Bytes. length * 2 ];  Int Index = 0 ;  For ( Byte  B: bytes ){  //  4-byte height Hexchars [index ++] = hexreferchars [B >>> 4 & 0xf];  //  4-bit lower in bytes Hexchars [index ++] = hexreferchars [B & 0xf ];}  Return   New  String (hexchars );} 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.