Android Security Encryption: Symmetric encryption detailed _android

Source: Internet
Author: User
Tags base64 binary to decimal decrypt numeric value asymmetric encryption stringbuffer

Android security encryption feature article index

    1. Android Secure encryption: Symmetric encryption
    2. Android Secure encryption: Asymmetric encryption
    3. Android Secure encryption: Message digest Digest
    4. Android Security Encryption: Digital signatures and digital certificates
    5. Android Secure encryption: HTTPS programming

The above learning all content, symmetric encryption, asymmetric encryption, message digest, digital signature and other knowledge is to understand the work of digital certificates as a preliminary knowledge. Digital certificate is the ultimate weapon in cryptography, is the crystallization of the wisdom of human thousands of years history, only after understanding the working principle of digital certificate, can we understand the secure communication mechanism of HTTPS protocol. It will eventually be handy in the SSL development process.

In addition, the two knowledge points of symmetric encryption and message digest can be used separately.

Digital certificates use all the knowledge you have learned

    1. Symmetric encryption and asymmetric encryption are used to achieve the secret key exchange, after which the two parties use the secret key for symmetric encrypted communication.
    2. Message digest and asymmetric encryption to achieve digital signature, the root certificate authority to sign the target certificate, at the time of verification, the root certificate with the public key to verify it. If the checksum succeeds, the certificate is trusted.
    3. The Keytool tool can create certificates, then submit them to the root certification authority for direct use of self-signed certificates, as well as output the RFC format information for certificates.
    4. Digital signature technology realizes the guarantee of identity authentication and data integrity.
    5. The encryption technology guarantees the confidentiality of the data, the message digest algorithm guarantees the integrity of the data, the high efficiency of symmetric encryption guarantees the reliability of the processing, and the digital signature technology guarantees the non-repudiation of the operation.

Through the above content of learning, we should be able to grasp the following knowledge points:

    1. Basics: Bit bits, bytes, characters, character encodings, incoming transformations, IO
    2. Know how to use symmetric encryption to solve problems in actual development
    3. Know symmetric encryption, asymmetric encryption, message digest, digital signature, digital certificate is to solve the problem of what happened
    4. Understanding the SSL communication process
    5. How to request HTTPS interface in actual development

Caesar Code

1. Introduce

Caesar cipher as one of the most ancient symmetric encryption system, in ancient Rome has been very popular, his basic idea is: by moving the letters to a certain number of digits to achieve encryption and decryption. All letters in the plaintext are replaced Cheng Mi-wen after they are offset (or forward) by a fixed number on the alphabet. For example, when the offset is 3, all the letters A will be replaced with D,B into E, thus, the digits are the key to the encryption and decryption of the Caesar's cipher.

For example: Each character of the string "ABC" characters to the right 3-bit to "def", and when decrypted, the "Def" is moved 3 digits to the left to restore, as shown in the following figure:

2. Preparation of knowledge

 Character converts to ASCII numeric value
 char chara = ' a ';
 int intA = Chara; Char is converted to int to get the corresponding ASCII code value, the value of ' a ' is converted to

char
int intA = 97;//97 corresponding ASCII code ' a '
char chara = (char) i NtA; The int value is strongly converted to char to get the corresponding ASCII character, that is, ' a '

