AES Encryption _android for Android data encryption

Source: Internet
Author: User
Tags decrypt key string md5 encryption random seed asymmetric encryption stringbuffer

Objective:

In addition to landing in the project, payment and other interfaces using RSA asymmetric encryption, outside the use of AES symmetric encryption, today we come to understand the AES encryption.

Several other encryption methods:
RSA encryption of Android data encryption
AES encryption of Android data encryption
Des encryption of Android data encryption
MD5 encryption of Android data encryption
BASE64 coding algorithm of Android data encryption
The safe hashing algorithm of SHA for android Data encryption

What is AES encryption?

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.

Let's actually look at how to do that:

For a brief introduction to the Aesutils class constants:

  Private final static String HEX = "0123456789ABCDEF";
  private static final String cbc_pkcs5_padding = "aes/cbc/pkcs5padding";//aes is encrypted. CBC is working mode pkcs5padding is fill mode
  Private static final String AES = "AES";//aes encryption
  private static final string sha1prng= "Sha1prng";////sha1prng strong random seed algorithm , to distinguish the calling method of more than 4.2 versions

How do I generate a random key?

  
   * * Generate random number, can be used as dynamic key encryption and decryption key must be consistent, otherwise it will not be
   decrypted
  /public static String GenerateKey () {
    try {
      SecureRandom localsecurerandom = securerandom.getinstance (sha1prng);
      byte[] Bytes_key = new BYTE[20];
      Localsecurerandom.nextbytes (Bytes_key);
      String Str_key = Tohex (Bytes_key);
      return str_key;
    } catch (Exception e) {
      e.printstacktrace ();
    }
    return null;
  }

AES Key Processing

  Processing of keys
  private static byte[] Getrawkey (byte[] seed) throws Exception {keygenerator
    KGen = Keygenerator.getin Stance (AES);
    For Android
    securerandom sr = null;
    In more than 4.2 versions, the SecureRandom acquisition has changed
    if (Android.os.Build.VERSION.SDK_INT >=) {
      sr = Securerandom.getinstance (sha1prng, "Crypto");
    } else {
      sr = securerandom.getinstance (SHA1PRNG);
    }
    For Java
    //SecureRandom = Securerandom.getinstance (sha1prng);
    Sr.setseed (seed);
    Kgen.init (128, SR); The 128-bit key version of the 256 bits or 128 bits,192bits
    //aes has 10 encryption loops, 192-bit key versions have 12 encryption loops, and 256-bit key versions have 14 encryption loops.
    Secretkey skey = Kgen.generatekey ();
    Byte[] raw = skey.getencoded ();
    return raw;
  

AES Encryption process


   * * Encryption/Public
  static string Encrypt (string key, String cleartext) {
    if Textutils.isempty (cleartext ) {return
      cleartext;
    }
    try {
      byte[] result = Encrypt (key, cleartext.getbytes ());
      return Base64encoder.encode (result);
    } catch (Exception e) {
      e.printstacktrace ();
    }
    return null;
  }
  * * Encryption
  /private static byte[] Encrypt (String key, byte[] clear) throws Exception {
    byte[] raw = Get Rawkey (Key.getbytes ());
    Secretkeyspec Skeyspec = new Secretkeyspec (raw, AES);
    Cipher Cipher = cipher.getinstance (cbc_pkcs5_padding);
    Cipher.init (Cipher.encrypt_mode, Skeyspec, New Ivparameterspec (New Byte[cipher.getblocksize ()));
    Byte[] Encrypted = cipher.dofinal (clear);
    return encrypted;
  }

AES Decryption Process

  
   * * Decryption/Public
  static string decrypt (string key, String encrypted) {
    if Textutils.isempty (encrypted ) {return
      encrypted;
    }
    try {
      byte[] enc = base64decoder.decodetobytes (encrypted);
      Byte[] result = Decrypt (key, enc);
      return new String (result);
    } catch (Exception e) {
      e.printstacktrace ();
    }
    return null;
  }
   * * Decryption
  /private static byte[] Decrypt (String key, byte[] encrypted) throws Exception {
    byte[] raw = Getrawkey (Key.getbytes ());
    Secretkeyspec Skeyspec = new Secretkeyspec (raw, AES);
    Cipher Cipher = cipher.getinstance (cbc_pkcs5_padding);
    Cipher.init (Cipher.decrypt_mode, Skeyspec, New Ivparameterspec (New Byte[cipher.getblocksize ()));
    byte[] decrypted = cipher.dofinal (encrypted);
    return decrypted;
  }

Binary Turn characters

 Binary turn character public
  static String Tohex (byte[] buf) {
    if (buf = = null) return
      "";
    StringBuffer result = new StringBuffer (2 * buf.length);
    for (int i = 0; i < buf.length i++) {
      Appendhex (result, buf[i));
    return result.tostring ();
  }

  private static void Appendhex (StringBuffer sb, byte b) {
    sb.append (Hex.charat ((b >> 4) & 0x0f)). Append (HEX . CharAt (b & 0x0f));
  

Test program:

 list<person> personlist = new arraylist<> ();  int testmaxcount = maximum number of data bars for 1000;//test//Add test data for (int i = 0; i < Testmaxcount; i++) {Person person = new
      Person ();
      Person.setage (i);
      Person.setname (string.valueof (i));
    Personlist.add (person);
    //fastjson generate JSON data String Jsondata = Jsonutils.objecttojsonforfastjson (personlist);
    LOG.E ("Mainactivity", "AES encrypted before JSON data---->" + jsondata);

    LOG.E ("Mainactivity", "AES encrypted before JSON data length---->" + jsondata.length ());
    Generates a dynamic key String Secretkey = Aesutils.generatekey ();

    LOG.E ("Mainactivity", "AES dynamic Secretkey---->" + secretkey);
    AES Encryption Long start = System.currenttimemillis ();
    String encrystr = Aesutils.encrypt (Secretkey, jsondata);
    Long end = System.currenttimemillis ();
    LOG.E ("Mainactivity", "AES encryption time-consuming cost time---->" + (End-start));
    LOG.E ("Mainactivity", "AES encrypted after JSON data---->" + encrystr); LOG.E ("Mainactivity", "AES encrypted after the length of the JSON data----> "+ encrystr.length ());
    AES Decryption start = System.currenttimemillis ();
    String decrystr = Aesutils.decrypt (Secretkey, ENCRYSTR);
    End = System.currenttimemillis ();
    LOG.E ("Mainactivity", "AES decryption time-consuming cost time---->" + (End-start));

 LOG.E ("Mainactivity", "AES decrypted after JSON data---->" + decrystr);

Running time is time-consuming:

This shows that the symmetric AES efficiency is still relatively high.

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.