C#签名验签帮助类

using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;

namespace VWFC.IT.CUP.BLL.Common
{
    /// <summary>
    /// web tools
    /// </summary>
    public sealed class WebUtils
    {
        #region Get Private Key
        /// <summary>
        /// Get Private Key
        /// </summary>
        /// <param name="path">pfx path</param>
        /// <param name="password">Private key password</param>
        /// <returns></returns>
        static public string GetPrivateKey(string path, string password)
        {
            try
            {
                X509Certificate2 cert = new X509Certificate2(path, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
                return cert.PrivateKey.ToXmlString(true);
            }
            catch
            {
                return string.Empty;
            }
        }
        #endregion

        #region Get Public Key
        /// <summary>
        /// Get Public Key
        /// </summary>
        /// <param name="path">pfx path</param>
        /// <param name="password">Private key password</param>
        /// <returns></returns>
        static public string GetPublicKey(string path, string password)
        {
            try
            {
                X509Certificate2 cert = new X509Certificate2(path, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
                return cert.PublicKey.Key.ToXmlString(false);
            }
            catch
            {
                return string.Empty;
            }
        }
        #endregion

        #region Get SHA512 Hash From String
        /// <summary>
        /// Get SHA512 Hash From String
        /// </summary>
        /// <param name="originalData"></param>
        /// <returns></returns>
        static public string GetHash512String(string originalData)
        {
            string result = string.Empty;
            byte[] bytValue = Encoding.UTF8.GetBytes(originalData);
            SHA512 sha512 = new SHA512CryptoServiceProvider();
            byte[] retVal = sha512.ComputeHash(bytValue);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            result = sb.ToString();
            return result;
        }

        /// <summary>
        /// Get SHA512 Hash From String
        /// </summary>
        /// <param name="originalData"></param>
        /// <returns></returns>
        static public string GetSHA512HashFromString2(string originalData)
        {
            string result = string.Empty;
                byte[] buffer = Encoding.UTF8.GetBytes(originalData);
                SHA512CryptoServiceProvider SHA512 = new SHA512CryptoServiceProvider();
                byte[] h5 = SHA512.ComputeHash(buffer);
                result = BitConverter.ToString(h5).Replace("-", string.Empty);
                result = result.ToLower();
            return result;
        }
        #endregion

        #region Get the value of the key from the key file
        /// <summary>
        /// Get the value of the key from the key file
        /// </summary>
        /// <param name="type">RSA PRIVATE KEY/RSA PUBLIC KEY</param>
        /// <param name="pemUrl">url of the key file</param>
        /// <returns>base64 string</returns>
        static public string GetKeyFromPem(string type, string pemUrl)
        {
            string base64 = string.Empty;
            try
            {
                using (FileStream fs = File.OpenRead(pemUrl))
                {
                    byte[] data1 = new byte[fs.Length];
                    fs.Read(data1, 0, data1.Length);
                    string pem = Encoding.UTF8.GetString(data1);
                    string header = String.Format("-----BEGIN {0}-----
", type);
                    string footer = String.Format("-----END {0}-----", type);
                    int start = pem.IndexOf(header) + header.Length;
                    int end = pem.IndexOf(footer, start);
                    base64 = pem.Substring(start, (end - start));
                }
            }
            catch { }
            return base64;
        }
        #endregion

        #region Parse Dictionary

        #region Dictionary Parse To String
        /// <summary>
        /// Dictionary Parse To String
        /// </summary>
        /// <param name="parameters">Dictionary</param>
        /// <returns>String</returns>
        static public string ParseToString(IDictionary<string, string> parameters)
        {
            IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
            IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();

            StringBuilder query = new StringBuilder("");
            while (dem.MoveNext())
            {
                string key = dem.Current.Key;
                string value = dem.Current.Value;
                if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
                {
                    query.Append(key).Append("=").Append(value).Append("&");
                }
            }
            string content = query.ToString().Substring(0, query.Length - 1);

            return content;
        }
        #endregion

        #region String Parse To Dictionary
        /// <summary>
        /// String Parse To Dictionary
        /// </summary>
        /// <param name="parameter">String</param>
        /// <returns>Dictionary</returns>
        static public Dictionary<string, string> ParseToDictionary(string parameter)
        {
            try
            {
                String[] dataArry = parameter.Split('&');
                Dictionary<string, string> dataDic = new Dictionary<string, string>();
                for (int i = 0; i <= dataArry.Length - 1; i++)
                {
                    String dataParm = dataArry[i];
                    int dIndex = dataParm.IndexOf("=");
                    if (dIndex != -1)
                    {
                        String key = dataParm.Substring(0, dIndex);
                        String value = dataParm.Substring(dIndex + 1, dataParm.Length - dIndex - 1);
                        dataDic.Add(key, value);
                    }
                }

                return dataDic;
            }
            catch
            {
                return null;
            }
        }
        #endregion

        #endregion

        #region Base64 encryption and decryption

        /// <summary>
        /// 服务器端Base64编码
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        static public string Base64Encode(string data)
        {
            string result = data;
            try
            {
                byte[] encData_byte = Encoding.UTF8.GetBytes(data);
                result = Convert.ToBase64String(encData_byte);
            }
            catch { }

            return result;
        }

        /// <summary>
        /// 服务器端Base64解码
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        static public string Base64Decode(string data)
        {
            string result = data;
            string decode = string.Empty;
            //try
            //{
            //    byte[] bytes = Convert.FromBase64String(result);
            //    decode = Encoding.UTF8.GetString(bytes);
            //}
            //catch { }
            try
            {
                UTF8Encoding encoder = new UTF8Encoding();
                Decoder utf8Decode = encoder.GetDecoder();
                byte[] todecode_byte = Convert.FromBase64String(data);
                int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
                char[] decoded_char = new char[charCount];
                utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
                result = new String(decoded_char);
            }
            catch { }

            return result;
        }

        #endregion

        #region Assign parameters to specified objects

        /// <summary>
        /// Assign parameters to specified objects
        /// </summary>
        /// <typeparam name="T">object type</typeparam>
        /// <param name="dic">Fields/values</param>
        /// <returns></returns>
        static public T Assign<T>(Dictionary<string, string> dic) where T : new()
        {
            Type myType = typeof(T);
            T entity = new T();
            var fields = myType.GetProperties();
            string val = string.Empty;
            object obj = null;

            foreach (var field in fields)
            {
                if (!dic.ContainsKey(field.Name))
                    continue;
                val = dic[field.Name];

                object defaultVal;
                if (field.PropertyType.Name.Equals("String"))
                    defaultVal = "";
                else if (field.PropertyType.Name.Equals("Boolean"))
                {
                    defaultVal = false;
                    val = (val.Equals("1") || val.Equals("on")).ToString();
                }
                else if (field.PropertyType.Name.Equals("Decimal"))
                    defaultVal = 0M;
                else
                    defaultVal = 0;

                if (!field.PropertyType.IsGenericType)
                    obj = string.IsNullOrEmpty(val) ? defaultVal : Convert.ChangeType(val, field.PropertyType);
                else
                {
                    Type genericTypeDefinition = field.PropertyType.GetGenericTypeDefinition();
                    if (genericTypeDefinition == typeof(Nullable<>))
                        obj = string.IsNullOrEmpty(val) ? defaultVal : Convert.ChangeType(val, Nullable.GetUnderlyingType(field.PropertyType));
                }

                field.SetValue(entity, obj, null);
            }

            return entity;
        }

        #endregion

    }
}
View Code

 调用

            //string publickKeyCer = Path.Combine(baseDirectory, AppConfig.GetPublicKeyCer);
            //publicKey = WebUtils.GetKeyFromPem("CERTIFICATE", publickKeyCer);

            //privateKey = WebUtils.GetPrivateKey(fileKeyUrl, AppConfig.GetPrivateKeyPassword);
View Code
原文地址:https://www.cnblogs.com/hofmann/p/11556604.html