Explain the basic methods of implementing SHA1 and MD5 encryption algorithms in Java

  • 2020-05-09 18:30:30
  • OfStack

SHA1


package com.stone.security; 
 
import java.io.ByteArrayInputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.security.DigestInputStream; 
import java.security.DigestOutputStream; 
import java.security.MessageDigest; 
import java.util.Arrays; 
 
import javax.crypto.Mac; 
import javax.crypto.SecretKey; 
import javax.crypto.SecretKeyFactory; 
import javax.crypto.spec.PBEKeySpec; 

public class SHA { 
 
 
 public static void main(String[] args) throws Exception { 
 encodeByMAC(" China oP ... &* (a)... &802134 ... "); 
  
 encodeBySHA(" China oP ... &* (a)... &802134 ... "); 
  
 shaFile(); 
 } 
 
 /** 
 *  use MAC  The algorithm   The message digest  
 * @param data 
 * @throws Exception 
 */ 
 public static void encodeByMAC(String data) throws Exception{ 
// KeyGenerator keyGen = KeyGenerator.getInstance("HmacSHA1"); 
// SecretKey key = keyGen.generateKey(); // This is generated every time key Don't 1 sample ,  Not available here  
  
 PBEKeySpec keySpec = new PBEKeySpec("randomkey^(^&*^%$".toCharArray()); 
 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); 
 SecretKey key = keyFactory.generateSecret(keySpec); 
  
 /* 
  *  This class provides a "message verification code" ( Message Authentication Code . MAC ) function of algorithm.  
  * MAC  Provide based on secret key 1 A way to check the integrity of information transmitted or stored on unreliable media.  
  *  Typically, the message captcha is used between two participants sharing the secret key to verify the information being transmitted between the two.  
  *  Based on the encrypted hash function  MAC  The mechanism is also called  HMAC . In combination with secret sharing keys,  
  * HMAC  Can be used with any cryptographic hash function (e.g  MD5  or  SHA-1 )  
  */ 
 Mac mac = Mac.getInstance("HmacSHA1"); 
 // The following 3 Are all available  
// Mac mac = Mac.getInstance("HmacSHA256"); 
// Mac mac = Mac.getInstance("HmacSHA384"); 
// Mac mac = Mac.getInstance("HmacSHA512"); 
 mac.init(key); 
 byte[] dest = mac.doFinal(data.getBytes()); 
 System.out.println(dest.length); 
 System.out.println("MAC Abstract: " + Arrays.toString(dest)); 
 } 
 
 /** 
 * SHA1 encryption   Using message digests MessageDigest  To deal with  
 * @throws Exception 
 */ 
 public static String encodeBySHA(String str) throws Exception{ 
 MessageDigest sha1; 
 sha1 = MessageDigest.getInstance("SHA1"); 
 // The following 3 A is not available  
// sha1 = MessageDigest.getInstance("SHA256"); 
// sha1 = MessageDigest.getInstance("SHA384"); 
// sha1 = MessageDigest.getInstance("SHA512"); 
  
 sha1.update(str.getBytes()); // Update the summary first  
 byte[] digest = sha1.digest(); // The hash is then computed by performing final operations such as padding. After this method is called, the digest is reset.  
  
 /* 
  *  Using the specified  byte  The array makes a final update to the summary and then completes the summary calculation.  
  *  That is, this method is called first  update(input) .  
  *  to  update  Method is passed  input  Array, and then call  digest() .  
  */ 
// byte[] digest = sha1.digest(str.getBytes()); 
  
 String hex = toHex(digest); 
 System.out.println("SHA1 Abstract :" + hex); 
 return hex; 
 } 
 
 /** 
 *  File data summary  
 * @throws Exception 
 */ 
 public static void shaFile() throws Exception { 
 MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); 
 DigestOutputStream dos = new DigestOutputStream(new FileOutputStream(new File("abc.txt")), messageDigest); 
 dos.write(" Chinese people... & ()) f* ( 214 ) admin*".getBytes()); 
 dos.close(); 
 byte[] digest = messageDigest.digest(); 
 System.out.println(" Write the file with the stream, and the summary of the file is :" + toHex(digest)); 
  
 DigestInputStream dis = new DigestInputStream(new FileInputStream(new File("abc.txt")), messageDigest); 
 byte[] buf = new byte[100]; 
 int len; 
 while ((len = dis.read(buf)) != -1) { 
  System.out.println(" The data read is: " + new String(buf, 0, len)); 
 } 
 dis.close(); 
 byte[] digest2 = messageDigest.digest(); 
 // When the stream is read and the file is finished,   The summary at this point   Only with   When writing the  1 sample  
 System.out.println(" Use the stream to read the file whose summary is :" + toHex(digest2)); 
 } 
 
 /** 
 * sha1  The turn 16 Into the system  
 * @param digest 
 * @return 
 */ 
 private static String toHex(byte[] digest) { 
 StringBuilder sb = new StringBuilder(); 
 int len = digest.length; 
  
 String out = null; 
 for (int i = 0; i < len; i++) { 
//  out = Integer.toHexString(0xFF & digest[i] + 0xABCDEF); // Add any  salt 
  out = Integer.toHexString(0xFF & digest[i]);// The original method  
  if (out.length() == 1) { 
  sb.append("0");// If it is 1 position   Fill in front of a 0 
  } 
  sb.append(out); 
 } 
 return sb.toString(); 
 } 
 
} 


MD5

