Android symmetric encryption and asymmetric encryption _android

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

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) in TA; 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 (need encrypted data) * @param key secret key, i.e. offset * @return return encrypted data/public static String en

    Crypt (string input, int key) {//Get each 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 (string input, int key) {//Get each 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 converted 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);

 }

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

The most frequently occurring characters in the statistical cipher, such as the most frequently occurring characters, are ' H '.

Calculates the offset of the character ' H ' through ' e ', with a value of 3, indicating that the original text is offset by 3 positions.

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 ()
    + "' Appearance" + entry.getvalue () + "Times"); } public static void EncryptFile (String srcfile, string destfile, int key) throws IOException {string ARTile = file2string (srcfile);
    Encrypted 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 destpath) {int decount = 0;//The number of alternative files currently decrypted//get the most frequently occurring character information (the more it appears, the more forward) list<entry<character, int
    eger>> maplist = Getmaxcountchar (input); For (Entry<character, integer> entry:maplist) {//Limit decryption file alternative number if (Decount >= de_max_file) {b
      Reak;

      ///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);
    }///Statistics string Most occurrences of the character public static List<entry<character, integer>> Getmaxcountchar (string data) {
    Map<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 () + "appearance" + entry.getvalue () + "Times");
    }*///Get maximum int maxcount = 0; For (Entry<character, integer> entry:map.entrySet ()) {//No statistics space if (/*entry.getkey ()!= ' &&
      */entry.getvalue () > Maxcount) {maxcount = Entry.getvalue (); //map convert to List for easy sorting list<entry<character, integer>> maplist = new Arraylist<map.entry<char Acter,integer>> (Map.entryset ());
      Sorts Collections.sort according to the number of occurrences of the character (Maplist, new Comparator<entry<character, integer>> () {@Override public int Compare (Entry<character, integer> O1, Entry<character, integer> O2) {return o2.g
      Etvalue (). CompareTo (O1.getvalue ());
    }
    });
  return maplist; public static string File2string (string path) throws IOException {FileReader reader = new FileReader (New File (PA
    th));
    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:

0 0 1 1 0 0 0 1
0 0 1 1 0 0 1 0
0 0 1 1 0 0 1 1
0 0 1 1 0 1 0 0
0 1 1 0 0 0 0 1
0 1 1 0 0 0 1 0
0 1 1 0 0 0 1 1
0 1 1 0 0 1 0 0

You can then perform various operations on them, such as swap location, segmentation, XOR, and so on, a common way of encryption is to operate the bit bit.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.