Sharing Java common several encryption algorithms (four) _java

Source: Internet
Author: User
Tags decrypt hmac readable rfc

Symmetric encryption algorithm is the application of an earlier encryption algorithm, technology mature. In the symmetric encryption algorithm, the data sender passes the plaintext (raw data) and the encryption key (Mi Yue) together after the special encryption algorithm is processed, makes it become the complex encrypted cipher text to send out. After receiving the ciphertext, if you want to interpret the original text, you need to use the encryption key and the same algorithm of the inverse algorithm to decrypt the ciphertext, in order to enable it to revert to readable plaintext. In the symmetric encryption algorithm, only one key is used, both the sender and the receiver use the key to encrypt and decrypt the data, which requires the decryption party to know the encryption key beforehand.

Simple Java encryption algorithms are:

BASE strictly speaking, it belongs to the encoding format, not the encryption algorithm.
MD (Message Digest algorithm, Information Digest algorithm)
SHA (Secure Hash algorithm, secure Hash Algorithm)
HMAC (hash messages authentication code, hash message authentication code)

The first kind. BASE

Base is one of the most common coding methods for transmitting bit byte code on the network, and you can view RFC~RFC with the MIME detail specification. Base encoding can be used to pass longer identity information in an HTTP environment. For example, in the Java Persistence System hibernate, base is used to encode a long unique identifier (typically a-bit uuid) as a string, as a parameter in an HTTP form and an HTTP GET URL. In other applications, it is often necessary to encode binary data into a form appropriate to the URL, including hidden form fields. At this point, the base encoding is not readable, that is, the encoded data will not be directly visible to the human eye. (Source Baidu Encyclopedia)

Java implementation code:

