日期:2014-05-18  浏览次数:20963 次

用C#去做数字签名
用C#语言怎么从本机去查到指定容器名的证书,并且去做签名,或者去进行签名的验证.我用CertOpenStore()和函数CertFindCertificateInStore去读证书的信息的时候CertFindCertificateInStore总读不出来信息,有那为朋友作过,介绍一下函数的声明,结构体的声明,谢谢

------解决方案--------------------
//给指定文件生成一个数字签名文件
private void GenerateADigitalSignatureFile(string fName, string fDigName)
{
DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
FileStream fs = new FileStream(fName,FileMode.Open,FileAccess.Read);
byte[] bt = new byte[fs.Length];
textBox7.Text = dsa.ToXmlString(false); //生成的公匙
bt = dsa.SignData(fs);
//string str = BitConverter.ToString(bt);
FileStream fw = new FileStream(fDigName,FileMode.OpenOrCreate,FileAccess.Write);
fw.Write(bt,0,bt.Length);
fs.Close();
fw.Close();
}

//验证文件的数字签名
private bool VerifyFileDig(string fName, string fDigName, string key)
{
DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
FileStream f = new FileStream(fName,FileMode.Open,FileAccess.Read);
byte[] bfile = new byte[f.Length];
f.Read(bfile,0,bfile.Length);
f.Close();

FileStream fd = new FileStream(fDigName,FileMode.Open,FileAccess.Read);
byte[] bd = new byte[fd.Length];
fd.Read(bd,0,bd.Length);
fd.Close();
dsa.FromXmlString(key);
return dsa.VerifyData(bfile,bd);
}
------解决方案--------------------
using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;
using System.Web.Security;

namespace Paladin.Common
{
/// <summary>
/// Security 的摘要说明。
/// 对称加密算法 : DES / TripleDES / RC2 / Rijndael
/// 非对称加密算法 : DSA / RSA
/// </summary>
public class Cryptography
{
public Cryptography()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
// DES 的加密方法 。
// 私钥加密 / 对称算法 。
public static string Encrypt_Des( string cleanString )
{
//.NET 框架提供的对称加密类需要一个密钥和一个新的 IV 来加密和解密数据。
//每当使用默认的构造函数创建其中一个托管对称加密类的新实例时,就会自动创建新的密钥和 IV
//DES 使用 64 位密钥、64 位块来加密和解密数据。每个数据块迭代 16 次以生成加密文本。
//初始化向量(IV) 用来第一次对数据块进行加密 。
byte[] KEY_64 = {42, 16, 93, 156, 78, 4, 218, 32}; // 指定的 Key
byte[] IV_64 = {55, 103, 246, 79, 36, 99, 167, 3}; // 初始化向量(IV)
DESCryptoServiceProvider provider = new DESCryptoServiceProvider ( ) ;
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream( ms , provider.CreateEncryptor( KEY_64,IV_64 ) , CryptoStreamMode.Write ) ;
StreamWriter sw = new StreamWriter( cs ) ;
sw.Write( cleanString ) ;
sw.Flush( ) ;
cs.FlushFinalBlock( ) ;
ms.Flush( ) ;
return Convert.ToBase64String( ms.GetBuffer( ) , 0 , int.Parse( ( ms.Length.ToString ( ) ) ) ) ;
}

// DES 的解密方法 。
// 私钥加密 / 对称算法 。
public static string Decrypt_Des( string encryptedString )
{
byte[] KEY_64 = {42, 16, 93, 156, 78, 4, 218, 32};
byte[] IV_