C# Andriod AES 加密算法

android端:

package com.kingmed.http;
import java.io.UnsupportedEncodingException;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
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;
    }
 
   
    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;
    }
 
   
    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;
    }
 
   
    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(); // 转成大写
    }
 
   
    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;
    }
}

.NET端:

using System;
using System.Text;
using System.Security.Cryptography;

///
///AESHelper 的摘要说明
///
///
/// AES对称加密解密类
///
public class AESHelper
{
    #region 成员变量
    ///
    /// 密钥(32位,不足在后面补0)
    ///
    private const string _passwd = "ihlih*0037JOHT*)(PIJY*(()JI^)IO%";
    ///
    /// 运算模式
    ///
    private static CipherMode _cipherMode = CipherMode.ECB;
    ///
    /// 填充模式
    ///
    private static PaddingMode _paddingMode = PaddingMode.PKCS7;
    ///
    /// 字符串采用的编码
    ///
    private static Encoding _encoding = Encoding.UTF8;
    #endregion

    #region 辅助方法
    ///
    /// 获取32byte密钥数据
    ///
    /// 密码
    ///
    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);
    }

    ///
    /// 将字符数组转换成字符串
    ///
    ///
    ///
    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();
    }

    ///
    /// 将字符串转换成字符数组
    ///
    ///
    ///
    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 加密
    ///
    /// 加密字节数据
    ///
    /// 要加密的字节数据
    /// 密码
    ///
    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;
    }

    ///
    /// 加密字符串(加密为16进制字符串)
    ///
    /// 要加密的字符串
    /// 密码
    ///
    public static string Encrypt(string inputString, string password)
    {
        byte[] toEncryptArray = _encoding.GetBytes(inputString);
        byte[] result = Encrypt(toEncryptArray, password);
        return ConvertByteToString(result);
    }

    ///
    /// 字符串加密(加密为16进制字符串)
    ///
    /// 需要加密的字符串
    /// 加密后的字符串
    public static string EncryptString(string inputString)
    {
        return Encrypt(inputString, _passwd);
    }
    #endregion

    #region 解密
    ///
    /// 解密字节数组
    ///
    /// 要解密的字节数据
    /// 密码
    ///
    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;
    }

    ///
    /// 解密16进制的字符串为字符串
    ///
    /// 要解密的字符串
    /// 密码
    /// 字符串
    public static string Decrypt(string inputString, string password)
    {
        byte[] toDecryptArray = ConvertStringToByte(inputString);
        string decryptString = _encoding.GetString(Decrypt(toDecryptArray, password));
        return decryptString;
    }

    ///
    /// 解密16进制的字符串为字符串
    ///
    /// 需要解密的字符串
    /// 解密后的字符串
    public static string DecryptString(string inputString)
    {
        return Decrypt(inputString, _passwd);
    }
    #endregion
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2014-03-24 13:08  JamesFan  阅读(118)  评论(0编辑  收藏  举报