android開發 java與c# 相容AES加密

來源:互聯網
上載者:User

標籤:android   style   blog   http   io   ar   color   os   使用   

由於android用戶端採用的是AES加密,伺服器用的是asp.net(c#),所以就造成了不一致的加密與解密問題,下面就貼出代碼,已經實驗過。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Security.Cryptography;using System.IO;namespace BLL{    public class AESHelper    {        /// <summary>        /// 有密碼的AES加密         /// </summary>        /// <param name="text">加密字元</param>        /// <param name="password">加密的密碼</param>        /// <param name="iv">密鑰</param>        /// <returns></returns>        public static string Encrypt(string toEncrypt, string key)        {            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);            RijndaelManaged rDel = new RijndaelManaged();            rDel.Key = keyArray;            rDel.Mode = CipherMode.ECB;            rDel.Padding = PaddingMode.PKCS7;            ICryptoTransform cTransform = rDel.CreateEncryptor();            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);            return Convert.ToBase64String(resultArray, 0, resultArray.Length);        }        /// <summary>        /// AES解密        /// </summary>        /// <param name="text"></param>        /// <param name="password"></param>        /// <param name="iv"></param>        /// <returns></returns>        public static string Decrypt(string toDecrypt, string key)        {            byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);            byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);            RijndaelManaged rDel = new RijndaelManaged();            rDel.Key = keyArray;            rDel.Mode = CipherMode.ECB;            rDel.Padding = PaddingMode.PKCS7;            ICryptoTransform cTransform = rDel.CreateDecryptor();            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);            return UTF8Encoding.UTF8.GetString(resultArray);        }    }}

 

java

import android.util.Base64;import javax.crypto.Cipher;import javax.crypto.spec.SecretKeySpec;/** * AES加密器 * @author Eric_Ni * */public class AESEncryptor {    // 加密    public static String Encrypt(String sSrc, String sKey) throws Exception {        if (sKey == null) {            System.out.print("Key為空白null");            return null;        }        // 判斷Key是否為16位        if (sKey.length() != 16) {            System.out.print("Key長度不是16位");            return null;        }        byte[] raw = sKey.getBytes("utf-8");        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"演算法/模式/補碼方式"        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));        return Base64.encodeToString(encrypted,Base64.DEFAULT);//.encodeToString(encrypted,0);//此處使用BASE64做轉碼功能,同時能起到2次加密的作用。    }    // 解密    public static String Decrypt(String sSrc, String sKey) throws Exception {        try {            // 判斷Key是否正確            if (sKey == null) {                System.out.print("Key為空白null");                return null;            }            // 判斷Key是否為16位            if (sKey.length() != 16) {                System.out.print("Key長度不是16位");                return null;            }            byte[] raw = sKey.getBytes("utf-8");            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");            cipher.init(Cipher.DECRYPT_MODE, skeySpec);            byte[] encrypted1 = Base64.decode(sSrc,Base64.DEFAULT);//先用base64解密            try {                byte[] original = cipher.doFinal(encrypted1);                String originalString = new String(original,"utf-8");                return originalString;            } catch (Exception e) {                System.out.println(e.toString());                return null;            }        } catch (Exception ex) {            System.out.println(ex.toString());            return null;        }    }}

 

我開始在網上看到別人用BASE64,引用的是:import org.apache.commons.codec.binary.Base64;

但是我下載過,又報錯Base64().encodeToString  nosuchMethod  煩躁...  

後面改為引用import android.util.Base64;一樣可以用,注意 android端採用了靜態方法,不需要new

 

測試資料 android用戶端 待加密字元:13 經加密後為:6U64XSoSkheXXhyQ3vxC3Q==

伺服器端: 收到字串:6U64XSoSkheXXhyQ3vxC3Q== 解密後:13

 

參考文檔:http://www.oschina.net/code/snippet_242957_9931 

android開發 java與c# 相容AES加密

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.