【asp.net小札记】序列化实体类为xml格式和hmac_md5加密

前端之家收集整理的这篇文章主要介绍了【asp.net小札记】序列化实体类为xml格式和hmac_md5加密前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1、序列化

/// <summary>
    /// 序列化为xml,返回规范化数据
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="c"></param>
    /// <returns></returns>
    public static string ToXml<T>(T c) where T : class
    {
        string str = string.Empty;
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Encoding = Encoding.GetEncoding("GB2312");
        settings.OmitXmlDeclaration = true;//是否编写声明
        settings.NewLineOnAttributes = true;
        //settings.Indent = true;
        XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
        namespaces.Add("","");
        using (MemoryStream ms = new MemoryStream())
        {
            using (XmlWriter writer = XmlWriter.Create(ms,settings))
            {
                //writer.WriteRaw("<?xml version='1.0' encoding='GB2312' standalone='yes'?>\r\n");
                writer.WriteRaw("<?xml version='1.0' encoding='GB2312' standalone='yes'?>");
                XmlSerializer serializer = new XmlSerializer(c.GetType());
                serializer.Serialize(writer,c,namespaces);
                byte[] arr = ms.ToArray();
                str = Encoding.GetEncoding("GB2312").GetString(arr,arr.Length);
                return str;
            }
        }
    }


2、加密

public class Md5Util
{
    /// <summary>
    ///  密钥
    /// </summary>
    public static readonly string key = "134143141";

    /// <summary>
    /// HMAC_MD5 算法
    /// </summary>
    /// <param name="key">密钥</param>
    /// <param name="str">明文</param>
    /// <returns></returns>
    public static string GetHMAC_Md5String(string key,string str)
    {
        byte[] keybytes = GetUTF8(key);
        using (HMACMD5 hmac = new HMACMD5(keybytes))
        {
            byte[] bs = hmac.ComputeHash(GetUTF8(str));
            StringBuilder sb = new StringBuilder();
            foreach (byte b in bs)
            {
                sb.AppendFormat("{0:x2}",b);
            }
            return sb.ToString();
        }
    }

    /// <summary>
    /// 返回字节数组
    /// </summary>
    /// <param name="content"></param>
    /// <returns></returns>
    public static byte[] GetUTF8(string content)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(content);
        return bytes;
    }

    /// <summary>
    /// 返回指定数组的md5哈希值
    /// </summary>
    /// <param name="sources"></param>
    /// <returns></returns>
    public static byte[] GetHash(byte[] sources)
    {
        MD5CryptoServiceProvider MD5CSP = new MD5CryptoServiceProvider();
        byte[] targets = MD5CSP.ComputeHash(sources);
        return targets;
    }
}

猜你在找的XML相关文章