Package com.cn. One-way encryption;
Import Sun.misc.BASEDecoder;
Import Sun.misc.BASEEncoder;
/* Base encryption decryption is bidirectional, you can find the inverse solution. Baseencoder and Basedecoder are unofficial JDK implementation classes.
Although it can be found and used in the JDK, it is not available in the API.
The classes of sun and Com.sun in the JRE are not documented, they belong to the Java, Javax Class library, the implementation of which is mostly related to the underlying platform, is generally not recommended.
BASE strictly speaking, belong to the encoding format, but not the encryption algorithm is mainly Baseencoder, basedecoder two classes, we only need to know how to use the corresponding method.
In addition, the number of byte digits produced after base encryption is multiples, if the number of digits is not sufficient to fill the = symbol.
Base is defined as the RFC definition: Base content transfer encoding is designed to describe the byte of any sequence as a form that is not easily recognized directly by the person. (The Base content-transfer-encoding is designed to represent arbitrary sequences of octets into a form that does not need
nly readable.) commonly used in mail, HTTP encryption, interception of HTTP information, you will find the login operation of the user name, password fields are encrypted by base. * * public class BASE {/** * Base decryption * * @param key * @return * @throws Exception/Public St 
  Atic byte[] Decryptbase (String key) throws Exception {return (new Basedecoder ()). Decodebuffer (key); /** * Base Encryption * * @param key * @return * @throws Exception/public static String ENCRYPTB ASE (byte[] key) throws Exception{return (new Baseencoder ()). Encodebuffer (key);
    public static void Main (string[] args) {String str= "";
     try {String result= base.encryptbase (Str.getbytes ());
     SYSTEM.OUT.PRINTLN ("result===== Encrypted Data ==========" +result);
     byte result[]= base.decryptbase (Result);
     String Str=new string (result);
  System.out.println ("str======== decryption Data ========" +STR);
  catch (Exception e) {e.printstacktrace (); }
  }
}

The second kind. Md

MD, the Message-digest algorithm (Information-digest algorithm), is used to ensure that information is transmitted in a complete and consistent order. is one of the most widely used hashing algorithms (also translated digest algorithm, hashing algorithm), the mainstream programming language has been generally implemented by MD. The basic principle of the hashing algorithm is to calculate the data (such as Chinese characters) as another fixed length value, MD, MD and MD are the precursor of the division. Widely used in encryption and decryption technology, often used for file verification. Check? No matter how large the file is, a unique MD value can be generated after Md. Like the ISO checksum now, it's all MD checksum. How do you use it? Of course, the ISO is the result of MD after MD. General Download Linux-iso friends have seen the download link next to the MD string. is used to verify that the file is consistent.

Java implementation:

 package com.cn. one-way encryption; Import Java.math.BigInteger; import java.security.MessageDigest; /* MD (Message Digest algorithm, Information digest algorithm) usually we do not use the above MD encryption directly. 
  The byte array produced by MD is usually given to base and then encrypted to get the corresponding string Digest: assembly/public class MD {public static final String KEY_MD = "MD";
    public static string GetResult (String inputstr) {System.out.println ("======= Data before Encryption:" +INPUTSTR);
    BigInteger Biginteger=null; 
     try {messagedigest MD = messagedigest.getinstance (KEY_MD);
     byte[] Inputdata = Inputstr.getbytes (); 
     Md.update (Inputdata); 
    BigInteger = new BigInteger (Md.digest ());
    catch (Exception e) {e.printstacktrace ();} 
    SYSTEM.OUT.PRINTLN ("MD Encryption:" + biginteger.tostring ());
  return biginteger.tostring (); 
       public static void Main (string args[]) {try {string inputstr = ' simple encryption ';
    GetResult (INPUTSTR);
    catch (Exception e) {e.printstacktrace (); }
  }
}

The MD algorithm has the following characteristics:

, compressibility: Any length of data, calculated MD value length are fixed.
, easy to calculate: The MD value is easy to calculate from the original data.
, resistance to modification: Any changes to the original data, even if only to modify the byte, the resulting MD value is very different.
, weak anti-collision: Given the original data and its MD value, it is very difficult to find a data with the same MD value (that is, to falsify data).
, strong anti-collision: It is very difficult to find two different data so that they have the same MD value.

The role of MD is to allow bulk information to be "compressed" into a confidential format (that is, converting an arbitrary length of a byte string into a certain length of hexadecimal digits) before signing the private key with the digital signature software. In addition to MD, the more famous among them are Sha, Ripemd and Haval.

The Third Kind. SHA

Secure Hash algorithm is mainly applicable to digital signature algorithms (Digital Signature algorithm DSA) defined in the digital signature standard (Digital Signature Standard DSS). For messages that are less than the ^ bit length, Sha produces a bit message digest. The algorithm has been developed and improved by encryption experts for many years, and has been widely used. The idea of the algorithm is to receive a clear text and then convert it into a paragraph (usually smaller) cipher in an irreversible way, or simply to take a string of input codes (called Pre-maps or information) and convert them to a shorter, The process of a fixed number of digits in the output sequence that is the hash value (also known as Information Digest or information authentication code). The hash function value can be said to be a "fingerprint" or "digest" of the plaintext, so the digital signature of the hash value can be considered a digital signature on the plaintext.

Java implementation:

 package com.cn. one-way encryption; Import Java.math.BigInteger; import java.security.MessageDigest; /* SHA (Secure Hash algorithm, secure hashing algorithm), digital signature and other cryptography applications are important tools, widely used in E-commerce and other information security areas. 
  Although both SHA and MD have been cracked through collision methods, the SHA is still recognized as a secure encryption algorithm, more secure than MD/public class SHA {public static final String Key_sha = "Sha";
    public static string GetResult (String inputstr) {BigInteger sha =null;
    System.out.println ("======= Data before Encryption:" +INPUTSTR); 
    byte[] Inputdata = Inputstr.getbytes (); 
       try {messagedigest messagedigest = messagedigest.getinstance (Key_sha);
       Messagedigest.update (Inputdata); 
       sha = new BigInteger (Messagedigest.digest ()); 
    System.out.println ("Sha Encrypted:" + sha.tostring ());
    catch (Exception e) {e.printstacktrace ();}
  return sha.tostring (); 
       public static void Main (string args[]) {try {string inputstr = ' simple encryption ';
    GetResult (INPUTSTR);
    catch (Exception e) {e.printstacktrace (); }
  }
}

Comparison of SHA and MD

Because both are derived from MD, the SHA and MD are very similar to each other. Correspondingly, their strength and other characteristics are similar, but there are several differences:

Security for brute force attacks: the most significant and important difference is that the SHA-Digest is longer than the MD summary. Using brute force technology, producing any message so that its summary equals a given report Digest's difficulty to MD is ^ order of magnitude operations, while to Sha is ^ order of magnitude. In this way, the SHA has greater strength in the forced attack.

Security for cryptanalysis: Because of the MD design, which is susceptible to cryptanalysis, Sha appears to be vulnerable to such attacks.

Speed: On the same hardware, the SHA runs slower than Md.

The fourth kind. Hmac

HMAC (hash messages authentication code, hash message discriminator, authentication protocol based on the hash algorithm of the key). The principle of the authentication code is to use the public function and the key to produce a fixed length value as the authentication identification, and use this identity to identify the integrity of the message. Use a key to generate a fixed-size small block of data, the Mac, and add it to the message, and then transfer. The receiver uses the key that is shared with the sender to authenticate the identity.

Java implementation code:

Package com.cn. One-way encryption;
/* HMAC HMAC (hash messages authentication code, hash message authentication code, authentication protocol based on the hash algorithm of the key).
The principle of the authentication code is to use the public function and the key to produce a fixed length value as the authentication identification, and use this identity to identify the integrity of the message. Use a key to generate a fixed-size small block of data, the Mac, and add it to the message, and then transfer. The receiver uses the key that is shared with the sender to authenticate the identity.
* * Import Javax.crypto.KeyGenerator;
Import Javax.crypto.Mac;
Import Javax.crypto.SecretKey;
Import Javax.crypto.spec.SecretKeySpec;
Import Com.cn.comm.Tools; 
  /** * Basic Encryption Component */public abstract class HMAC {public static final String Key_mac = "Hmacmd"; /** * Initializes the HMAC key * * @return * @throws Exception/public static String Initmackey () throws Excepti 
    on {keygenerator keygenerator = keygenerator.getinstance (KEY_MAC); 
    Secretkey Secretkey = Keygenerator.generatekey (); 
  Return Base.encryptbase (secretkey.getencoded ());  /** * HMAC Encryption: Main method * * @param data * @param key * @return * @throws Exception/Public Static String Encrypthmac (byte[] data, String key) throws Exception {Secretkey Secretkey =New Secretkeyspec (Base.decryptbase (key), KEY_MAC); 
    Mac Mac = Mac.getinstance (Secretkey.getalgorithm ()); 
    Mac.init (Secretkey); 
  return new String (mac.dofinal (data));
    public static string GetResult (String inputstr) {string Path=tools.getclasspath ();
    String filesource=path+ "/file/hmac_key.txt";
    System.out.println ("======= Data before Encryption:" +INPUTSTR);
    String Result=null;
      try {byte[] Inputdata = Inputstr.getbytes (); String key = Hmac.initmackey (); 
      /* Generate key/SYSTEM.OUT.PRINTLN ("mac key: = = = =" + key);
      /* Write key to File/Tools.writemyfile (Filesource,key);
      result= Hmac.encrypthmac (Inputdata, key);
    SYSTEM.OUT.PRINTLN ("HMAC encrypted: = = =" + result); 
    catch (Exception e) {e.printstacktrace ();}
  return result.tostring ();
     public static string GetResult (String inputstr) {System.out.println ("======= Data before Encryption:" +INPUTSTR);
     String Path=tools.getclasspath ();
     String filesource=path+ "/file/hmac_key.txt"; String key=null;;
       try {* * to read the key from the file/Key=tools.readmyfile (Filesource); 
    System.out.println ("getresult key: = = =" + key);
    catch (Exception e) {e.printstacktrace ();}
    String Result=null; 
      try {byte[] Inputdata = Inputstr.getbytes ();
      /* Encrypt the data * * * result= Hmac.encrypthmac (inputdata, key);
    SYSTEM.OUT.PRINTLN ("HMAC encrypted: = = =" + result); 
    catch (Exception e) {e.printstacktrace ();}
  return result.tostring ();
       public static void Main (string args[]) {try {string inputstr = ' simple encryption ';
       /* Use the same key: Encrypt the data: see if the result of two times encryption is the same * * GetResult (INPUTSTR);
    GetResult (INPUTSTR);
    catch (Exception e) {e.printstacktrace (); }
  }
}

The above content is small to share the Java commonly used several encryption algorithms (four), I hope you like.

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.