In depth understanding of the Java encryption branch

  • 2020-04-01 01:26:47
  • OfStack

u programming ideas :
The MessageDigest class in the java.security package provides a way to compute a MessageDigest by first generating an object, executing its update () method to pass the raw data to the object, and then executing its digest () method to get the MessageDigest. The specific steps are as follows:
(1) generate the MessageDigest object
The MessageDigest m = MessageDigest getInstance (" MD5 ");
Analysis: same as the KeyGenerator class in section 2.2.1. The MessageDigest class is also a factory class whose constructor is protected and not allowed
New MessageDigist () is used directly to create the object, 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 used are "MD5", "SHA", etc. If you are interested in the details of the MD5 algorithm, please refer to it
http://www.gztarena.com/rfc1321.txt.
(2) pass in the string to be calculated
M.update (x.getbytes ("UTF8"));
Analysis: x is the string to be calculated, the parameter passed by update is byte type or byte type array, for the string, need to use first
The getBytes () method generates an array of strings.
(3) calculate the message digest
Byte s[]= m.docigest ();
Analysis: perform the digest (guangzhou dune Java) method of the MessageDigest object to complete the calculation. The calculated result is returned through an array of byte types.
(4) processing the calculation results
If necessary, the following code can be used to convert the calculated result s to a string.
 
String result=""; 
for  ( int i=0; i 
result+=Integer.toHexString (( 0x000000ff & s )  | 0xffffff00 ). substring ( 6 );  
} 

u code and analysis :
The complete procedure is 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 );  
} 
} 

u running program
Input the Java DigestCalc ABC to run the program, where the command line parameter ABC is the original data, and the screen outputs the message summary after calculation:
900150983 cd24fb0d6963f7d28e17f72.

Related articles: