Order
The previous articles are all about one-way encryption algorithms. It involves the BASE64, MD5, SHA, HMAC and several other common encryption and decryption algorithms.
This article, as well as several later. It is intended to introduce several symmetric cryptographic algorithms. For example: DES, 3DES (TripleDES), AES, and so on. Well, this article is mainly about DES about a bit.
Background
Before the discussion DES. First, let's look at what a symmetric encryption algorithm is. For the symmetric encryption algorithm, he used the time earlier. Technology is relatively mature in symmetric cryptographic algorithms. The sender of the data sends the plaintext (raw data) and the encryption key together by a special encryption algorithm to make it into a complex cipher cipher. If the receiving party receives the ciphertext, it wants to interpret the original text. It is necessary to decrypt the ciphertext using the encryption-used key and the inverse algorithm of the same algorithm, so that it can be recovered into readable plaintext.
In a symmetric encryption algorithm, the key used is only one. Both parties use this key to encrypt and decrypt the data. This requires the decryption party to know the encryption key beforehand.
The characteristic of symmetric encryption algorithm is that the algorithm is open and the computational amount is small. The disadvantage is that both sides of the transaction use the same key, the security is not guaranteed.
Concept
So, what is DES? How did he get here? I believe that very many people are very interested. As a result of the development of the time, the requirements of the progress is relatively strict, very often there is no time to understand these things at all.
So today we specialize in studying this thing.
DES, known as the "Data Encryption Standard", is called the "encryption standards" in Chinese. is a block algorithm that uses key encryption. DES algorithm is a symmetric password system in the password system. Also known as the U.S. Data Encryption standard. It is a symmetric password system encryption algorithm developed by IBM in the 1972.
The plaintext is grouped by 64 bits, the key is 64 bits long, the key is actually 56 bit to the DES operation (8th, 16, 24, 32, 40, 48, 56, 64 bits is the check bit, so that each key has an odd number of 1) After grouping the plaintext group and the 56-bit key in a bitwise substitution or Exchange method to form the encryption of the ciphertext group Method.
Basic principle
There are three entry parameters: key, data, mode. Key is the secret key used for encryption and decryption, and data is encryptedthe decrypted data. mode for its operating modes. When the mode is in cryptographic mode, the plaintext is grouped according to 64 bits. Form a clear text group. Key is used to encrypt data when the mode is in decryption mode. Key is used to decrypt the data.
In practice, the key only uses 64 bits of 56 bits, so that it has high security.
Main Process
The DES algorithm turns the 64-bit plaintext input block into a 64-bit ciphertext output block. The key it uses is also 64 bits. The algorithm is divided into two main steps:
Its function is to put the input 64 bits of data block again combined, and the output is divided into L0, R0 two parts. Each part is 32 bits long, and its permutation rule is to change the 58th position of the input to the first position, the 50th place to the 2nd digit ... And so on, the last one is the original 7th place. L0 and R0 are two parts after the transposition output. L0 is the left 32 bits of the output, R0 is the right 32 bit, example: set the input value before the change to D1 D2 D3 ... D64, the result after the initial substitution is: L0 = D58 D50 ... D8;r0 = D57 D49 ... D7.
After 16 iterations of the operation. Get L16, R16. With this as input, the inverse permutation is exactly the inverse of the initial permutation. Thus, the ciphertext output is obtained.
The main flowchart for the entire algorithm is as follows:
Grouping Mode
ECB. Chinese name "Electronic password this mode". is the oldest and simplest model that divides encrypted data into groups, each with the same size as the encryption key length.
Each group is then encrypted with the same key, such as the DES algorithm. Assuming that the last packet length is not 64 bits, 64 bits should be padded.
What you see:
Cbc. In the Chinese name "Cipher block chain mode", the biggest difference from ECB mode is the addition of the initial vector. He is characterized by a 64-bit (8-byte) cipher per cipher, and the CBC mode always produces the same ciphertext when using the same key and initial vector in the same plaintext.
CFB, Chinese name "Encrypted feedback mode". The cryptographic feedback mode overcomes the disadvantage of having to wait for 8 bytes of talent encryption. It uses the packet password as the stream password's key stream generator.
He is characterized by. Each encrypted Pi and Ci is not greater than 64 bits, and the encryption algorithm and decryption algorithm are the same. cannot be applied to public key algorithms. Use the same key and the initial vector. Similarly plaintext uses the CFB mode encryption to output the same ciphertext. The ability to use different initialization variables to make the same plaintext produce different ciphertext. Prevent dictionary attacks. The encryption strength depends on the key length, the length of the encryption block is too small, the number of loops is added, the cost is added, and the length of the encryption block is 8-bit integer times (that is, bytes); Once a data error occurs, the data for the current and subsequent 8 blocks is affected.
OFB, the Chinese name "Output feedback mode", unlike the CFB mode, the encryption shift register is not related to ciphertext, only with encryption key and encryption algorithm, the practice is no longer ciphertext input to the encryption shift register, but the output of the packet cipher (Oi) input to a register. Because the ciphertext does not participate in the chain operation. So makes the OFB mode more easy to be attacked, does not carry out the error propagation, a ciphertext error occurs, only affects the corresponding plaintext, but does not affect the other bits; not self-synchronizing. Assuming that the encryption and decryption two operations are out of sync, then the system needs to be initialized again, and each time another synchronization, a different initial vector should be used. To avoid generating the same bit stream. Avoid "known plaintext" attacks.
CTR. The Chinese name "Count Mode" is a series of input data blocks (called counts) are encrypted, resulting in a series of output blocks, the output block and plaintext xor or get ciphertext. For the last block of data. May be a long u bit local data block, this u bit will be used for XOR operation, and the remaining b-u bits will be discarded (b represents the length of the block).
Code Implementation
<span style= "Font-family:comic Sans MS;" ><span style= "FONT-SIZE:12PX;" >package Com.sica.des;import Com.google.common.base.strings;import Sun.misc.base64decoder;import Sun.misc.base64encoder;import Javax.crypto.cipher;import Javax.crypto.keygenerator;import Javax.crypto.SecretKey; Import Javax.crypto.secretkeyfactory;import Javax.crypto.spec.deskeyspec;import java.security.InvalidKeyException ; Import Java.security.key;import Java.security.nosuchalgorithmexception;import Java.security.securerandom;import java.security.spec.invalidkeyspecexception;/** * Created by Xiang.li on 2015/2/28. * Des plus decryption tool class * * <pre> * Support DES, Desede (TripleDES, is 3DES), AES, Blowfish, RC2, RC4 (arcfour) * des key si Ze must be equal to Desede (TripleDES) key size must being equal to or 168 * AES key size must be Equal to +, 192 or 256,but 192 and the bits may not be available * Blowfish key size must being multiple of 8, and can only range from 448 (inclusive) * RC2 key size must be between and 1024x768 bits * RC4 (arcfour) key size must be bet Ween and 1024x768 bits * Details need to focus on JDK Document http://.../docs/technotes/guides/security/SunProviders.html * </pre> */public class DES {/** * defines the encryption method */Private final static String Key_des = "DES"; Private final static String Key_aes = "AES"; Test/** * Global Array */private final static string[] hexdigits = {"0", "1", "2", "3", "4", "5", "6" , "7", "8", "9", "a", "B", "C", "D", "E", "F"}; /** * Initialize key * @return */public static String init () {return init (null); }/** * Initialize key * @param seed initialization parameter * @return */public static string init (String seed) {Secur Erandom secure = null; String str = ""; The try {if (null! = Secure) {//with the parameter initialization of secure = new SecureRandom (decryptBase64 (SE ed)); } else { Initialize secure = new SecureRandom () with no parameters; } keygenerator generator = Keygenerator.getinstance (key_des); Generator.init (secure); Secretkey key = Generator.generatekey (); str = encryptBase64 (key.getencoded ()); } catch (Exception e) {e.printstacktrace (); } return str; /** * Convert key * @param key key byte array * @return */private static key Bytetokey (byte[] key) {SEC Retkey secretkey = null; try {deskeyspec DKs = new Deskeyspec (key); Secretkeyfactory factory = secretkeyfactory.getinstance (key_des); Secretkey = Factory.generatesecret (DKS); When using other symmetric encryption algorithms, such as AES, Blowfish and other algorithms, replace the above three lines of code with the following code//Secretkey = new Secretkeyspec (key, key_des); } catch (InvalidKeyException e) {e.printstacktrace (); } catch (NoSuchAlgorithmException e) {e.printstacktrace (); } catch (InvaLidkeyspecexception e) {e.printstacktrace (); } return Secretkey; /** * DES decryption * @param data required to decrypt the string * @param key key * @return */public static string decryptd ES (string data, string key) {//Verify the passed-in string if (Strings.isnullorempty (data)) {return ""; }//Call decryption method complete decryption byte[] bytes = decryptdes (hexstring2bytes (data), key); Converts the resulting byte array into a string returning a return of new string (bytes); /** * DES decryption * @param data required to decrypt the byte array * @param key key * @return */public static byte[] Decrypt DES (byte[] data, String key) {byte[] bytes = NULL; try {Key k = Bytetokey (DecryptBase64 (key)); Cipher Cipher = cipher.getinstance (key_des); Cipher.init (Cipher.decrypt_mode, k); bytes = cipher.dofinal (data); } catch (Exception e) {e.printstacktrace (); } return bytes; }/** * DES encryption * @parAM data needs to encrypt the string * @param key Key * @return * * * public static string Encryptdes (string data, string key) { Validates the passed-in string if (Strings.isnullorempty (data)) {return ""; }//Call encryption Method complete encryption byte[] bytes = Encryptdes (Data.getbytes (), key); Converts the resulting byte array into a string returning return bytearraytohexstring (bytes); }/** * DES encryption * @param data needs to be encrypted byte array * @param key key * @return */public static byte[] Encrypt DES (byte[] data, String key) {byte[] bytes = NULL; try {Key k = Bytetokey (DecryptBase64 (key)); Cipher Cipher = cipher.getinstance (key_des); Cipher.init (Cipher.encrypt_mode, k); bytes = cipher.dofinal (data); } catch (Exception e) {e.printstacktrace (); } return bytes; }/** * BASE64 decrypt * @param key The string to decrypt * @return byte array * @throws Exception */public static Byte [] decryptBase64 (String key) throWS Exception {return (new Base64decoder ()). Decodebuffer (key); }/** * BASE64 encryption * @param key byte array to encrypt * @return String * @throws Exception */public static Stri Ng EncryptBase64 (byte[] key) throws Exception {return (new Base64encoder ()). Encodebuffer (key); }/** * Converts a byte into a 16-binary string * @param B-byte array * @return String */private static string Bytetohexstring (by Te b) {int ret = b; System.out.println ("ret =" + ret); if (Ret < 0) {ret + = 256; } int m = RET/16; int n = ret% 16; return hexdigits[m] + hexdigits[n]; }/** * Convert byte array to hexadecimal String * @param bytes byte array * @return Hexadecimal string * * * private static string Bytearraytohex String (byte[] bytes) {stringbuffer sb = new StringBuffer (); for (int i = 0; i < bytes.length; i++) {Sb.append (bytetohexstring (bytes[i])); } return sb.tostring (); }/** * Conversion 16The binary string is a byte array * @param hexstr hexadecimal String * @return */public static byte[] Hexstring2bytes (string hexstr) { Byte[] B = new Byte[hexstr.length ()/2]; int j = 0; for (int i = 0; i < b.length; i++) {char C0 = Hexstr.charat (j + +); Char C1 = Hexstr.charat (j + +); B[i] = (byte) ((Parse (C0) << 4) | Parse (c1)); } return B; }/** * Converts character type data to integer data * @param c character * @return */private static int parse (char c) {if (c = ' A ') return (C-' a ' + Ten) & 0x0f; if (c >= ' a ') return (C-' a ' +) & 0x0f; Return (C-' 0 ') & 0x0f; }/** * Test method * @param args */public static void main (string[] args) {String key = Des.init (); System.out.println ("des key: \ n" + key); String Word = "123"; String Encword = encryptdes (Word, key); SYSTEM.OUT.PRINTLN (word + "\ n encryption: \ n" + Encword);SYSTEM.OUT.PRINTLN (word + "\ n Decrypt: \ n" + decryptdes (Encword, key)); }}</span><span style= "FONT-SIZE:14PX;" ></span></span>
Conclusion
to here. This article is almost the same to end, I hope the above content to you crossing have a little help, even a bit. In fact, in the daily development, the hypothesis is not particularly strict in the progress control. For these principles, we still need to know, for those details of things, can not be memorized. If you have a net, you will be able to follow it. But this premise is that the original rational things must understand, know the principle. There will be a solution to the idea, have a train of thought, solve the problem is sooner or later, the details of it, not so tangled, do when the consideration can be, after all, time is limited.
DES in the Java encryption and decryption technology series