You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

306 lines
9.6 KiB
C#

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.Runtime.InteropServices;
namespace NetLibrary.Safety
{
/**//// <summary>
/// 私钥加密(对称加密)
/// </summary>
public class CryptoPrivate
{
private SymmetricAlgorithm mobjCryptoService;
private string Key;
/**//// <summary>
/// 对称加密类的构造函数
/// 密钥可以通过当前公司进行编码以其编码为Key。
/// </summary>
/// <param name="key">密钥</param>
public CryptoPrivate(string key)
{
mobjCryptoService = new RijndaelManaged();
//mobjCryptoService.
Key=key;
}
/// <summary>
/// 获得密钥
/// </summary>
/// <returns>密钥</returns>
private byte[] GetLegalKey()
{
string sTemp = Key;
mobjCryptoService.GenerateKey();
//生成随机密钥
byte[] bytTemp = mobjCryptoService.Key; //取得密钥
int KeyLength = bytTemp.Length; //密钥长度
if (sTemp.Length > KeyLength) //如果<<公司标志>>长度大于密钥长度,返回长度等于密钥长度一样的字符串
sTemp = sTemp.Substring(0, KeyLength);
else if (sTemp.Length < KeyLength) //如果<<公司标志>>长度小于密钥长度用空格填充到密钥所需长度
sTemp = sTemp.PadRight(KeyLength, ' ');
return ASCIIEncoding.ASCII.GetBytes(sTemp); //返回密钥数组
}
/**//// <summary>
/// 获得初始向量IV
/// </summary>
/// <returns>初试向量IV</returns>
private byte[] GetLegalIV()
{
string sTemp = "E3ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";
mobjCryptoService.GenerateIV();
byte[] bytTemp = mobjCryptoService.IV;
int IVLength = bytTemp.Length;
if (sTemp.Length > IVLength)
sTemp = sTemp.Substring(0, IVLength);
else if (sTemp.Length < IVLength)
sTemp = sTemp.PadRight(IVLength, ' ');
return ASCIIEncoding.ASCII.GetBytes(sTemp);
}
/// <summary>
/// 加密方法
/// </summary>
/// <param name="Source">待加密的串</param>
/// <returns>经过加密的串</returns>
public string Encrypto(string Source)
{
byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
MemoryStream ms = new MemoryStream();
mobjCryptoService.Key = GetLegalKey();
mobjCryptoService.IV = GetLegalIV();
ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();
CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
cs.Write(bytIn, 0, bytIn.Length);
cs.FlushFinalBlock();
ms.Close();
byte[] bytOut = ms.ToArray();
return Convert.ToBase64String(bytOut);
}
/// <summary>
/// 解密方法
/// </summary>
/// <param name="Source">待解密的串</param>
/// <returns>经过解密的串</returns>
public string Decrypto(string Source)
{
StreamReader sr;
byte[] bytIn = Convert.FromBase64String(Source);
MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
mobjCryptoService.Key = GetLegalKey();
mobjCryptoService.IV = GetLegalIV();
ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
sr = new StreamReader(cs);
return sr.ReadToEnd();
}
public static string Encryp(string Source)
{
CryptoPrivate cp = new CryptoPrivate("formmatwizard54073");
return cp.Encrypto(Source);
}
public static string Decryp(string Source)
{
CryptoPrivate cp = new CryptoPrivate("formmatwizard54073");
return cp.Decrypto(Source);
}
}
/// <summary>
/// 公钥加密(不对称加密)
/// </summary>
public class CryptoPublic
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
/// <summary>
/// 返回私钥
/// </summary>
public string GetPrikey()
{
string pubkey = rsa.ToXmlString(false); //公钥
return rsa.ToXmlString(true); //返回私钥
}
/// <summary>
/// 返回公钥
/// </summary>
public string GetPubkey()
{
string pubkey = rsa.ToXmlString(false); //公钥
return rsa.ToXmlString(false); //返回公钥
}
/// <summary>
/// 加密方法(要加密的字符串byte不能超过117个字节)
/// </summary>
/// <param name="Source">待加密的串</param>
/// <param name="pubkey">公钥</param>
public string Encrypto(string Source,string pubkey)
{
byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
rsa.FromXmlString(pubkey);
byte[] bytOut=rsa.Encrypt(bytIn,false); //加密数据
return Convert.ToBase64String(bytOut);
}
/// <summary>
/// 解密方法
/// </summary>
/// <param name="Source">待解密的串</param>
/// <pubkey>私钥</pubkey>
public string Decrypto(string Source,string prikey)
{
byte[] bytIn = Convert.FromBase64String(Source);
rsa.FromXmlString(prikey);
byte[] d=rsa.Decrypt(bytIn,false); //解密数据
return UTF8Encoding.UTF8.GetString(d);
}
/// <summary>
/// 数字签名
/// </summary>
/// <param name="Source">要签名的字符串</param>
/// <param name="prikey">私钥</param>
public string RsaCreateSignature(string Source,string prikey)
{
rsa.FromXmlString(prikey);
RSAPKCS1SignatureFormatter f = new RSAPKCS1SignatureFormatter(rsa);
f.SetHashAlgorithm("MD5");
byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(bytIn);
byte[] b = f.CreateSignature(result); //针对希哈值进行签名
return Convert.ToBase64String(b); //取得签名后希哈值
}
/// <summary>
/// 验证签名
/// </summary>
/// <param name="Source">要验证的字符串</param>
/// <param name="pubkey">公钥</param>
/// <param name="Hash">签名后的字符串</param>
public bool RsaVerifySignature(string Source,string Hash,string pubkey)
{
rsa.FromXmlString(pubkey);
RSAPKCS1SignatureDeformatter f = new RSAPKCS1SignatureDeformatter(rsa);
f.SetHashAlgorithm("MD5");
byte[] key = Convert.FromBase64String(Hash);
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] name = md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(Source));
if (f.VerifySignature(name,key)==true){return true;}
return false;
}
public static string GetHashPassword(string password)
{
MD5 md5 = MD5.Create();
byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
public static string GetHashPassword(string password,int StartIndex,int Length)
{
MD5 md5 = MD5.Create();
byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString().Substring(StartIndex,Length);
}
/**//// <summary>
/// MD5 32位加密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string Md5For32(string str)
{
string cl = str;
string pwd = "";
MD5 md5 = MD5.Create();//实例化一个md5对像
// 加密后是一个字节类型的数组这里要注意编码UTF8/Unicode等的选择 
byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
// 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
for (int i = 0; i < s.Length; i++)
{
// 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母如果使用大写X则格式后的字符是大写字符
pwd = pwd + s[i].ToString("x2");
}
return pwd;
}
}
/// <summary>
/// U盘加密
/// </summary>
public class UCryptoPublic
{
[DllImport("HD_Security.dll")]
private static extern int HD_VerifyPassword(StringBuilder password, int passwordlen);
[DllImport("HD_Security.dll")]
private static extern int HD_Initialize(StringBuilder password, int passwordlen);
[DllImport("HD_Security.dll")]
public static extern int HD_GetDeviceSn(StringBuilder szSn, ref int nSnLen);
/// <summary>
/// 验证密码'成功(9000)打开设备失败(0)认证密码不正确(2)密码长度不正确(3)'
/// </summary>
/// <param name="password">密码</param>
/// <param name="passwordlen">密码长度</param>
public static int VerifyPassword(StringBuilder password, int passwordlen)
{
return HD_VerifyPassword(password, passwordlen);
}
/// <summary>
/// 初始化密码'成功(9000)打开设备失败(0)初始化设备失败(1)密码长度不正确(3)'
/// </summary>
/// <param name="password">密码</param>
/// <param name="passwordlen">密码长度</param>
public static int Initialize(StringBuilder password, int passwordlen)
{
return HD_Initialize(password, passwordlen);
}
/// <summary>
/// 返回U盘序列号'成功(9000)打开设备失败(0)获得序列号失败(4)'
/// </summary>
/// <param name="szSn">输出序列号</param>
/// <param name="nSnlen">输出序列号长度</param>
public static int GetDeviceSn(out string szSn, out int nSnLen)
{
StringBuilder sb = new StringBuilder(60);
int snlen = 0;
int a = HD_GetDeviceSn(sb, ref snlen);
szSn = sb.ToString();
nSnLen = snlen;
return a;
}
}
}