The symmetric encryption algorithm is an earlier encryption algorithm with mature technology. In the symmetric encryption algorithm, the data sender processes the plaintext (original data) and encryption key (mi yue) together with a special encryption algorithm, turning them into complex encrypted ciphertext and sending them out. After the recipient receives the ciphertext, if he wants to decipher the original text, he needs to use the key used for encryption and the inverse algorithm of the same algorithm to decrypt the ciphertext in order to restore it to readable plaintext. In the symmetric encryption algorithm, only one key is used. Both the sender and the receiver use this key to encrypt and decrypt the data. This requires the decryptor to know the encryption key in advance.
Simple java encryption algorithms are:
BASE strictly speaking is an encoding format, not an encryption algorithm
MD (Message Digest algorithm, message digest algorithm)
SHA (Secure Hash Algorithm, secure hash algorithm)
HMAC (Hash Message Authentication Code, hash message authentication code)
Type 1. BASE
Base is one of the most common encoding methods for transmitting Bit byte codes on the Internet. You can view RFC~RFC, which has detailed specifications for MIME. Base encoding can be used to convey longer identification information in an HTTP environment. For example, in the Java Persistence system Hibernate, Base is used to encode a long unique identifier (usually a -bit UUID) into a string, which is used as parameters in HTTP forms and HTTP GET URLs. In other applications, it is often necessary to encode binary data into a form suitable for placement in a URL (including hidden form fields). At this time, Base encoding is unreadable, that is, the encoded data will not be directly visible to the naked eye. (Source: Baidu Encyclopedia)
java implementation code:
package com.cn. One-way encryption; import sun.misc.BASEDecoder; import sun.misc.BASEEncoder;/*BASE encryption and decryption are two-way, and the inverse solution can be found. BASEEncoder and BASEDecoder are unofficial JDK implementation classes. Although it can be found and used in the JDK, it cannot be found in the API. The classes starting with sun and com.sun in JRE are undocumented. They belong to the basis of java and javax class libraries. Most of their implementations are related to the underlying platform and are generally not recommended. Strictly speaking, BASE is an encoding format, while non-encryption algorithms mainly include the two classes BASEEncoder and BASEDecoder. We only need to know how to use the corresponding methods. In addition, the number of bytes generated after BASE encryption is a multiple of . If the number of bytes is insufficient, fill it with the = symbol. BASE According to the definition of RFC, Base is defined as: Base content transfer encoding is designed to describe any sequence of bits in a form that is not easily recognized directly by humans. (The Base Content-Transfer-Encoding is designed to represent arbitrary sequences of octets in a form that need not be humanly readable.) Commonly seen in emails and http encryption. When intercepting http information, you will find the username and password fields for login operations. Encrypted via BASE. */public class BASE { /** * BASE decryption* * @param key * @return * @throws Exception */ public static byte[] decryptBASE(String key) throws Exception { return (new BASEDecoder()).decodeBuffer(key ); } /** * BASE encryption* * @param key * @return * @throws Exception */ public static String encryptBASE(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========Decrypted data========"+str); } catch (Exception e) { e.printStackTrace( ); } }}
Second type. MD
MD is Message-Digest Algorithm (Message-Digest Algorithm), which is used to ensure complete and consistent information transmission. It is one of the hash algorithms widely used in computers (also translated as digest algorithm and hash algorithm). MD has been generally implemented in mainstream programming languages. Computing data (such as Chinese characters) into another fixed-length value is the basic principle of the hash algorithm. The predecessors of MD are MD, MD and MD. Widely used in encryption and decryption technology, often used for file verification. check? No matter how big the file is, a unique MD value can be generated after MD. For example, the current ISO calibration is MD calibration. How to use it? Of course, the MD value is generated after ISO is passed through MD. Generally, friends who have downloaded linux-ISO have seen the MD string next to the download link. It is used to verify whether the files are consistent.
java implementation:
package com.cn. One-way encryption; import java.math.BigInteger; import java.security.MessageDigest;/*MD (Message Digest algorithm, message digest algorithm) Usually we do not directly use the above MD encryption. Usually, the byte array generated by MD is handed over to BASE and then encrypted to obtain 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("After 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: For data of any length, the length of the calculated MD value is fixed.
, Easy to calculate: It is easy to calculate the MD value from the original data.
. Modification resistance: If any changes are made to the original data, even if only a single byte is modified, the resulting MD value will be very different.
, Weak anti-collision: Knowing the original data and its MD value, it is very difficult to find data with the same MD value (that is, forged data).
, Strong anti-collision: It is very difficult to find two different data so that they have the same MD value.
The function of MD is to allow large-capacity information to be "compressed" into a confidential format (that is, to convert a byte string of any length into a string of hexadecimal digits of a certain length) before signing the private key with digital signature software. In addition to MD, the more famous ones include sha-, RIPEMD and Haval.
The third type.SHA
The Secure Hash Algorithm is mainly applicable to the Digital Signature Algorithm DSA defined in the Digital Signature Standard DSS. For messages less than ^ bits in length, SHA produces a one-bit message digest. This algorithm has been developed and improved by encryption experts over the years and has been increasingly perfected and widely used. The idea of this algorithm is to receive a piece of plaintext and then convert it into a piece of (usually smaller) ciphertext in an irreversible way. It can also be simply understood as taking a string of input codes (called pre-mapping or information), and The process of converting them into a short-length, fixed-digit output sequence, that is, a hash value (also called a message digest or message 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 regarded as the digital signature of the plaintext.
java implementation:
package com.cn. One-way encryption; import java.math.BigInteger; import java.security.MessageDigest;/*SHA (Secure Hash Algorithm, secure hash algorithm), digital signature and other important tools in cryptography applications, are widely used It is widely used in information security fields such as e-commerce. Although both SHA and MD have been cracked through collision methods, SHA is still a recognized secure encryption algorithm and is 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("After SHA encryption:" + 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(); } }}
SHA-Comparison with MD
Since both are derived from MD, SHA- and MD are very similar to each other. Correspondingly, their strengths and other characteristics are similar, but there are several differences:
Security against brute force attacks: The most significant and important difference is that the SHA-digest is longer than the MD-digest. Using brute force techniques, the difficulty of generating any message whose digest is equal to a given message digest is an operation of the order of magnitude for MD and an operation of the order of magnitude for SHA-. This way, SHA- has greater strength against brute force attacks.
Security against cryptanalysis: Due to the design of MD, which is vulnerable to cryptanalysis attacks, SHA- appears less vulnerable to such attacks.
Speed: SHA- runs slower than MD on the same hardware.
The fourth type.HMAC
HMAC (Hash Message Authentication Code, hash message authentication code, authentication protocol based on key Hash algorithm. The principle of message authentication code to achieve authentication is to use a public function and key to generate a fixed-length value as an authentication identifier. Use this Identifies the integrity of the message. Use a key to generate a small data block of fixed size, namely MAC, and add it to the message, and then transmit it using the key shared with the sender for authentication.
java implementation code:
package com.cn.One-way encryption;/*HMACHMAC(Hash Message Authentication Code, hash message authentication code, authentication protocol based on key Hash algorithm. The principle of message authentication code is to use a public function and key to generate a fixed-length value as an authentication identifier, and use this identifier to authenticate the integrity of the message. Sex. Use a key to generate a small data block of fixed size, namely MAC, and add it to the message, and then transmit it. The receiver uses the key shared with the sender for authentication, etc. */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"; /** * Initialize HMAC key* * @return * @throws Exception */ public static String initMacKey() throws Exception { 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("After HMAC encryption:===" + 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 { /*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 data*/ result= HMAC.encryptHMAC(inputData, key); System .out.println("After HMAC encryption:===" + 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: Check whether the results of the two encryptions are the same*/ getResult(inputStr); getResult(inputStr); } catch (Exception e) { e.printStackTrace(); } }}
The above content is the several encryption algorithms (four types) commonly used in Java shared by the editor. I hope you like it.