Implement MD5 encryption in Java

Source: Internet
Author: User
Package com. CS;

/*************************************** ****************************************
* The MD5 class implements the MD5 message-Digest in the rfc1321 submitted to the IETF by RSA Data Security, Inc.Algorithm.
**************************************** **************************************/
Import java. Lang. Reflect .*;

Public class MD5 {

/*
* The following S11-S44 is actually a 4*4 matrix, which is implemented with # define in the original C implementation. Here they are implemented as static
* Final indicates read-only and can be shared among multiple instances in the same process space.
*/
Static final int S11 = 7;

Static final int S12 = 12;

Static final int S13 = 17;

Static final int S14 = 22;

Static final int S21 = 5;

Static final int s22 = 9;

Static final int S23 = 14;

Static final int S24 = 20;

Static final int s31 = 4;

Static final int s32 = 11;

Static final int s33 = 16;

Static final int s34 = 23;

Static final int s41 = 6;

Static final int S42 = 10;

Static final int s43 = 15;

Static final int s44 = 21;

Static final byte [] padding = {-128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0 };

/*
* The following three members are the three core data used in the MD5 calculation process. They are defined in the md5_ctx structure in the original C implementation.
*
*/
Private long [] State = new long [4]; // state (ABCD)

Private long [] Count = new long [2]; // number of BITs, modulo 2 ^ 64 (LSB

// First)

Private byte [] buffer = new byte [64]; // input buffer

/*
* Digesthexstr is the only public member of MD5 and is the hexadecimal ASCII representation of the latest calculation result.
*/
Public String digesthexstr;

/*
* Digest is the binary representation of the latest calculation result, indicating the MD5 value of bits.
*/
Private byte [] digest = new byte [16];

/*
* Getmd5ofstr is the main public method of MD5-like. The entry parameter is the string you want to perform MD5 conversion.
* The returned result is the transformed result, which is obtained from the public member digesthexstr.
*/
Public String getmd5ofstr (string inbuf ){
Md5init ();
Md5update (inbuf. getbytes (), inbuf. Length ());
Md5final ();
Digesthexstr = "";
For (INT I = 0; I <16; I ++ ){
Digesthexstr + = bytehex (Digest [I]);
}
Return digesthexstr;

}

// This is the standard constructor of the MD5 class. JavaBean requires a public constructor without parameters.
Public MD5 (){
Md5init ();

Return;
}

/* Md5init is an initialization function that initializes core variables and loads Standard magic numbers */
Private void md5init (){
Count [0] = 0l;
Count [1] = 0l;
/// * Load magic initialization constants.

State [0] = 0x67452301l;
State [1] = 0xefcdab89l;
State [2] = 0x98badcfel;
State [3] = 0x10325476l;

Return;
}

/*
* F, G, H, and I are four basic MD5 functions. In the original MD5 C implementation, they are
* Simple bitwise operations may implement them into macros for efficiency reasons. In Java, we implement them into private methods and keep their names in the original C.
*/

Private long F (long X, long y, long Z ){
Return (X & Y) | ((~ X) & Z );

}

Private long g (long X, long y, long Z ){
Return (X & z) | (Y &(~ Z ));

}

Private long H (long X, long y, long Z ){
Return x ^ y ^ Z;
}

Private long I (long X, long y, long Z ){
Return y ^ (X | (~ Z ));
}

/*
* Ff, GG, HH, and II will call F, G, H, and I for the next step transformation ff, GG, HH, and II transformations
* Rounds 1, 2, 3, and 4. rotation is separate from addition to prevent
* Recomputation.
*/

Private long ff (long a, long B, long C, long d, long X, long s, long AC ){
A + = f (B, c, d) + x + AC;
A = (INT) A <s) | (INT) A >>> (32-S ));
A + = B;
Return;
}

Private long Gg (long a, long B, long C, long d, long X, long s, long AC ){
A + = g (B, c, d) + x + AC;
A = (INT) A <s) | (INT) A >>> (32-S ));
A + = B;
Return;
}

