Android和.NET通用的AES演算法

來源:互聯網
上載者:User

1.NET原始碼:

using System;using System.Text;using System.Security.Cryptography;namespace ConsoleApplicationDemo{    /// <summary>    /// AES對稱式加密解密類    /// </summary>    public class AESHelper    {        #region 成員變數        /// <summary>        /// 密鑰(32位,不足在後面補0)        /// </summary>        private const string _passwd = "ihlih*0037JOHT*)(PIJY*(()JI^)IO%";        /// <summary>        /// 運算模式        /// </summary>        private static CipherMode _cipherMode = CipherMode.ECB;        /// <summary>        /// 填充模式        /// </summary>        private static PaddingMode _paddingMode = PaddingMode.PKCS7;        /// <summary>        /// 字串採用的編碼        /// </summary>        private static Encoding _encoding = Encoding.UTF8;        #endregion        #region 輔助方法        /// <summary>        /// 擷取32byte密鑰資料        /// </summary>        /// <param name="password">密碼</param>        /// <returns></returns>        private static byte[] GetKeyArray(string password)        {            if (password == null)            {                password = string.Empty;            }            if (password.Length < 32)            {                password = password.PadRight(32, '0');            }            else if (password.Length > 32)            {                password = password.Substring(0, 32);            }            return _encoding.GetBytes(password);        }        /// <summary>        /// 將字元數群組轉換成字串        /// </summary>        /// <param name="inputData"></param>        /// <returns></returns>        private static string ConvertByteToString(byte[] inputData)        {            StringBuilder sb = new StringBuilder(inputData.Length * 2);            foreach (var b in inputData)            {                sb.Append(b.ToString("X2"));            }            return sb.ToString();        }        /// <summary>        /// 將字串轉換成字元數組        /// </summary>        /// <param name="inputString"></param>        /// <returns></returns>        private static byte[] ConvertStringToByte(string inputString)        {            if (inputString == null || inputString.Length < 2)            {                throw new ArgumentException();            }            int l = inputString.Length / 2;            byte[] result = new byte[l];            for (int i = 0; i < l; ++i)            {                result[i] = Convert.ToByte(inputString.Substring(2 * i, 2), 16);            }            return result;        }        #endregion        #region 加密        /// <summary>        /// 加密位元組資料        /// </summary>        /// <param name="inputData">要加密的位元組資料</param>        /// <param name="password">密碼</param>        /// <returns></returns>        public static byte[] Encrypt(byte[] inputData, string password)        {            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();            aes.Key = GetKeyArray(password);            aes.Mode = _cipherMode;            aes.Padding = _paddingMode;            ICryptoTransform transform = aes.CreateEncryptor();            byte[] data = transform.TransformFinalBlock(inputData, 0, inputData.Length);            aes.Clear();            return data;        }        /// <summary>        /// 加密字串(加密為16進位字串)        /// </summary>        /// <param name="inputString">要加密的字串</param>        /// <param name="password">密碼</param>        /// <returns></returns>        public static string Encrypt(string inputString, string password)        {            byte[] toEncryptArray = _encoding.GetBytes(inputString);            byte[] result = Encrypt(toEncryptArray, password);            return ConvertByteToString(result);        }        /// <summary>        /// 字串加密(加密為16進位字串)        /// </summary>        /// <param name="inputString">需要加密的字串</param>        /// <returns>加密後的字串</returns>        public static string EncryptString(string inputString)        {            return Encrypt(inputString, _passwd);        }        #endregion        #region 解密        /// <summary>        /// 解密位元組數組        /// </summary>        /// <param name="inputData">要解密的位元組資料</param>        /// <param name="password">密碼</param>        /// <returns></returns>        public static byte[] Decrypt(byte[] inputData, string password)        {            AesCryptoServiceProvider aes = new AesCryptoServiceProvider();            aes.Key = GetKeyArray(password);            aes.Mode = _cipherMode;            aes.Padding = _paddingMode;            ICryptoTransform transform = aes.CreateDecryptor();            byte[] data = null;            try            {                data = transform.TransformFinalBlock(inputData, 0, inputData.Length);            }            catch            {                return null;            }            aes.Clear();            return data;        }        /// <summary>        /// 解密16進位的字串為字串        /// </summary>        /// <param name="inputString">要解密的字串</param>        /// <param name="password">密碼</param>        /// <returns>字串</returns>        public static string Decrypt(string inputString, string password)        {            byte[] toDecryptArray = ConvertStringToByte(inputString);            string decryptString = _encoding.GetString(Decrypt(toDecryptArray, password));            return decryptString;        }        /// <summary>        /// 解密16進位的字串為字串        /// </summary>        /// <param name="inputString">需要解密的字串</param>        /// <returns>解密後的字串</returns>        public static string DecryptString(string inputString)        {            return Decrypt(inputString, _passwd);        }        #endregion    }}

2.Android代碼:

package com.google.test;import java.io.UnsupportedEncodingException;import javax.crypto.Cipher;import javax.crypto.spec.SecretKeySpec;/** AES對稱式加密解密類 **/public class AESHelper {/** 演算法/模式/填充 **/private static final String CipherMode = "AES/ECB/PKCS5Padding";/** 建立密鑰 **/private static SecretKeySpec createKey(String password) {byte[] data = null;if (password == null) {password = "";}StringBuffer sb = new StringBuffer(32);sb.append(password);while (sb.length() < 32) {sb.append("0");}if (sb.length() > 32) {sb.setLength(32);}try {data = sb.toString().getBytes("UTF-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}return new SecretKeySpec(data, "AES");}/** 加密位元組資料 **/public static byte[] encrypt(byte[] content, String password) {try {SecretKeySpec key = createKey(password);Cipher cipher = Cipher.getInstance(CipherMode);cipher.init(Cipher.ENCRYPT_MODE, key);byte[] result = cipher.doFinal(content);return result;} catch (Exception e) {e.printStackTrace();}return null;}/** 加密(結果為16進位字串) **/public static String encrypt(String content, String password) {byte[] data = null;try {data = content.getBytes("UTF-8");} catch (Exception e) {e.printStackTrace();}data = encrypt(data, password);String result = byte2hex(data);return result;}/** 解密位元組數組 **/public static byte[] decrypt(byte[] content, String password) {try {SecretKeySpec key = createKey(password);Cipher cipher = Cipher.getInstance(CipherMode);cipher.init(Cipher.DECRYPT_MODE, key);byte[] result = cipher.doFinal(content);return result;} catch (Exception e) {e.printStackTrace();}return null;}/** 解密16進位的字串為字串 **/public static String decrypt(String content, String password) {byte[] data = null;try {data = hex2byte(content);} catch (Exception e) {e.printStackTrace();}data = decrypt(data, password);if (data == null)return null;String result = null;try {result = new String(data, "UTF-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}return result;}/** 位元組數組轉成16進位字串 **/public static String byte2hex(byte[] b) { // 一個位元組的數,StringBuffer sb = new StringBuffer(b.length * 2);String tmp = "";for (int n = 0; n < b.length; n++) {// 整數轉成十六進位表示tmp = (java.lang.Integer.toHexString(b[n] & 0XFF));if (tmp.length() == 1) {sb.append("0");}sb.append(tmp);}return sb.toString().toUpperCase(); // 轉成大寫}/** 將hex字串轉換成位元組數組 **/private static byte[] hex2byte(String inputString) {if (inputString == null || inputString.length() < 2) {return new byte[0];}inputString = inputString.toLowerCase();int l = inputString.length() / 2;byte[] result = new byte[l];for (int i = 0; i < l; ++i) {String tmp = inputString.substring(2 * i, 2 * i + 2);result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);}return result;}}

另:要支援AES/ECB/ZeroBytePadding(對應.net的PaddingMode.Zeros),需引入bcprov .jar!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.