[Android development experience] How to ensure consistency between DES encryption on Android and the server, androiddes

Source: Internet
Author: User

[Android development experience] How to ensure consistency between DES encryption on Android and the server, androiddes

Reprinted please indicate the source: http://blog.csdn.net/zhaokaiqiang1992

When our applications involve sensitive data, we usually perform simple encryption on the data. In data interaction with servers, apart from using post requests to enhance data security, we can use common encryption algorithms to encrypt data. Today, we mainly introduce the DES encryption algorithm.

First, DES is a symmetric encryption algorithm. symmetric encryption means that encryption and decryption use the same key. In our actual application, the same key is used when the server and client encrypt and decrypt data. In addition, there is an asymmetric encryption algorithm, that is, the public key and private key mechanism. This method can be used for identity authentication, which will be detailed later.

DES is called Data EncryptionStandard, which is the Data encryption standard. It is a block algorithm that uses Key encryption. The DES algorithm has three entry parameters: Key, Data, and Mode. Among them, the Key is a 7-byte 56-bit, which is the working Key of the DES algorithm; the Data is 8-byte 64-bit, which is the Data to be encrypted or decrypted; the Mode is DES, which can be encrypted or decrypted.

The following code implements DES encryption in Java or Android:

Package com. qust. rollcallstudent. utils; import java. security. invalidAlgorithmParameterException; import java. security. key; import java. security. spec. algorithmParameterSpec; import java. util. locale; import javax. crypto. cipher; import javax. crypto. secretKeyFactory; import javax. crypto. spec. DESKeySpec; import javax. crypto. spec. ivParameterSpec;/***** @ ClassName: com. qust. rollcallstudent. utils. DESUtil * @ Descr Iption: DES encryption and decryption toolkit * @ author zhaokaiqiang * @ date 8:40:56 **/public class DESUtil {public static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding "; /*** DES algorithm, encrypt ** @ param data * string to be encrypted * @ param key * encrypt the private key, the length cannot be less than 8 characters * @ return the encrypted byte array. Generally, the * @ throws InvalidAlgorithmParameterException * @ throws Exception */public static String encode (String key, string data) {if (data = Null) return null; try {Your eyspec dks = new your eyspec (key. getBytes (); SecretKeyFactory keyFactory = SecretKeyFactory. getInstance ("DES"); // The length of the key cannot be less than 8 bytes Key secretKey = keyFactory. generateSecret (dks); Cipher cipher = Cipher. getInstance (ALGORITHM_DES); IvParameterSpec iv = new IvParameterSpec ("12345678 ". getBytes (); AlgorithmParameterSpec paramSpec = iv; cipher. init (Cipher. ENCRYPT_MODE, secretKey, par AmSpec); byte [] bytes = cipher. doFinal (data. getBytes (); return byte2String (bytes);} catch (Exception e) {e. printStackTrace (); return data ;}/ *** DES algorithm, decrypt the ** @ param data * string to be decrypted * @ param key * to decrypt the private key, the length cannot be less than 8 characters * @ return the decrypted byte array * @ throws Exception */public static String decode (String key, String data) {if (data = null) return null; try {Your eyspec dks = new your eyspec (key. getBytes (); SecretKeyF Actory keyFactory = SecretKeyFactory. getInstance ("DES"); // The length of the key cannot be less than 8 bytes Key secretKey = keyFactory. generateSecret (dks); Cipher cipher = Cipher. getInstance (ALGORITHM_DES); IvParameterSpec iv = new IvParameterSpec ("12345678 ". getBytes (); AlgorithmParameterSpec paramSpec = iv; cipher. init (Cipher. DECRYPT_MODE, secretKey, paramSpec); return new String (cipher. doFinal (byte2hex (data. getBytes ();} catch (Ex Ception e) {e. printStackTrace (); return data ;}/ *** Binary Conversion String ** @ param B * @ return */private static String byte2String (byte [] B) {StringBuilder hs = new StringBuilder (); String stmp; for (int n = 0; B! = Null & n <B. length; n ++) {stmp = Integer. toHexString (B [n] & 0XFF); if (stmp. length () = 1) hs. append ('0'); hs. append (stmp);} return hs. toString (). toUpperCase (Locale. CHINA);}/*** convert binary to hexadecimal ** @ param B * @ return */private static byte [] byte2hex (byte [] B) {if (B. length % 2 )! = 0) throw new IllegalArgumentException (); byte [] b2 = new byte [B. length/2]; for (int n = 0; n <B. length; n + = 2) {String item = new String (B, n, 2); b2 [n/2] = (byte) Integer. parseInt (item, 16);} return b2 ;}}

If you just want to use it, you don't have to look down. Let's start with some details about the DES algorithm.

In the above encryption and decryption method, we passed in a string "DES/CBC/PKCS5Padding" when getting the Cipher instance. What do these three parameters mean?

In fact, the three parameters correspond to the "algorithm/mode/fill", that is, we must use the DES algorithm for encryption, adopt the CBC mode, and use the PKCS5Padding mode for filling.

In addition to the CBC mode and ECB mode, different encryption methods are used.

So what is the difference between the CBC model and the ECB model?


The ECB mode refers to the electronic cryptographic model, which is the oldest and simplest mode. It divides encrypted data into several groups, and the size of each group is the same as the length of the encryption key; then, each group uses the same key for encryption, such as the DES algorithm. If the last group is not 64-bit long, it must be 64-bit. This mode features:

1. Each Key, plaintext, and ciphertext length must be 64 bits;

2. Duplicate sorting of data blocks does not require detection;

3. The same plaintext block (using the same key) generates the same ciphertext block, which is prone to dictionary attacks;

4. An error affects only one ciphertext block;

The CBC mode refers to the encrypted block chain mode. The biggest difference from the ECB mode is that the initial vector is added. The following code obtains an initial vector,

IvParameterSpec iv = new IvParameterSpec ("12345678". getBytes ());

This mode features:

1. the ciphertext length encrypted each time is 64 bits (8 bytes );

2. When the same plaintext uses the same key and initial vector, the CBC mode always produces the same ciphertext;

3. ciphertext blocks depend on previous operation results. Therefore, ciphertext blocks cannot be rearranged;

4. Different Initialization vectors can be used to prevent the same ciphertext produced by the same plain text, so as to resist dictionary attacks to a certain extent;

5. After an error occurs, the current and subsequent ciphertext values will be affected;

The PKCS5Padding parameter indicates the data completing mode when the number of data digits is insufficient. It can also be called the data filling mode.

PKCS5Padding: specifically, "the number that is filled indicates the total number of entered bytes"

For example, if the difference is two bytes, that is, ##### 22, and the difference is five bytes, that is, ### 55555, you can know the number and quantity of the padding according to the last one.

After introducing these details of DES, we can know that on different platforms, as long as these parameters can be consistent, encryption and decryption can be achieved.

1. the encryption and decryption keys are consistent.

2. When using the CBC mode, ensure that the initial vector is consistent.

3. Use the same filling mode

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.