The basic method of implementing SHA1 and MD5 encryption algorithm in Java is _java

Source: Internet
Author: User
Tags hmac md5 encryption sha1 sha1 encryption

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......&* () ... &8021 
  
 34.. "); 
  
 Encodebysha ("China op......&* () ... &802134 ..."); 
 Shafile (); /** * Message digest using MAC algorithm * @param data * @throws Exception/public static void Encodebymac (String data) thro 
WS exception{//Keygenerator KeyGen = keygenerator.getinstance ("HmacSHA1"); Secretkey key = Keygen.generatekey (); 
 This is not the same as the key generated each time, the pbekeyspec keyspec = new Pbekeyspec ("randomkey^ (^&*^%$". ToCharArray ()) cannot be used here. SecretkeyfacTory keyfactory = Secretkeyfactory.getinstance ("Pbewithmd5anddes"); 
  
 Secretkey key = Keyfactory.generatesecret (KEYSPEC); 
  * * This class provides the functionality of the message authentication code (authentication Code,mac) algorithm. 
  * MAC provides a way to check the integrity of information transmitted or stored on unreliable media based on a secret key. 
  * Typically, message authentication codes are used between two participants who share secret keys to verify the information transmitted between the two. * The MAC mechanism based on cryptographic hash functions is also called HMAC. 
 Combining secret shared keys, * HMAC can be used for any cryptographic hash function (e.g. MD5 or SHA-1)/Mac Mac = Mac.getinstance ("HmacSHA1"); 
All of the following three are 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 Summary:" + arrays.tostring (dest)); /** * SHA1 encryption using message digest messagedigest processing * @throws Exception/public static string Encodebysha (String str) thro 
 WS exception{MessageDigest SHA1; 
 SHA1 = Messagedigest.getinstance ("SHA1"); 
The following three types are not available//SHA1 = Messagedigest.getinstance ("SHA256"); SHA1 = Messagedigest.getinsTance ("SHA384"); 
  
 SHA1 = Messagedigest.getinstance ("SHA512"); Sha1.update (Str.getbytes ()); Update the digest first byte[] digest = Sha1.digest (); The hash is then completed by performing a final operation such as padding. 
  
 After calling this method, the summary is reset. 
  * * To last update the summary using the specified byte array, and then complete the summary calculation. 
  * That is, this method first calls update (input), * passes the input array to the Update method, and then invokes Digest (). 
  
 *///byte[] Digest = Sha1.digest (Str.getbytes ()); 
 String hex = Tohex (digest); 
 System.out.println ("SHA1 Summary:" + hex); 
 return hex; /** * File Data Digest * @throws Exception */public static void Shafile () throws Exception {MessageDigest messaged 
 Igest = Messagedigest.getinstance ("SHA1"); 
 Digestoutputstream dos = new Digestoutputstream (New FileOutputStream ("Abc.txt"), messagedigest); 
 Dos.write ("Chinese People ......& ()) f* (214) admin*". GetBytes ()); 
 Dos.close (); 
 Byte[] Digest = Messagedigest.digest (); 
  
 System.out.println ("Write file using streaming, the summary of the file is:" + Tohex (Digest)); 
 Digestinputstream dis = new Digestinputstream (New FileInputStream ("Abc.txt"), messagedigest);byte[] buf = new byte[100]; 
 int Len; 
 while (len = Dis.read (buf))!=-1) {System.out.println ("read data is:" + new String (buf, 0, Len)); 
 } dis.close (); 
 byte[] Digest2 = Messagedigest.digest (); 
 When the stream is read, the file is read, and the summary is System.out.println the same as when it was written ("read the file using the stream, the summary of the file is:" + Tohex (digest2)); /** * SHA1 Summary turn 16 * @param Digest * @return * * private static String Tohex (byte[] digest) {Stringbuild 
 ER 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 = in Teger.tohexstring (0xFF & Digest[i])//original method if (out.length () = = 1) {sb.append ("0");//if 1-bit front complement 0} Sb.appe 
 nd (out); 
 return sb.tostring (); 

 } 
 
}


MD5

MD5 (message Digest algorithm 5), which is the fifth edition of the Messaging Digest algorithm. a message digest is an algorithm that, regardless of how long the original data is, the result of the message digest is fixed-length; it's an irreversible algorithm.
The change of any bit bit in the original data will result in a great difference in the results of the message digest, and the probability of calculating the original data according to the result is very low.
The message digest can be regarded as the fingerprint of the original data, and the original data is different from 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......&* () ... &8021 
  
 34.. "); 
  
 ENCODEBYMD5 ("China op......&* () ... &802134 ..."); 
 Md5file (); /** * Message digest using MAC algorithm * @param data * @throws Exception/public static void Encodebymac (String data) thro 
WS exception{//Keygenerator KeyGen = keygenerator.getinstance ("HmacMD5"); Secretkey key = Keygen.generatekey (); 
 This is not the same as the key generated each time, the pbekeyspec keyspec = new Pbekeyspec ("randomkey^ (^&*^%$". ToCharArray ()) cannot be used here. SecretkeyfactOry keyfactory = secretkeyfactory.getinstance ("Pbewithmd5anddes"); 
  
 Secretkey key = Keyfactory.generatesecret (KEYSPEC); 
  * * This class provides the functionality of the message authentication code (authentication Code,mac) algorithm. 
  * MAC provides a way to check the integrity of information transmitted or stored on unreliable media based on a secret key. 
  * Typically, message authentication codes are used between two participants who share secret keys to verify the information transmitted between the two. * The MAC mechanism based on cryptographic hash functions is also called HMAC. 
 Combining secret shared keys, * HMAC can be used for 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 Summary:" + arrays.tostring (dest)); /** * MD5 encryption using message digest messagedigest processing * @throws Exception/public static string EncodeByMd5 (String str) throw 
 s exception{messagedigest MD5; 
  
 MD5 = messagedigest.getinstance ("MD5"); Md5.update (Str.getbytes ()); Update the digest first byte[] digest = Md5.digest (); The hash is then completed by performing a final operation such as padding. 
  
 After calling this method, the summary is reset. 
  * * To last update the summary using the specified byte array, and then complete the summary calculation. 
  * That is, this method first calls update (input), * passes the input array to the Update method, and then invokes Digest (). */ 
