public void Encrypt(string FileName)
{
string tempFile = Path.GetTempFileName();
byte[] file = null;
using (BinaryReader reader = new BinaryReader(new
FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read)))
{
file = new byte[reader.BaseStream.Length];
reader.Read(file, 0, file.Length);
}
//// Signature
// create ContentInfo (what is signed)
ContentInfo content = new ContentInfo(file);
// object representing a signed message
SignedCms signedMessage = new SignedCms(content);
// create CmsSigner (who signs)
CmsSigner signer = new CmsSigner(_signer);
signer.IncludeOption = X509IncludeOption.EndCertOnly;
// sign the message
signedMessage.ComputeSignature(signer, false);
// create serialized representation
byte[] signedBytes = signedMessage.Encode();
//// Encryption
// create ContentInfo (what is encrypted)
ContentInfo signedContent = new ContentInfo(signedBytes);
// object representing an encrypted message
EnvelopedCms encryptedMessage = new EnvelopedCms(signedContent);
// add recipients
CmsRecipientCollection recipients = new CmsRecipientCollection();
foreach (X509Certificate2 cert in _recipients)
{
CmsRecipient recipient = new CmsRecipient(cert);
recipients.Add(recipient);
}
// encrypt the message
encryptedMessage.Encrypt(recipients);
// create serialized representation
byte[] signedAndEncryptedBytes = encryptedMessage.Encode();
using (BinaryWriter writer = new BinaryWriter(new
FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None)))
{
writer.Write(signedAndEncryptedBytes);
}
File.Delete(FileName);
File.Move(tempFile, FileName);
}
Also, have you tested signing with the smart card in other apps (works fine
in Outlook or similar)?
--
Joe Kaplan-MS MVP Directory Services Programming
Co-author of "The .NET Developer's Guide to Directory Services Programming"
http://www.directoryprogramming.net
"mtrekker" <mtre...@discussions.microsoft.com> wrote in message
news:BFB32284-C90C-47C6...@microsoft.com...
From what I can tell, the CmsSigner object only supports private keys that
are stored with normal Windows key containers or protected with via Windows
CSPs, so I don't see how you'll be able to make this work. The only thing I
can think of would be to find a .NET PKCS#11 library that will allow you to
access the private key on the smart card, then create an in memory key
container and somehow use that to build up the certificate object you use to
create the CmsSigner. However, I'm not really sure about if this would even
work. I've not seen this scenario attempted.
Ideally you'd have a CSP driver for your card instead.
--
Joe Kaplan-MS MVP Directory Services Programming
Co-author of "The .NET Developer's Guide to Directory Services Programming"
http://www.directoryprogramming.net
"mtrekker" <mtre...@discussions.microsoft.com> wrote in message
news:CA826B60-5A39-45D0...@microsoft.com...