Android Development Java is compatible with C # AES encryption

Source: Internet
Author: User

Because the Android client is using AES encryption, the server is ASP. NET (C #), so it creates inconsistent encryption and decryption problems, the following is posted code, has been tested.

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Security.Cryptography;usingSystem.IO;namespacebll{ Public classAeshelper {/// <summary>        ///AES encryption with password/// </summary>        /// <param name= "text" >Encrypted characters</param>        /// <param name= "password" >Encrypted Password</param>        /// <param name= "IV" >secret key</param>        /// <returns></returns>         Public Static stringEncrypt (stringToencrypt,stringkey) {            byte[] Keyarray =UTF8Encoding.UTF8.GetBytes (key); byte[] Toencryptarray =UTF8Encoding.UTF8.GetBytes (Toencrypt); RijndaelManaged Rdel=Newrijndaelmanaged (); Rdel.key=Keyarray; Rdel.mode=CIPHERMODE.ECB; Rdel.padding=PADDINGMODE.PKCS7; ICryptoTransform Ctransform=Rdel.createencryptor (); byte[] Resultarray = Ctransform.transformfinalblock (Toencryptarray,0, toencryptarray.length); returnConvert.tobase64string (Resultarray,0, resultarray.length); }        /// <summary>        ///AES Decryption/// </summary>        /// <param name= "text" ></param>        /// <param name= "password" ></param>        /// <param name= "IV" ></param>        /// <returns></returns>         Public Static stringDecrypt (stringTodecrypt,stringkey) {            byte[] Keyarray =UTF8Encoding.UTF8.GetBytes (key); byte[] Toencryptarray =convert.frombase64string (Todecrypt); RijndaelManaged Rdel=Newrijndaelmanaged (); Rdel.key=Keyarray; Rdel.mode=CIPHERMODE.ECB; Rdel.padding=PADDINGMODE.PKCS7; ICryptoTransform Ctransform=Rdel.createdecryptor (); byte[] Resultarray = Ctransform.transformfinalblock (Toencryptarray,0, toencryptarray.length); returnUTF8Encoding.UTF8.GetString (resultarray); }    }}

Java

Importandroid.util.Base64;ImportJavax.crypto.Cipher;ImportJavax.crypto.spec.SecretKeySpec;/*** AES Encryption *@authorEric_ni **/ Public classAesencryptor {//Encrypt     Public StaticString Encrypt (String sSrc, String SKey)throwsException {if(SKey = =NULL) {System.out.print ("Key is null NULL"); return NULL; }        //determine if key is 16-bit        if(Skey.length ()! = 16) {System.out.print ("Key length is not 16-bit"); return NULL; }        byte[] raw = Skey.getbytes ("Utf-8"); Secretkeyspec Skeyspec=NewSecretkeyspec (Raw, "AES"); Cipher Cipher= Cipher.getinstance ("aes/ecb/pkcs5padding");//"algorithm/Mode/complement Method"Cipher.init (Cipher.encrypt_mode, Skeyspec); byte[] encrypted = Cipher.dofinal (Ssrc.getbytes ("Utf-8")); returnBase64.encodetostring (Encrypted,base64.default);//. encodetostring (encrypted,0);//The BASE64 is used here to do transcoding functions, and can play 2 times encryption function.     }    //decryption     Public StaticString Decrypt (String sSrc, String SKey)throwsException {Try {            //determine if key is correct            if(SKey = =NULL) {System.out.print ("Key is null NULL"); return NULL; }            //determine if key is 16-bit            if(Skey.length ()! = 16) {System.out.print ("Key length is not 16-bit"); return NULL; }            byte[] raw = Skey.getbytes ("Utf-8"); Secretkeyspec Skeyspec=NewSecretkeyspec (Raw, "AES"); Cipher Cipher= Cipher.getinstance ("aes/ecb/pkcs5padding");            Cipher.init (Cipher.decrypt_mode, Skeyspec); byte[] encrypted1 = Base64.decode (Ssrc,base64.default);//first decrypt with Base64 .            Try {                byte[] Original =cipher.dofinal (encrypted1); String originalstring=NewString (Original, "Utf-8"); returnoriginalstring; } Catch(Exception e) {System.out.println (e.tostring ()); return NULL; }        } Catch(Exception ex) {System.out.println (ex.tostring ()); return NULL; }    }}

I began to see people using BASE64 on the internet, citing:import org.apache.commons.codec.binary.base64;

But I downloaded, and error Base64 (). encodetostring Nosuchmethod irritability ...

Refer to import android.util.Base64 later, as you can use, notice that the Android has a static method and does not need new

Test data Android client to encrypt characters: 13 after encryption: 6u64xsoskhexxhyq3vxc3q==

Server side: Received string: 6u64xsoskhexxhyq3vxc3q== after decryption: 13

Reference Document: http://www.oschina.net/code/snippet_242957_9931

Android Development Java is compatible with C # AES encryption

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.