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 = ; 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, , data1.Length);
string pem = Encoding.UTF8.GetString(data1);
string header = String.Format("-----BEGIN {0}-----\r\n", 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(, query.Length - ); 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 = ; i <= dataArry.Length - ; i++)
{
String dataParm = dataArry[i];
int dIndex = dataParm.IndexOf("=");
if (dIndex != -)
{
String key = dataParm.Substring(, dIndex);
String value = dataParm.Substring(dIndex + , dataParm.Length - dIndex - );
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, , todecode_byte.Length);
char[] decoded_char = new char[charCount];
utf8Decode.GetChars(todecode_byte, , todecode_byte.Length, decoded_char, );
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("") || val.Equals("on")).ToString();
}
else if (field.PropertyType.Name.Equals("Decimal"))
defaultVal = 0M;
else
defaultVal = ; 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 }
}

调用

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

C#签名验签帮助类的更多相关文章

  1. Java 签名验签工具类

    public class SignatureUtil { private static final String CHARSET = "UTF-8"; private static ...

  2. RSA签名验签

    import android.util.Base64; import java.security.KeyFactory; import java.security.PrivateKey; import ...

  3. 利用SHA-1算法和RSA秘钥进行签名验签(带注释)

    背景介绍 1.SHA 安全散列算法SHA (Secure Hash Algorithm)是美国国家标准和技术局发布的国家标准FIPS PUB 180-1,一般称为SHA-1.其对长度不超过264二进制 ...

  4. RSA密钥生成、加密解密、签名验签

    RSA 非对称加密公钥加密,私钥解密 私钥签名,公钥验签 下面是生成随机密钥对: //随机生成密钥对 KeyPairGenerator keyPairGen = null; try { keyPair ...

  5. .net 实现签名验签

    本人被要求实现.net的签名验签,还是个.net菜鸡,来分享下采坑过程 依然,签名验签使用的证书格式依然是pem,有关使用openssl将.p12和der转pem的命令请转到php实现签名验签 .ne ...

  6. C# RSACryptoServiceProvider加密解密签名验签和DESCryptoServic

    C#在using System.Security.Cryptography下有 DESCryptoServiceProvider RSACryptoServiceProvider DESCryptoS ...

  7. RSACryptoServiceProvider加密解密签名验签和DESCryptoServiceProvider加解密

    原文:RSACryptoServiceProvider加密解密签名验签和DESCryptoServiceProvider加解密 C#在using System.Security.Cryptograph ...

  8. 数据安全管理:RSA加密算法,签名验签流程详解

    本文源码:GitHub·点这里 || GitEE·点这里 一.RSA算法简介 1.加密解密 RSA加密是一种非对称加密,在公开密钥加密和电子商业中RSA被广泛使用.可以在不直接传递密钥的情况下,完成加 ...

  9. js rsa sign使用笔记(加密,解密,签名,验签)

    你将会收获: js如何加密, 解密 js如何签名, 验签 js和Java交互如何相互解密, 验签(重点) 通过谷歌, 发现jsrsasign库使用者较多. 查看api发现这个库功能很健全. 本文使用方 ...

随机推荐

  1. python中的匿名函数

    python 使用 lambda 来创建匿名函数. 所谓匿名,意即不再使用 def 语句这样标准的形式定义一个函数. lambda 只是一个表达式,函数体比 def 简单很多. lambda的主体是一 ...

  2. Redis启动后基础只是讲解

    1.单进程 epoll是Linux内核为处理大批量文件描述符而作了改进的epoll,是Linux下多路复用IO接口select/poll的增强版本, 它能显著提高程序在大量并发连接中只有少量活跃的情况 ...

  3. 【零基础】AI神经元解析(含实例代码)

    一.序言 关于“深度学习”大部分文章讲的都云里雾里,直到看到“床长”的系列教程以及<深度学习入门:基于Python的理论与实现>,这里主要是对这两个教程进行个人化的总结,目标是让“0基础” ...

  4. java课后实验性问题7

    1.异常处理 import javax.swing.*; class AboutException { public static void main(String[] a) { int i = 1, ...

  5. C之数据类型

    java的数据类型 byte 1个字节 boolean 1个字节 short 2个字节 char 2个字节 int 4个字节 float 4个字节 long 8个字节 double 8个字节 c语言的 ...

  6. win7上 nginx 出现 403 Forbidden

    一般是目录权限问题,在conf文件找到 location / { index index.html index.htm index.php;# autoindex on; } 把#去掉就可以了.

  7. Qt编写自定义控件34-磁盘容量统计

    一.前言 磁盘容量统计控件,说白了,就是用来统计本地盘符占用的容量,包括但不限于已用空间.剩余空间.总大小.已用百分比等,其中对应的百分比采用进度条显示,该进度条的前景色和背景色及文字颜色可以设置,在 ...

  8. 免费申请https

    https://blog.csdn.net/MariaOzawa/article/details/81877756 实测有效

  9. Masonry问题

    1. Masonry的布局问题: 参考博客: https://github.com/huang303513/UILayoutOfiOS 2. Masonry的自适应行高问题: 参考博客:https:/ ...

  10. GBDT详解例子

    https://blog.csdn.net/zpalyq110/article/details/79527653