MD5 (Message Digest Algorithm 5), version 5 of the message digest algorithm. Message digest is an algorithm: no matter how long the original data is, the result of message digest is of fixed length. It's an irreversible algorithm
Any change in the bit bit of the original data will result in a very different result of the message summary, and the probability of deducing the original data based on the result is extremely low.
The message digest can be viewed as a fingerprint of the original data, and the original data is different depending on the fingerprint.


package com.stone.security; 
 
import java.io.ByteArrayInputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.security.DigestInputStream; 
import java.security.DigestOutputStream; 
import java.security.MessageDigest; 
import java.util.Arrays; 
 
import javax.crypto.Mac; 
import javax.crypto.SecretKey; 
import javax.crypto.SecretKeyFactory; 
import javax.crypto.spec.PBEKeySpec; 

public class MD5 { 
 
 
 public static void main(String[] args) throws Exception { 
 encodeByMAC(" China oP ... &* (a)... &802134 ... "); 
  
 encodeByMd5(" China oP ... &* (a)... &802134 ... "); 
  
 md5File(); 
 } 
 
 /** 
 *  use MAC  The algorithm   The message digest  
 * @param data 
 * @throws Exception 
 */ 
 public static void encodeByMAC(String data) throws Exception{ 
// KeyGenerator keyGen = KeyGenerator.getInstance("HmacMD5"); 
// SecretKey key = keyGen.generateKey(); // This is generated every time key Don't 1 sample ,  Not available here  
  
 PBEKeySpec keySpec = new PBEKeySpec("randomkey^(^&*^%$".toCharArray()); 
 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); 
 SecretKey key = keyFactory.generateSecret(keySpec); 
  
 /* 
  *  This class provides a "message verification code" ( Message Authentication Code . MAC ) function of algorithm.  
  * MAC  Provide based on secret key 1 A way to check the integrity of information transmitted or stored on unreliable media.  
  *  Typically, the message captcha is used between two participants sharing the secret key to verify the information being transmitted between the two.  
  *  Based on the encrypted hash function  MAC  The mechanism is also called  HMAC . In combination with secret sharing keys,  
  * HMAC  Can be used with any cryptographic hash function (e.g  MD5  or  SHA-1 )  
  */ 
 Mac mac = Mac.getInstance("HmacMD5"); 
 mac.init(key); 
 byte[] dest = mac.doFinal(data.getBytes()); 
 System.out.println(dest.length); 
 System.out.println("MAC Abstract: " + Arrays.toString(dest)); 
 } 
 
 /** 
 * md5 encryption   Using message digests MessageDigest  To deal with  
 * @throws Exception 
 */ 
 public static String encodeByMd5(String str) throws Exception{ 
 MessageDigest md5; 
 md5 = MessageDigest.getInstance("MD5"); 
  
 md5.update(str.getBytes()); // Update the summary first  
 byte[] digest = md5.digest(); // The hash is then computed by performing final operations such as padding. After this method is called, the digest is reset.  
  
 /* 
  *  Using the specified  byte  The array makes a final update to the summary and then completes the summary calculation.  
  *  That is, this method is called first  update(input) .  
  *  to  update  Method is passed  input  Array, and then call  digest() .  
  */ 
// byte[] digest = md5.digest(str.getBytes()); 
  
 String hex = toHex(digest); 
 System.out.println("MD5 Abstract :" + hex); 
 return hex; 
 } 
 
 /** 
 *  File data summary  
 * @throws Exception 
 */ 
 public static void md5File() throws Exception { 
 MessageDigest messageDigest = MessageDigest.getInstance("MD5"); 
 DigestOutputStream dos = new DigestOutputStream(new FileOutputStream(new File("abc.txt")), messageDigest); 
 dos.write(" Chinese people... & ()) f* ( 214 ) admin*".getBytes()); 
 dos.close(); 
 byte[] digest = messageDigest.digest(); 
 System.out.println(" Write the file with the stream, and the summary of the file is :" + toHex(digest)); 
  
  
 DigestInputStream dis = new DigestInputStream(new FileInputStream(new File("abc.txt")), messageDigest); 
 byte[] buf = new byte[100]; 
 int len; 
 while ((len = dis.read(buf)) != -1) { 
  System.out.println(" The data read is: " + new String(buf, 0, len)); 
 } 
 dis.close(); 
 byte[] digest2 = messageDigest.digest(); 
 // When the stream is read and the file is finished,   The summary at this point   Only with   When writing the  1 sample  
 System.out.println(" Use the stream to read the file whose summary is :" + toHex(digest2)); 
 } 
 
 /** 
 * md5  The turn 16 Into the system  
 * @param digest 
 * @return 
 */ 
 private static String toHex(byte[] digest) { 
 StringBuilder sb = new StringBuilder(); 
 int len = digest.length; 
  
 String out = null; 
 for (int i = 0; i < len; i++) { 
//  out = Integer.toHexString(0xFF & digest[i] + 0xABCDEF); // Add any  salt 
  out = Integer.toHexString(0xFF & digest[i]);// The original method  
  if (out.length() == 1) { 
  sb.append("0");// If it is 1 position   Fill in front of a 0 
  } 
  sb.append(out); 
 } 
 return sb.toString(); 
 } 
 
} 

PS: here are 2 encryption tools for MD5, interested friends can refer to the following:

MD5 online encryption tool:

http://tools.ofstack.com/password/CreateMD5Password

MD5/hash/ SHA-1 / SHA-2 / SHA-256 / SHA-512 / SHA-3 / RIPEMD-160 encryption tools:

http://tools.ofstack.com/password/hash_md5_sha


Related articles: