DES in the Java encryption and decryption technology series

Source: Internet
Author: User
Tags base64 decrypt



Order
The previous articles talk about the one-way encryption algorithm, which involves the BASE64, MD5, SHA, HMAC and several more common encryption and decryption algorithm. This article, and later, intends to introduce several symmetric cryptographic algorithms, such as DES, 3DES (TripleDES), AES, and so on. Well, this article is mainly about DES about a bit.

Background
Before we talk about DES, let's look at what a symmetric encryption algorithm is. For symmetric encryption algorithm, he applied the time earlier, the technology is relatively mature, in the symmetric encryption algorithm, the data originator will be clear (raw data) and encryption key together through a special encryption algorithm processing, so that it becomes a complex encryption ciphertext sent out. After receiving the ciphertext, if you want to interpret the original text, it is necessary to decrypt the ciphertext by using the encryption key and the inverse algorithm of the same algorithm, so that it can be restored to readable plaintext.


In the symmetric encryption algorithm, only one key is used, both parties use this key to encrypt and decrypt the data, which requires the decryption party must 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 a lot of people are very interested, because in the development of the time, the requirements of the relatively strict, many times there is no time to understand these things. So today we specialize in studying this thing.
DES, known as the "Data Encryption Standard", is a block algorithm that uses key cryptography in Chinese, which is called the "encryption standards". DES algorithm is a symmetric cryptosystem in the cryptography system, also known as the United States data Encryption Standard, is the 1972 U.S. IBM developed symmetric cryptography algorithm. The plaintext is grouped by 64 bits, the key is 64 bits long, and the key is in fact 56 bits participating in the DES operation (8th, 16, 24, 32, 40, 48, 56, 64 bits are check bits, so that each key has an odd number of 1) the plaintext group and the 56-bit key are substituted or exchanged to form ciphertext group encryption Method.

Basic principle
There are three entry parameters: key, data, mode. Key is the secret key used for encryption and decryption, and data is encrypteddecrypt the data, mode for its operating modes. When the mode is in encryption mode, plaintext is grouped by 64 bits to form a clear text group, key is used to encrypt the data, and when the mode is 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, and the key used is also 64 bits, and the algorithm is divided into two main steps:
    • Initial displacement
Its function is to put the input 64 bits of data block re-combination, and the output is divided into L0, R0 two parts, each of the length of 32 bits, the substitution rules for the 58th position of the input to the first position, 50th place to 2nd bit ... And so on, the last one is the original 7th place. L0, R0 is the two parts of the output, L0 is the left 32 bits of output, R0 is the right 32 bits, 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.
    • Inverse displacement
After 16 iterations, we get L16, R16, this as input, inverse substitution, inverse permutation is just the inverse of the initial permutation, which is the ciphertext output.
The main flowchart for the entire algorithm is as follows:



Grouping Mode
    • ECB mode

The ECB, the Chinese name "Electronic cipher Mode", is the oldest and simplest mode, which divides the encrypted data into groups, each with the same size as the encryption key. Then each group is encrypted with the same key, such as the DES algorithm, if the last packet length is not 64 bits, the 64 bits should be padded. :


    • CBC mode

CBC, 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 the same plaintext is used with the same key and initial vector.


    • CFB Mode

CFB, Chinese name "Cryptographic feedback mode", the cryptographic feedback mode overcomes the disadvantage of waiting for 8 bytes to encrypt, it uses the block cipher as the key stream generator of the stream password. His characteristic is that each encryption of Pi and Ci is not greater than 64 bits, encryption algorithm and decryption algorithm is the same, not suitable for public key algorithm, using the same key and initial vector, the same plaintext using the CFB mode encryption output the same cipher; You can use different initialization variables to produce different ciphertext for the same plaintext, Prevent dictionary attacks; The encryption strength depends on the key length, the encryption block length is too small, it increases the number of loops, resulting in increased overhead, and the length of the encryption block is 8-bit integer times (that is, bytes); Once an error occurs, the data for the current and subsequent 8 blocks is affected.


    • OFB mode

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 ciphertext does not participate in the chain operation, so that the OFB mode is more vulnerable to attack, no error propagation, a ciphertext error, will only affect the corresponding plaintext of the bit, without affecting the other bits, not self-synchronizing, if the encryption and decryption two operations out of sync, then the system needs to be reinitialized, each time resynchronization , a different initial vector should be used. Avoids generating the same bitstream and avoids "known plaintext" attacks.


    • CTR Mode

CTR, Chinese name "Counting 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, it may be a long U-bit local data block, the 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 * Specific content needs 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"; Testing/** * 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 = ""; try {if (null! = Secure) {//initialize with parameter secure = new SecureRandom (decryptBase64 (SE            ed));             } else {   Initialize with no parameters secure = new SecureRandom ();            } 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 needed 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 to 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 needed 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 requires an encrypted 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 to complete encryption byte[] bytes = Encryptdes (Data.getbytes (), key);    Converts the resulting byte array into a string returning return bytearraytohexstring (bytes); }/** * DES encryption * @param data requires an 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 decryption * @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 required to encrypt byte array * @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
Here, this article is almost over, hope that the above content to you crossing have a little help, even a bit better. In fact, in the daily development, if not the progress of the control of the special strict, for these principles of things, we still need to know, for those details of things, can not memorize, there is a net, with the use of follow-up can be. 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 the time to consider on the line, after all, time is limited.

DES in the Java encryption and decryption technology series

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.