3. Caesar Password Simple Code implementation

 /** * Encryption * @param input data source (requires encrypted data) * @param key key, i.e. offset * @return returns the encrypted data/public static String encrypt (Strin

 g input, int key) {//Get every character in the string char[] array = Input.tochararray ();
 for (int i = 0; i < Array.Length ++i) {//character converted to ASCII code value int ascii = Array[i];
 Character offsets, such as a->b ASCII = ASCII + key;
 ASCII code value conversion to char char Newchar = (char) ASCII;

 Replace the original character array[i] = Newchar;
 The above 4 lines of code can be abbreviated to one line//array[i] = (char) (Array[i] + key);
 The//character array is converted to string return new string (array); /** * Decryption * @param input data source (encrypted data) * @param key key, i.e. offset * @return return decrypted data/public static String decrypt (Str
 ing input, int key) {//Get every character in the string char[] array = Input.tochararray ();
 for (int i = 0; i < Array.Length ++i) {//character converted to ASCII code value int ascii = Array[i];
 Restores character offsets, such as b->a ASCII = Ascii-key;
 ASCII code value conversion to char char Newchar = (char) ASCII;

 Replace the original character array[i] = Newchar;
 The above 4 lines of code can be abbreviated to one line//array[i] = (char) (Array[i]-key); }//character array converted to string return nEW String (array);

 }

Code Output results:

4. Decode Caesar Password: Frequency analysis method

Caesar password encryption strength is too low, only need to use the frequency analysis method can be cracked.

In any written language, different letters or combinations of letters appear in varying frequencies. Moreover, for any piece of text written in this language, there are roughly the same characteristic letter distributions. For example, in English, the letter E appears with a high frequency, while X appears less.

The typical distribution of letters in English text is shown in the following illustration:

5. Crack the process

    1. The most frequently occurring characters in the statistical cipher, such as the most frequently occurring characters, are ' H '.
    2. Calculates the offset of the character ' H ' through ' e ', with a value of 3, indicating that the original text is offset by 3 positions.
    3. Restores all characters in redaction to 3 locations.

Note: The most frequent characters in the statistical ciphertext, you need to count a few alternatives, because the most likely is a space or other characters, such as the most frequent characters ' # ' is a space after the character, ' H ' is the ' e ' offset value.

Decryption to try more than a few times, because not necessarily the most frequent characters is the target character we want, the following figure, the second decryption result is correct.

/** * Frequency analysis method to crack Caesar's password/public class Frequencyanalysis {//English the most frequent characters private static final char Magic_char = ' E ';

 Crack generated maximum number of files private static final int de_max_file = 4;

 public static void Main (string[] args) throws Exception {//test 1, statistics number of characters//printcharcount ("Article1_en.txt");
 Encrypted file//int key = 3;

 EncryptFile ("Article1.txt", "Article1_en.txt", key);
 Read the encrypted file String artile = file2string ("Article1_en.txt");
 Decrypt (generates multiple alternative files) decryptcaesarcode (artile, "article1_de.txt");
 public static void Printcharcount (string path) throws ioexception{string data = file2string (path);
 List<entry<character, integer>> maplist = Getmaxcountchar (data);  For (Entry<character, integer> entry:maplist) {//Output the first few statistics System.out.println ("character" + entry.getkey () + "' appear" +
 Entry.getvalue () + "Times"); } public static void EncryptFile (String srcfile, string destfile, int key) throws IOException {string artile = File
 2String (Srcfile); Encrypting file String encryptdata = myEncrypt.encrypt (artile, key);
 Save the Encrypted file String2file (encryptdata, destfile); /** * Crack Caesar Password * @param input data source * @return return decrypted data/public static void Decryptcaesarcode (string input, String d Estpath) {int decount = 0;//The number of alternate files generated by the current decryption//get the most frequently occurring character information (more often than not) List<entry<character, integer>> Maplis
 t = Getmaxcountchar (input);
 For (Entry<character, integer> entry:maplist) {//Limit decryption file alternative number if (Decount >= de_max_file) {break;

 ///Output previous statistics System.out.println ("character" + entry.getkey () + "' appears" + entry.getvalue () + "Times");
 ++decount;
 The highest occurrence of the character and the offset of the Magic_char is the key int key = Entry.getkey ()-Magic_char;
 SYSTEM.OUT.PRINTLN ("guessing key =" + key + ", decryption generates the first" + Decount + "Alternate file" + "\ n");

 String decrypt = myencrypt.decrypt (input, key);
 String fileName = "De_" + Decount + destpath;
 String2file (decrypt, fileName); The most common static list<entry<character in the characters that appear in the statistics string, integer>> Getmaxcountchar (string data) {MAP&L T Character, integer> Map = new Hashmap<character, integer> ();
 char[] array = Data.tochararray ();
 for (char C:array) {if (!map.containskey (c)) {Map.put (c, 1);
 }else{Integer count = Map.get (c);
 Map.put (c, Count + 1); ///Output statistics/*for (Entry<character, integer> entry:map.entrySet ()) {System.out.println (Entry.getkey () + "appears
 "+ entry.getvalue () +" Times ");
 }*///Get maximum int maxcount = 0; For (Entry<character, integer> entry:map.entrySet ()) {//No statistics space if (/*entry.getkey ()!= ' && */entry.ge
 TValue () > Maxcount) {maxcount = Entry.getvalue (); //map convert to List for easy sorting list<entry<character, integer>> maplist = new Arraylist<map.entry<character,int
 Eger>> (Map.entryset ()); Sort Collections.sort (maplist, New Comparator<entry<character, integer>> () {@Override public int C, according to the number of occurrences of the character Ompare (Entry<character, integer> O1, Entry<character, integer> O2) {return O2.getvalue (). CompareTo (
 O1.getvalue ());
 }
 }); Return Maplist; public static string File2string (string path) throws IOException {FileReader reader = new FileReader (new File (path))
 ;
 char[] buffer = new char[1024];
 int len =-1;
 StringBuffer sb = new StringBuffer ();
 while (len = reader.read (buffer))!=-1) {sb.append (buffer, 0, Len);
 return sb.tostring ();
 public static void String2file (string data, string path) {FileWriter writer = null;
 try {writer = new FileWriter (new File (path));
 Writer.write (data);
 catch (Exception e) {e.printstacktrace ();
 }finally {if (writer!= null) {try {writer.close ();
 catch (IOException e) {e.printstacktrace ();

 }
 }
 }

 }
}

Symmetric encryption

Introduced

Both encryption and decryption use the same secret key, a cryptographic method called symmetric encryption, also known as single key encryption.
Simple to understand: encryption and decryption are the same key.

Caesar's password is symmetric encryption, and his character offset is the secret key.

Common algorithms for symmetric encryption

AES, DES, 3DES, Tdea, Blowfish, RC2, RC4, RC5, Idea, skipjack and so on.

DES: All known as the data encryption Standard, the encryption standard, is a block algorithm using key cryptography, which was identified by the United States federal government's national standards office as a federal data Processing standard (FIPS) in 1976 and subsequently widely circulated internationally.

3DES: Also known as Triple DES, is a generic term for the triple-Data encryption Algorithm (Tdea,triple-Encryption-algorithm) block cipher.
It is equivalent to applying three DES encryption algorithms to each block of data. The encryption key length of the original des Cipher becomes easily brute force because of the enhancement of computer computing power; 3DES is designed to provide a relatively simple way to avoid similar attacks by increasing the length of the Des's key, rather than designing a new block cipher algorithm.

AES: Advanced Encryption Standard (English: Advanced encryption Standard, abbreviation: AES), also known as the Rijndael encryption method in cryptography, is a block encryption standard used by the U.S. federal government. This standard, which replaces the original DES, has been analyzed and widely used worldwide. After five years of selection process, the Advanced Encryption Standard was issued by the National Institute of Standards and Technology (NIST) on November 26, 2001 in FIPS PUB 197 and became an effective standard on May 26, 2002. In the 2006, the Advanced Encryption Standard has become one of the most popular algorithms in symmetric key cryptography.

Introduction to DES algorithm

DES encryption principle (for bits to operate, swap positions, XOR, etc., do not need to know more)

Prepare knowledge

Bit is the smallest transmission unit of a computer. A value of 0 or one to indicate the bit bit

For example the number 3 corresponding binary data is: 00000011

code example

 int i = A;
 String bit = integer.tobinarystring (i);
 Output: 97 the corresponding binary data is: 1100001
 System.out.println (i + "corresponding binary data is:" + bit);

Byte and bit difference

Data storage is in "byte" (byte), data transfer is mostly with "bit" (bit, also known as "bit" as a unit, a bit represents a 0 or 1 (i.e., binary), each 8 bits (bit, abbreviated B) Form a byte (byte, abbreviated to B), is the smallest level of information units.

Byte Value Range:

BYTE value range:-128 to 127
System.out.println (Byte.min_value + "to" + Byte.max_value);

That is, between 10000000 and 01111111, one byte occupies 8 bits

Binary to decimal diagram:

Any string can be converted to a byte array

String data = "1234ABCD";
byte[] bytes = data.getbytes ()/content: 49 50 51 52 97 98 99 100

Above data 49 50 51 52 97 98 99 100 corresponding binary data (i.e. bit bit):

00110001
00110010
00110011
00110100
01100001
01100010
01100011
01100100

Turn them up a little bit, and you can be seen as a matrix:

They can then be performed on a variety of operations, such as swap location, segmentation, XOR, and so on, the common way of encryption is to operate the bit bit, such as the following image of the IP permutation and S-box operations are common encryption of some ways:

IP substitution:

S-box Replacement:

DES Encryption Process Diagram (the process is very complex, only need to know that the internal operation of the bit bit can):

Symmetric encryption Application Scenario

    1. Local data encryption (such as encrypting some sensitive data inside sharedpreferences in Android)
    2. Network transport: Login interface POST request parameter encryption {username=lisi,pwd=ojya4i9vasroxvlh75wpcg==}
    3. Encrypt user logon result information and serialize to local disk (Serialize user object to local disk, deserialize to memory at next logon)
    4. Web page interactive data encryption (ie, HTTPS after learning)

DES Algorithm Code implementation

1, Get Cipher object (can be translated as a cipher or cipher system)
 Cipher Cipher = cipher.getinstance ("DES");
 2, create the secret key
 Secretkey = Keygenerator.getinstance ("DES"). GenerateKey ();
 3, set operation mode (encryption/decryption)
 Cipher.init (Cipher.encrypt_mode, key);
 4, perform operation
 byte[] result = Cipher.dofinal ("Dark Horse". GetBytes ());

AES Algorithm Code implementation

Use ditto, just replace "DES" parameter "AES" can.

Results of encryption using BASE64 encoding

Byte[] result = Cipher.dofinal ("Dark Horse". GetBytes ());
System.out.println (new String (result));

Output results:

The result of the encryption is a byte array, these encrypted bytes in the Code table (such as UTF-8 Code table) can not find the corresponding characters, will appear garbled, when the garbled string converted to a byte array, the length will change, resulting in decryption failure, so the converted data is not safe.

Using Base64 to encode the byte array, any byte can be mapped into the corresponding Base64 characters, then can be restored to the byte array, which is conducive to the data stored in the transmission after encryption, so the conversion is safe. Similarly, it is safe to convert a byte array into a 16 string.

The output result of converting ciphertext into BASE64 encoding:

Conversion of ciphertext into 16-encoded output:

Java does not directly provide Base64 and byte array to 16 into the API, development in general is their own handwritten or direct use of third-party provided by the mature and stable tool classes (such as Apache Commons-codec).

Base64 Character Mapping table

How to apply symmetric encryption in a specific way

1. Generate the secret key and save it to the hard disk, read the secret key later to encrypt and decrypt the operation, the actual development of the use of relatively little

Generate Random secret key
Secretkey Secretkey = keygenerator.getinstance ("AES"). GenerateKey ();
Serializing a secret key to disk
fileoutputstream fos = new FileOutputStream (New File ("Heima.key"));

ObjectOutputStream oos = new ObjectOutputStream (FOS);
Oos.writeobject (Secretkey);

Read the secret key from the disk
fileinputstream FIS = new FileInputStream ("Heima.key");
ObjectInputStream ois = new ObjectInputStream (FIS);
Key key = (key) ois.readobject ();

2. Use a custom secret key (write the secret key in the code)

Create key notation 1
keyspec keyspec = new Deskeyspec (Key.getbytes ());
Secretkey Secretkey = secretkeyfactory.getinstance (algorithm).
Generatesecret (KEYSPEC);

Create key notation 2
//secretkey secretkey = new Secretkeyspec (Key.getbytes (), key_algorithm);

Cipher Cipher = cipher.getinstance (cipher_algorithm);
Cipher.init (Cipher.decrypt_mode, secretkey);
After the key, the following code is cipher, omitted here ...

Attention matters

Write a secret key in the code there is a certain risk, when others decompile the code, you may see the secret key, Android development in the proposed use JNI to write the key value in C code, or even split into several, and finally combined into a real secret key

Algorithm/working mode/Fill mode

When initializing a cipher object, the parameter can pass the algorithm name directly: for example:

Cipher C = cipher.getinstance ("DES");

You can also specify a more detailed parameter, format: "Algorithm/mode/padding", that is, "algorithm/work Mode/fill mode"

Cipher C = cipher.getinstance ("des/cbc/pkcs5padding");

Cipher Block Working mode

Block cipher mode of operation is an extension of the encryption method for block-handling passwords, not only for AES, including DES, but also for cryptographic methods such as RSA.

Fill mode

Padding (Padding) is the data that needs to be processed by block, when the data length does not conform to the block processing requirements, a rule that fills the block length according to a certain method.

Specific code:

Secret key algorithm
private static final String Key_algorithm = "DES";
Encryption algorithm: Algorithm/mode/padding algorithm/working mode/fill mode
private static final String Cipher_algorithm = "des/ecb/pkcs5padding";
//secret key
private static final string key = "12345678";//des secret key length must be 8 bits or more
//private static final String key = "12 34567890123456 ";//aes secret key length must be 16 bits

//initialization secret key
Secretkey secretkey = new Secretkeyspec (Key.getbytes (), Key_ algorithm);
Cipher Cipher = cipher.getinstance (cipher_algorithm);

Encryption
Cipher.init (Cipher.encrypt_mode, secretkey);
Byte[] result = Cipher.dofinal (Input.getbytes ());

Note: AES and DES require IV parameters in CBC operation mode

AES and DES need IV parameter
IVPARAMETERSPEC IV = new Ivparameterspec (Key.getbytes ()) in CBC operation mode.

Encryption
Cipher.init (Cipher.encrypt_mode, Secretkey, iv);

Summarize

DES security is not high enough in modern times, then the 3DES algorithm has been improved a lot, but its implementation efficiency is low, AES algorithm encryption strength, high execution efficiency, simple to use, the actual development of the proposed AES algorithm. In actual Android development, symmetric encryption, such as selecting the AES algorithm, can be used to solve many problems, such as:

    1. To do a management password of the app, we use different password in different websites, it is difficult to remember, want to do a unified management of the app, but the account password saved in the phone, once lost easy to cause security risks, so need an encryption algorithm, the account password information encrypted to keep, At this time, if the use of symmetric encryption algorithm, the data encryption, the secret key we keep in mind, only need to remember a password. You can restore the information when needed.
    2. When you need to store sensitive data in sharedprefrence, you can also use symmetric encryption, which can be restored when needed.
    3. When requesting a network interface, we need to upload some sensitive data, also can use symmetric encryption, the server uses the same algorithm can be decrypted. or the server needs to pass data to the client, it can also be encrypted first, and then the client uses the same algorithm to decrypt it.

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.