Private long HH (long a, long B, long C, long d, long X, long s, long AC ){
A + = H (B, c, d) + x + AC;
A = (INT) A <s) | (INT) A >>> (32-S ));
A + = B;
Return;
}

Private long II (long a, long B, long C, long d, long X, long s, long AC ){
A + = I (B, C, D) + x + AC;
A = (INT) A <s) | (INT) A >>> (32-S ));
A + = B;
Return;
}

/*
* Md5update is the main calculation process of MD5, inbuf is the byte string to be transformed, and inputlen is the length.
* The function is called by getmd5ofstr. before calling the function, you need to call md5init. Therefore, we design it as private
*/
Private void md5update (byte [] inbuf, int inputlen ){

Int I, index, partlen;
Byte [] block = new byte [64];
Index = (INT) (count [0] >>> 3) & 0x3f;
/// * UPDATE Number of BITs */
If (count [0] + = (inputlen <3) <(inputlen <3 ))
Count [1] ++;
Count [1] + = (inputlen >>> 29 );

Partlen = 64-index;

// Transform as same times as possible.
If (inputlen> = partlen ){
Md5memcpy (buffer, inbuf, index, 0, partlen );
Md5transform (buffer );

For (I = partlen; I + 63 <inputlen; I ++ = 64 ){

Md5memcpy (Block, inbuf, 0, I, 64 );
Md5transform (Block );
}
Index = 0;

} Else

I = 0;

/// * Buffer remaining input */
Md5memcpy (buffer, inbuf, index, I, inputlen-I );

}

/*
* Md5final sorting and entering output results
*/
Private void md5final (){
Byte [] bits = new byte [8];
Int index, padlen;

/// * Save Number of BITs */
Encode (bits, Count, 8 );

/// * Pad out to 56 mod 64.
Index = (INT) (count [0] >>> 3) & 0x3f;
Padlen = (index <56 )? (56-index): (120-index );
Md5update (padding, padlen );

/// * Append length (before padding )*/
Md5update (bits, 8 );

/// * Store state in Digest */
Encode (Digest, state, 16 );

}

/*
* Md5memcpy is a block copy function of the byte array used internally. It starts from inpos of the input and sets the LEN Length.
* Copying bytes to the outpos position of output starts.
*/

Private void md5memcpy (byte [] output, byte [] input, int outpos, int inpos,
Int Len ){
Int I;

For (I = 0; I <Len; I ++)
Output [outpos + I] = input [inpos + I];
}