//byte[] Digest = Md5.digest (Str.getbytes ()); 
 String hex = Tohex (digest); 
 System.out.println ("MD5 Summary:" + hex); 
 return hex; /** * File Data Digest * @throws Exception */public static void Md5file () throws Exception {MessageDigest messaged 
 Igest = Messagedigest.getinstance ("MD5"); 
 Digestoutputstream dos = new Digestoutputstream (New FileOutputStream ("Abc.txt"), messagedigest); 
 Dos.write ("Chinese People ......& ()) f* (214) admin*". GetBytes ()); 
 Dos.close (); 
 Byte[] Digest = Messagedigest.digest (); 
  
  
 System.out.println ("Write file using streaming, the summary of the file is:" + Tohex (Digest)); 
 Digestinputstream dis = new Digestinputstream (New FileInputStream ("Abc.txt"), messagedigest); 
 byte[] buf = new byte[100]; 
 int Len; 
 while (len = Dis.read (buf))!=-1) {System.out.println ("read data is:" + new String (buf, 0, Len)); 
 } dis.close (); 
 byte[] Digest2 = Messagedigest.digest (); 
 When the stream is read, the file is read, and the summary is System.out.println the same as when it was written ("read the file using the stream, the summary of the file is:" + Tohex (digest2)); 
 } 
 
 /*** MD5 Summary Turn 16 * @param digest * @return/private static String Tohex (byte[) digest) {StringBuilder sb = new S 
 Tringbuilder (); 
  
 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 = in Teger.tohexstring (0xFF & Digest[i])//original method if (out.length () = = 1) {sb.append ("0");//if 1-bit front complement 0} Sb.appe 
 nd (out); 
 return sb.tostring (); 
 } 
 
}

PS: Here again for you to provide 2 MD5 encryption tools, interested friends can refer to:

MD5 Online Encryption Tool:

Http://tools.jb51.net/password/CreateMD5Password

Online md5/hash/sha-1/sha-2/sha-256/sha-512/sha-3/ripemd-160 Encryption Tool:

Http://tools.jb51.net/password/hash_md5_sha

Related Article

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.