轉JSON字符串,並進行AES加密

轉Json時注意引用C盤裏的System.Web.Extensions.dll文件json

private string JsonEncr(object obj)
{
  System.Web.Script.Serialization.JavaScriptSerializer objSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
  string json = objSerializer.Serialize(obj);
  return json;
}

只須要傳入相應的類或其餘,例如:數組

private void Form1_Load(object sender, EventArgs e)
{
    Infomation info = new Infomation();
    nfo.name = "Curry";
    info.age = 18;
    info.gender = "男";
    textBox1.Text = JsonEncr(info);
}

private class Infomation
{
    public string name { get; set; }
    public int age { get; set; }
    public string gender { get; set; }
}

  這樣就能夠獲得相應的Json字符串了,下面說下AES加密ui

AES加密(加密步驟)
1.加密字符串獲得2進制數組;
2.將2禁止數組轉爲16進制;
3.進行base64編碼編碼

注意引用using System.Security.Cryptography;加密

private String Encrypt(String key, String toEncrypt)
{
            Byte[] _Key = Encoding.ASCII.GetBytes(key);
            Byte[] _Source = Encoding.UTF8.GetBytes(toEncrypt);

            //Aes aes = Aes.Create("AES");
            var aes = new RijndaelManaged();
            aes.Mode = CipherMode.ECB;
            aes.Padding = PaddingMode.PKCS7;
            aes.Key = _Key;

            ICryptoTransform cTransform = aes.CreateEncryptor();
            Byte[] cryptData = cTransform.TransformFinalBlock(_Source, 0, _Source.Length);
            String HexCryptString = Hex_2To16(cryptData);

            Byte[] HexCryptData = Encoding.UTF8.GetBytes(HexCryptString);
            String CryptString = Convert.ToBase64String(HexCryptData);
            return CryptString;
}

"toEncrypt"要加密的字符串,"key"密鑰orm

例如:blog

private static string Key = "0123456789012345";ip

string ecValue = Encrypt(Key, json);字符串

另外代碼中有2進制轉16進制,附上代碼get

 private String Hex_2To16(Byte[] bytes)
        {
            String hexString = String.Empty;
            Int32 iLength = 65535;
            if (bytes != null)
            {
                StringBuilder strB = new StringBuilder();

                if (bytes.Length < iLength)
                {
                    iLength = bytes.Length;
                }

                for (int i = 0; i < iLength; i++)
                {
                    strB.Append(bytes[i].ToString("X2"));
                }
                hexString = strB.ToString();
            }
            return hexString;
        }
相關文章
相關標籤/搜索