IOS Development Note-andriod/java/ios Three-party AES Universal encryption

Source: Internet
Author: User
Tags decrypt net cryptography

The mobile is getting more and more fire, we in the development process, always encounter with the mobile side to deal with the scene. In order to make the data interaction more secure, we need to encrypt the data transmission. Today, we studied the encryption of several languages, and realized it. Net,java (andriod), iOS are the same set of cryptographic algorithms, the following share to everyone.

AES encryption has a variety of algorithm modes, the following provides two sets of mode available source code.

Encryption method:

    1. Encrypt the text AES first
    2. return Base64 transcoding

Decryption method:

    1. BASE64 Decoding of data
    2. For AES Decryption
I. CBC (Cipher block Chaining, crypto block chain) mode

is a circular mode, the previous group of ciphertext and the current group of plaintext XOR or operation after encryption, the purpose of this is to enhance the difficulty of cracking.

    • Secret key
    • Key offset

Java/adriod encryption Aesoperator class:

 PackageCom.bci.wx.base.util;ImportJavax.crypto.Cipher;ImportJavax.crypto.spec.IvParameterSpec;ImportJavax.crypto.spec.SecretKeySpec;ImportSun.misc.BASE64Decoder;ImportSun.misc.BASE64Encoder;/*** AES is a reversible encryption algorithm, the user's sensitive information encryption processing of the original data AES encryption, in the Base64 encoding conversion;*/ Public classAesoperator {/** Encryption key can be composed of 26 letters and numbers here using AES-128-CBC encryption mode, key needs to be 16 bits. */    PrivateString SKey = "SMKLDOSPDOSLDAAA";//key, you can modify it yourself    PrivateString ivparameter = "0392039203920300";//offset, can be modified by itself    Private StaticAesoperator instance =NULL; PrivateAesoperator () {} Public Staticaesoperator getinstance () {if(Instance = =NULL) Instance=NewAesoperator (); returninstance; }     Public StaticString Encrypt (String encdata, string secretkey,string vector)throwsException {if(Secretkey = =NULL) {            return NULL; }        if(Secretkey.length ()! = 16) {            return NULL; } Cipher Cipher= Cipher.getinstance ("aes/cbc/pkcs5padding"); byte[] Raw =secretkey.getbytes (); Secretkeyspec Skeyspec=NewSecretkeyspec (Raw, "AES"); Ivparameterspec IV=NewIvparameterspec (Vector.getbytes ());//using CBC mode, a vector IV is required to increase the strength of the encryption algorithmCipher.init (Cipher.encrypt_mode, Skeyspec, iv); byte[] encrypted = Cipher.dofinal (Encdata.getbytes ("Utf-8")); return NewBase64encoder (). Encode (encrypted);//transcoding is done here using BASE64.     }    //Encrypt     PublicString Encrypt (String sSrc)throwsException {Cipher Cipher= Cipher.getinstance ("aes/cbc/pkcs5padding"); byte[] Raw =skey.getbytes (); Secretkeyspec Skeyspec=NewSecretkeyspec (Raw, "AES"); Ivparameterspec IV=NewIvparameterspec (Ivparameter.getbytes ());//using CBC mode, a vector IV is required to increase the strength of the encryption algorithmCipher.init (Cipher.encrypt_mode, Skeyspec, iv); byte[] encrypted = Cipher.dofinal (Ssrc.getbytes ("Utf-8")); return NewBase64encoder (). Encode (encrypted);//transcoding is done here using BASE64.     }    //decryption     PublicString Decrypt (String sSrc)throwsException {Try {            byte[] raw = Skey.getbytes ("ASCII"); Secretkeyspec Skeyspec=NewSecretkeyspec (Raw, "AES"); Cipher Cipher= Cipher.getinstance ("aes/cbc/pkcs5padding"); Ivparameterspec IV=NewIvparameterspec (Ivparameter.getbytes ());            Cipher.init (Cipher.decrypt_mode, Skeyspec, iv); byte[] encrypted1 =NewBase64decoder (). Decodebuffer (SSRC);//first decrypt with Base64 .            byte[] Original =cipher.dofinal (encrypted1); String originalstring=NewString (Original, "Utf-8"); returnoriginalstring; } Catch(Exception ex) {return NULL; }    }         PublicString Decrypt (String ssrc,string key,string IVs)throwsException {Try {            byte[] raw = Key.getbytes ("ASCII"); Secretkeyspec Skeyspec=NewSecretkeyspec (Raw, "AES"); Cipher Cipher= Cipher.getinstance ("aes/cbc/pkcs5padding"); Ivparameterspec IV=NewIvparameterspec (Ivs.getbytes ());            Cipher.init (Cipher.decrypt_mode, Skeyspec, iv); byte[] encrypted1 =NewBase64decoder (). Decodebuffer (SSRC);//first decrypt with Base64 .            byte[] Original =cipher.dofinal (encrypted1); String originalstring=NewString (Original, "Utf-8"); returnoriginalstring; } Catch(Exception ex) {return NULL; }    }         Public StaticString Encodebytes (byte[] bytes) {StringBuffer Strbuf=NewStringBuffer ();  for(inti = 0; i < bytes.length; i++) {strbuf.append (Char) (((Bytes[i] >> 4) & 0xF) + ((int) ' A '))); Strbuf.append ((Char) (((Bytes[i]) & 0xF) + ((int) ' A '))); }        returnstrbuf.tostring (); }     Public Static voidMain (string[] args)throwsException {//strings that need to be encryptedString CSRC = "[{\" request_no\ ": \" 1001\ ", \" service_code\ ": \" fs0001\ ", \" contract_id\ ": \" 100002\ ", \" order_id\ ": \" 0\ ", \" phone_id\ ": \" 13913996922\ ", \" plat_offer_id\ ": \" 100094\ ", \" channel_id\ ": \" 1\ ", \" activity_id\ ": \" 100045\ "}]"; //Encrypt        LongLstart =System.currenttimemillis (); String enstring=aesoperator.getinstance (). Encrypt (CSRC); System.out.println ("The encrypted string is:" +enstring); LongLusetime = System.currenttimemillis ()-Lstart; System.out.println ("Encryption Time:" + Lusetime + "milliseconds"); //decryptionLstart =System.currenttimemillis (); String destring=aesoperator.getinstance (). Decrypt (enstring); System.out.println ("The decrypted string is:" +destring); Lusetime= System.currenttimemillis ()-Lstart; System.out.println ("Decryption Time:" + Lusetime + "milliseconds"); }}

. NET Cryptography:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Security.Cryptography;usingSystem.Text;usingSystem.Threading.Tasks;namespaceaes_dome{classProgram {Private Static stringKey ="smkldospdosldaaa";//key, you can modify it yourself        Private Static stringIV ="0392039203920300";//offset, can be modified by itself        Static voidMain (string[] args) {            stringEncrytpdata = Encrypt ("ABC", key, IV);            Console.WriteLine (Encrytpdata); stringDecryptdata = Decrypt ("5z9weequvr7qtd+woxv+kw==", key, IV);            Console.WriteLine (Decryptdata);        Console.ReadLine (); }         Public Static stringEncrypt (stringToencrypt,stringKeystringIV) {byte[] Keyarray =UTF8Encoding.UTF8.GetBytes (key); byte[] Ivarray =UTF8Encoding.UTF8.GetBytes (iv); byte[] Toencryptarray =UTF8Encoding.UTF8.GetBytes (Toencrypt); RijndaelManaged Rdel=Newrijndaelmanaged (); Rdel.blocksize= -; Rdel.keysize= the; Rdel.feedbacksize= -; Rdel.padding=PADDINGMODE.PKCS7; Rdel.key=Keyarray; Rdel.iv=Ivarray; Rdel.mode=CIPHERMODE.CBC; ICryptoTransform Ctransform=Rdel.createencryptor (); byte[] Resultarray = Ctransform.transformfinalblock (Toencryptarray,0, toencryptarray.length); returnConvert.tobase64string (Resultarray,0, resultarray.length); }         Public Static stringDecrypt (stringTodecrypt,stringKeystringIV) {byte[] Keyarray =UTF8Encoding.UTF8.GetBytes (key); byte[] Ivarray =UTF8Encoding.UTF8.GetBytes (iv); byte[] Toencryptarray =convert.frombase64string (Todecrypt); RijndaelManaged Rdel=Newrijndaelmanaged (); Rdel.key=Keyarray; Rdel.iv=Ivarray; Rdel.mode=CIPHERMODE.CBC; Rdel.padding=Paddingmode.zeros; ICryptoTransform Ctransform=Rdel.createdecryptor (); byte[] Resultarray = Ctransform.transformfinalblock (Toencryptarray,0, toencryptarray.length); returnUTF8Encoding.UTF8.GetString (resultarray); }    }}

iOS source code, direct download: Source download

Ii. ECB (Electronic Code Book, electronic cipher) mode

is a basic encryption method, ciphertext is divided into blocks of equal length of the block (not enough), and then individually encrypted, one by one output composed ciphertext.

You only need to provide a password.

Ios,android,java has been transferred source code: Source Download

AES online encryption and decryption verification tool: http://www.seacha.com/tools/aes.html

IOS Development Note-andriod/java/ios Three-party AES Universal encryption

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.