Java: MD5 encrypted string

Source: Internet
Author: User

Back up a small program. Use MD5 to encrypt the file and generate a ciphertext source program. Very easy to use.

Import java. Security. messagedigest;
Import java. Security. nosuchalgorithmexception;
Import java. Io .*;

Public class encryptutil
{
/**
*
* @ Param filepath the full path of the file
* @ Return
* @ Throws exception
*/
Public static string encrypt (string filepath) throws exception
{
String instr = getstring (filepath );
Messagedigest MD = NULL;
String out = NULL;

Try
{
MD = messagedigest. getinstance ("MD5 ");
Byte [] digest = md. Digest (instr. getbytes ());
Out = byte2hex (Digest );
}
Catch (nosuchalgorithmexception E)
{
E. printstacktrace ();
Throw E;
}

Return out;
}

Private Static string byte2hex (byte [] B)
{
String HS = "";
String stmp = "";
For (INT n = 0; n <B. length; n ++)
{
Stmp = (Java. Lang. Integer. tohexstring (B [N] & 0xff ));
If (stmp. Length () = 1)
{
HS = HS + "0" + stmp;
}
Else
{
HS = HS + stmp;
}
}
Return HS. touppercase ();
}

Private Static string getstring (string filepath) throws exception
{
Stringbuffer sbuf = new stringbuffer ();
Try
{
Filereader Fr = new filereader (filepath );
Bufferedreader BR = new bufferedreader (FR );

String line = Br. Readline ();

While (line! = NULL)
{
Sbuf. append (line );
Sbuf. append ("/R/N ");
Line = Br. Readline ();
}
BR. Close ();
Fr. Close ();
}
Catch (exception E)
{
E. printstacktrace ();
Throw E;
}
// System. Out. println (sbuf. tostring ());

Return sbuf. tostring (). Trim ();
}

Public static void main (string [] ARGs) throws exception
{
If (ARGs. length> 0)
{
String result = NULL;
Try
{
Result = encrypt (ARGs [0]);
}
Catch (exception E)
{
E. printstacktrace ();
}
System. Out. println (ARGs [0] + ":" + result );
// System. Out. println (ARGs [1] + ":" + encrypt (ARGs [1]);
}
Else
{
System. Out. println ("the file does not exist ");
}
}
 
}

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.