★ Programming Ideas:
The MessageDigest class in the Java.security package provides a way to compute a message digest, generate the object first, execute its update () method to pass the raw data to the object, and then execute its digest () method to get the message digest. The specific steps are as follows:
(1) Generating MessageDigest objects
MessageDigest m=messagedigest.getinstance ("MD5");
Analysis: The same as the Keygenerator class in the 2.2.1 section. The MessageDigest class is also a factory class whose constructors are protected and do not allow
The object is created directly using the new Messagedigist (), and the MessageDigest object must be generated through its static method getinstance ().
The parameters passed in specify the algorithm used to compute the message digest, commonly known as "MD5", "SHA", and so on. If you are interested in the details of the MD5 algorithm, refer to
Http://www.gztarena.com/rfc1321.txt.
(2) passing in the string to be computed
M.update (X.getbytes ("UTF8"));
Analysis: X is the string that needs to be computed, the parameter that the update passes in is a byte type or an array of byte types, and for strings, you need to first use the
The GetBytes () method generates an array of strings.
(3) Calculation message digest
byte s[]=m.digest ();
Analysis: The digest (Guangzhou the Java) method of executing the MessageDigest object completes the calculation, and the result of the calculation is returned through an array of byte types.
(4) Processing calculation results
If necessary, you can use the following code to convert the computed result s to a string.
Copy Code code as follows:
String result= "";
for (int i=0; I
Result+=integer.tohexstring ((0x000000ff & S) | 0XFFFFFF00). SUBSTRING (6);
}
★ Code and Analysis:
The complete procedure is as follows:
Copy Code code as follows:
Import java.security.*;
public class digestpass{
public static void Main (String args[]) throws exception{
String X=args[0];
MessageDigest m=messagedigest.getinstance ("MD5");
M.update (X.getbytes ("UTF8"));
byte s[]=m.digest ();
String result= "";
for (int i=0; I
Result+=integer.tohexstring ((0x000000ff & S) | 0XFFFFFF00). SUBSTRING (6);
}
SYSTEM.OUT.PRINTLN (result);
}
}
★ Run the program
Enter Java DIGESTCALC ABC to run the program, where the command line parameter ABC is the raw data, and the screen outputs the computed message digest:
900150983cd24fb0d6963f7d28e17f72.