/*
* Md5transform is the MD5 core transformation.ProgramWith md5update, the block is the original byte of the block.
*/
Private void md5transform (byte block []) {
Long A = State [0], B = State [1], c = State [2], D = State [3];
Long [] x = new long [16];

Decode (x, block, 64 );

/* Round 1 */
A = ff (a, B, c, d, X [0], S11, 0xd76aa478l);/* 1 */
D = ff (D, a, B, c, X [1], S12, 0xe8c7b756l);/* 2 */
C = ff (c, d, A, B, X [2], S13, 0x242070dbl);/* 3 */
B = ff (B, c, d, A, X [3], S14, 0xc1bdceeel);/* 4 */
A = ff (a, B, c, d, X [4], S11, 0xf57c0fafl);/* 5 */
D = ff (D, a, B, c, X [5], S12, 0x4787c62al);/* 6 */
C = ff (c, d, A, B, X [6], S13, 0xa8304613l);/* 7 */
B = ff (B, c, d, A, X [7], S14, 0xfd469501l);/* 8 */
A = ff (a, B, c, d, X [8], S11, 0x698098d8l);/* 9 */
D = ff (D, a, B, c, X [9], S12, 0x8b44f7afl);/* 10 */
C = ff (c, d, A, B, X [10], S13, 0xffff5bb1l);/* 11 */
B = ff (B, c, d, A, X [11], S14, 0x895cd7bel);/* 12 */
A = ff (a, B, c, d, X [12], S11, 0x6b901122l);/* 13 */
D = ff (D, a, B, c, X [13], S12, 0xfd987193l);/* 14 */
C = ff (c, d, A, B, X [14], S13, 0xa679438el);/* 15 */
B = ff (B, c, d, A, X [15], S14, 0x49b40821l);/* 16 */

/* Round 2 */
A = Gg (a, B, c, d, X [1], S21, 0xf61e2562l);/* 17 */
D = Gg (D, a, B, c, X [6], s22, 0xc040b340l);/* 18 */
C = Gg (c, d, A, B, X [11], S23, 0x265e5a51l);/* 19 */
B = Gg (B, c, d, A, X [0], S24, 0xe9b6c7aal);/* 20 */
A = Gg (a, B, c, d, X [5], S21, 0xd62f105dl);/* 21 */
D = Gg (D, a, B, c, X [10], s22, 0x2441453l);/* 22 */
C = Gg (c, d, A, B, X [15], S23, 0xd8a1e681l);/* 23 */
B = Gg (B, c, d, A, X [4], S24, 0xe7d3fbc8l);/* 24 */
A = Gg (a, B, c, d, X [9], S21, 0x21e1cde6l);/* 25 */
D = Gg (D, a, B, c, X [14], s22, 0xc33707d6l);/* 26 */
C = Gg (c, d, A, B, X [3], S23, 0xf4d50d87l);/* 27 */
B = Gg (B, c, d, A, X [8], S24, 0x455a14edl);/* 28 */
A = Gg (a, B, c, d, X [13], S21, 0xa9e3e905l);/* 29 */
D = Gg (D, a, B, c, X [2], s22, 0xfcefa3f8l);/* 30 */
C = Gg (c, d, A, B, X [7], S23, 0x676f02d9l);/* 31 */
B = Gg (B, c, d, A, X [12], S24, 0x8d2a4c8al);/* 32 */

/* Round 3 */
A = HH (a, B, c, d, X [5], s31, 0xfffa3942l);/* 33 */
D = HH (D, a, B, c, X [8], s32, 0x8771f681l);/* 34 */
C = HH (c, d, A, B, X [11], s33, 0x6d9d6122l);/* 35 */
B = HH (B, c, d, A, X [14], s34, 0xfde5380cl);/* 36 */
A = HH (a, B, c, d, X [1], s31, 0xa4beea44l);/* 37 */
D = HH (D, a, B, c, X [4], s32, 0x4bdecfa9l);/* 38 */
C = HH (c, d, A, B, X [7], s33, 0xf6bb4b60l);/* 39 */
B = HH (B, c, d, A, X [10], s34, 0xbebfbc70l);/* 40 */
A = HH (a, B, c, d, X [13], s31, 0x289b7ec6l);/* 41 */
D = HH (D, a, B, c, X [0], s32, 0xeaa1_fal);/* 42 */
C = HH (c, d, A, B, X [3], s33, 0xd4ef3085l);/* 43 */
B = HH (B, c, d, A, X [6], s34, 0x4881d05l);/* 44 */
A = HH (a, B, c, d, X [9], s31, 0xd9d4d039l);/* 45 */
D = HH (D, a, B, c, X [12], s32, 0xe6db99e5l);/* 46 */
C = HH (c, d, A, B, X [15], s33, 0x1fa27cf8l);/* 47 */
B = HH (B, c, d, A, X [2], s34, 0xc4ac5665l);/* 48 */

/* Round 4 */
A = II (a, B, c, d, X [0], s41, 0xf4292244l);/* 49 */
D = II (D, a, B, c, X [7], S42, 0x432aff97l);/* 50 */
C = II (c, d, A, B, X [14], s43, 0xab9423a7l);/* 51 */
B = II (B, c, d, A, X [5], s44, 0xfc93a039l);/* 52 */
A = II (a, B, c, d, X [12], s41, 0x655b59c3l);/* 53 */
D = II (D, a, B, c, X [3], S42, 0x8f0ccc92l);/* 54 */
C = II (c, d, A, B, X [10], s43, 0xffeff47dl);/* 55 */
B = II (B, c, d, A, X [1], s44, 0x85845dd1l);/* 56 */
A = II (a, B, c, d, X [8], s41, 0x6fa87e4fl);/* 57 */
D = II (D, a, B, c, X [15], S42, 0xfe2ce6e0l);/* 58 */
C = II (c, d, A, B, X [6], s43, 0xa3014314l);/* 59 */
B = II (B, c, d, A, X [13], s44, 0x4e0811a1l);/* 60 */
A = II (a, B, c, d, X [4], s41, 0xf7537e82l);/* 61 */
D = II (D, a, B, c, X [11], S42, 0xbd3af235l);/* 62 */
C = II (c, d, A, B, X [2], s43, 0x2ad7d2bbl);/* 63 */
B = II (B, c, d, A, X [9], s44, 0xeb86d391l);/* 64 */

State [0] + =;
State [1] + = B;
State [2] + = C;
State [3] + = D;

}

/*
* Encode splits the long array into byte arrays in sequence. Because Java's long type is 64bit, only 32 bit is removed to adapt to the use of the original C implementation.
*/
Private void encode (byte [] output, long [] input, int Len ){
Int I, J;

For (I = 0, j = 0; j <Len; I ++, J + = 4 ){
Output [J] = (byte) (input [I] & 0 xffl );
Output [J + 1] = (byte) (input [I] >>> 8) & 0 xffl );
Output [J + 2] = (byte) (input [I] >>> 16) & 0 xffl );
Output [J + 3] = (byte) (input [I] >>> 24) & 0 xffl );
}
}

/*
* Decode combines byte arrays into long arrays in order, because Java's long type is 64bit,
* Only low 32bit is merged and high 32bit is cleared to adapt to the use of the original C implementation.
*/
Private void decode (long [] output, byte [] input, int Len ){
Int I, J;

For (I = 0, j = 0; j <Len; I ++, J + = 4)
Output [I] = b2iu (input [J]) | (b2iu (input [J + 1]) <8)
| (B2iu (input [J + 2]) <16) | (b2iu (input [J + 3]) <24 );

Return;
}

/*
* B2iu is a "Escalation" program that writes byte without considering the plus or minus signs, Because Java does not have the unsigned operation.
*/
Public static long b2iu (byte B ){
Return B <0? B & amp; 0x7f + 128: B;
}

/*
* Bytehex () is used to convert the number of bytes to the hexadecimal ASCII representation,
* Because the tostring of byte in Java cannot be implemented, we do not have sprintf (outbuf, "% 02x", IB) in C)
*/
Public static string bytehex (byte Ib ){
Char [] digit = {'0', '1', '2', '3', '4', '5', '6', '7 ', '8', '9', 'A ',
'B', 'C', 'D', 'E', 'F '};
Char [] Ob = new char [2];
Ob [0] = digit [(ib >>> 4) & 0x0f];
Ob [1] = digit [IB & 0x0f];
String S = new string (OB );
Return S;
}

Public static void main (string ARGs []) {

MD5 M = new MD5 ();
If (array. getlength (ARGs) = 0) {// if no parameter exists, run the standard test suite

System. Out. println ("MD5 test suite :");
System. Out. println ("MD5 ("): "+ M. getmd5ofstr (""));
System. Out. println ("MD5 (" "A" "):" + M. getmd5ofstr (""));
System. Out. println ("MD5 (" ABC ""): "+ M. getmd5ofstr (" ABC "));
System. Out. println ("MD5 (" "helloworld" "):" + M. getmd5ofstr ("helloworld "));
System. Out. println ("MD5 (" "Message Digest ""):"
+ M. getmd5ofstr ("Message Digest "));
System. Out. println ("MD5 (" abcdefghijklmnopqrstuvwxyz ""):"
+ M. getmd5ofstr ("abcdefghijklmnopqrstuvwxyz "));
System. Out
. Println ("MD5 (" "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789 ""):"
+ M
. Getmd5ofstr ("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789 "));
} Else
System. Out
. Println ("MD5 (" + ARGs [0] + ") =" + M. getmd5ofstr (ARGs [0]);

}

}

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.