http://www.bouncycastle.org/csharp/index.html
下载bin的zip文件。
工程添加引用“BouncyCastle.Crypto.dll”
代码添加引用:
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto.Parameters;
签名&读证书序列号:
FileStream fileStream = null;
try
{
fileStream = new FileStream(certPath, FileMode.Open);
Pkcs12Store store = new Pkcs12Store(fileStream, certPwd.ToCharArray());
string pName = null;
foreach (string n in store.Aliases)
{
if (store.IsKeyEntry(n))
{
pName = n;
//break;
}
}
Cert signCert = new Cert();
AsymmetricKeyParameter key = store.GetKey(pName).Key;
X509CertificateEntry[] chain = store.GetCertificateChain(pName);
X509Certificate cert = chain[0].Certificate;
string certId = cert.SerialNumber.ToString(); //证书序列号
ISigner normalSig = SignerUtilities.GetSigner("SHA1WithRSA");
normalSig.Init(true, key);
normalSig.BlockUpdate(data, 0, data.Length);
byte[] normalResult = normalSig.GenerateSignature(); //签名结果
}
finally
{
if (fileStream != null)
fileStream.Close();
}
验签&读证书序列号:
FileStream fileStream = null;
try
{
fileStream = new FileStream(file.DirectoryName + "\\" + file.Name, FileMode.Open);
X509Certificate certificate = new X509CertificateParser().ReadCertificate(fileStream);
string certId = certificate.SerialNumber.ToString(); //证书序列号
AsymmetricKeyParameter key = certificate.GetPublicKey();
ISigner verifier = SignerUtilities.GetSigner("SHA1WithRSA");
verifier.Init(false, key);
verifier.BlockUpdate(srcByte, 0, srcByte.Length);
return verifier.VerifySignature(signature); //验签结果
}
finally
{
if(fileStream != null)
fileStream.Close();
}
加密:
FileStream fileStream = null;
try
{
fileStream = new FileStream(file.DirectoryName + "\\" + file.Name, FileMode.Open);
X509Certificate certificate = new X509CertificateParser().ReadCertificate(fileStream);
string certId = certificate.SerialNumber.ToString(); //证书序列号
AsymmetricKeyParameter key = certificate.GetPublicKey();
IBufferedCipher c = CipherUtilities.GetCipher("RSA/NONE/PKCS1Padding");
c.Init(true, new ParametersWithRandom(key, new SecureRandom()));
return c.DoFinal(dataToBeEnc); //加密结果
}
finally
{
if(fileStream != null)
fileStream.Close();
}