Click here to Skip to main content
Click here to Skip to main content

Cryptography in .NET

By , 9 Oct 2002
 

Overview

Windows provides a Public Key Infrastructure (PKI) that allows us to store certificates for encryption purposes. To access the this store we had two possibilities in the unmanaged past: The CryptoAPI and the CAPICOM.

The Framework Class Library (= FCL) provies a lot of function for encryption, but the current release doesn't provide any classes for accessing the the certificate store. Fortunately a the Web Services Development Kit (WSDK) Technology Preview adds this functionality; later this will be included in the FCL itself. But in the mean time you have to download the WSDK.

Enumerating The Certificate Store

The article Using WS-Security with the Web Services Development Kit Technology Preview has this nice example:
using Microsoft.WSDK.Security.Cryptography;
using Microsoft.WSDK.Security.Cryptography.X509Certificates;
  ...
private X509CertificateStore store;
  ...
private void Form1_Load( object sender, System.EventArgs e )
{
    store = X509CertificateStore.CurrentUserStore( X509CertificateStore.MyStore );
    store.OpenRead();
    foreach( X509Certificate cert in store.Certificates )
    {
        listBox1.Items.Add( cert.GetName() );
    }
}

Asymmetric Encryption/Signature Example

The following code is the funcionallity of my submitted example. It assumes that you have at least two certificates (with private key!) in your Personal Certificate Store.

try
{

   // GENERAL CODE TO READ THE CERTIFICATES FROM THE WINDOWS PKI INFRASTRUCTURE
   //
   // BEGINNER-TIP: Start MMC (=Microsoft Management Console) and select "Add-in/remove Snapin"
   // from the "Console" menu. Now press "Add.." button. Select "Certificates" in the list and
   // press "Add" button. You have the choise to select "My user account" or "Computer account".
   // Then press "Finish" and "Close" and start exploring the installed certificates... 
   // Each store has a "Personal" section with is BTW represented by the letters "MY".
   // Also interessting is the "Trusted root" certificates, there you see all the Certificate
   // Issuer that you trust, there is quite a lot and sometimes it's a good idea to delete
   // all of them and only add the one you need or really trust, for security resasons.
   //

   // Open private certificate store of current user

   X509CertificateStore store = 
               X509CertificateStore.CurrentUserStore( X509CertificateStore.MyStore );
   store.OpenRead();

   // Read e.g. the first two certificate
   X509Certificate sender = (X509Certificate)store.Certificates[0];
   X509Certificate receiver = (X509Certificate)store.Certificates[1];

   // Let's see who we are dealing with... - ps: not nessesary for the following code
   string sender_serial = sender.GetName();
   string receiver_serial = receiver.GetName();


   //
   // SENDER-SIDE CODE
   //

   // SENDER-SIDE: Extract own private keys and receiver's public key

   RSAParameters sender_private = sender.Key.ExportParameters( true );
   RSAParameters receiver_public = receiver.Key.ExportParameters( false );

   // SENDER-SIDE: Asymmetric encryption with receivers's public key
   RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
   rsa.ImportParameters( receiver_public ); 
   byte[] cleartext = ASCIIEncoding.ASCII.GetBytes("test");
   byte[] cipher = rsa.Encrypt( cleartext, false );
   
   // SENDER-SIDE: Sign the cipher with own private key
   rsa = new RSACryptoServiceProvider();
   rsa.ImportParameters( sender_private );
   byte[] signature = rsa.SignData( cipher, new SHA1CryptoServiceProvider() );

   //
   // TODO: TRANSFER DATA OVER UNSECURE CHANNEL...
   //

   // RECEIVER-SIDE: Get own private key and sender's public key

   RSAParameters receiver_private = receiver.Key.ExportParameters( true );
   RSAParameters sender_public = sender.Key.ExportParameters( false );


   // RECEIVER-SIDE: Verify signature with sender's public key
   //
   // Note: You are ONLY verifying the signature and NOT verifying the Certificate!
   // It's corresponding to the CAPICOM call SignedData.Verify( CAPICOM_VERIFY_SIGNATURE_ONLY )
   // I did not yet find out how we can use the .NET library to verify the Certificate
   // against the issuer-chain. If someone knows how to do this, and not using interop
   // and the SignedData.Verify( CAPICOM_VERIFY_SIGNATURE_AND_CERTIFICATE ), I would be
   // very, very, very happy - because this is a requirement in the software I'm developing
   // currently and if we can't do that I have to do CAPI-interop :-(
   // At the moment I think that there is no simple function call for this and this s***s.
   // Maybe it's possible to walk throw the chain-of-issuers and validate the fingerprint
   // this the public key of the issuer. But I don't know enough about that....
   // ANY HELP TO THIS POINT IS MORE THAN WELCOME
   //

   rsa = new RSACryptoServiceProvider();
   rsa.ImportParameters( sender_public );
   if( rsa.VerifyData( cipher, new SHA1CryptoServiceProvider(), signature ) )
   {
      // RECEIVER-SIDE: Asmymetirc decryption with own private key
      rsa.ImportParameters( receiver_private );
      byte[] cleartext_after_decription = rsa.Decrypt( cipher, false );

      // Check result
      Debug.Assert( ASCIIEncoding.ASCII.GetString( cleartext ) ==
         ASCIIEncoding.ASCII.GetString( cleartext_after_decription ),
         "Ups, the cleartext input is not equal the cleartext output..." );
   }
   else
      Debug.Assert( false, "Ups, check signature failed!" );
}
catch( Exception e )
{

   // NOTE: the following exception, that may occure during 'ExportParameters( true )'
   //
   //   System.Security.Cryptography.CryptographicException
   //   "Key information could not be exported from the cryptographic service 
   //    provider (CSP) for this implementation." }"
   // 
   // Can have one of the following reasons:
   // + The certificate was NOT imported with the flag "Mark the private key as exportable"
   // + The type "SSL Server Authentication(40)" and is in a CurrentUser store and not in
   //   the LocalComputer store. See certificate details in the MMC under "NetscapeCertType".
   //   IMHO: This reason is very wicked and I don't understand it!!


   Debug.Assert( false, e.ToString() );
}

Note: The X509Certificate class provides the function ExportParameters and the boolean parameter defines if the private key has to be submitted as well.

A quick note

Favorite person names for encryption examples are Alice, Bob and mean Steve. If you like to see how they are doing in .NET, search your MSDN examples for the excellent example file called PublicKey.cs!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Manuel Permuy
Web Developer
Switzerland Switzerland
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionwhat is the difference between signing and encryption in rsa?memberMember 151309928 Oct '09 - 2:45 
hi,
 
i'm doing a comparison of performance between ECC and RSA ,
i used ECDsaCng class for ECC,i used the SignData(),verifyData() methods.
i used RSACryptoServiceProvider class for RSA,using signData(),VerifyData() methods also.
 
but the signing of data is including the compute of hash,and i want to do the comparsion
between the tow algorithms as encryption methods.
so the signing and verifying of data times between the tow algorithms will not be accurate.
 
and i noticed there are Encrypt(),Decrypt() methods in RSACryptoServiceProvider class
but no such methods in ECDsa class,
 
so the question is :how can i use ECC as encryption method,like to encrypt a message by the
public key and decrypt it by the private or encrypt it bey private and decrypt by public?
 
another question is :how can i use RSAcng class because i didn't find it in
System.Security.Cryptography namespace,and i am using VS 2008.
here is some info about this class in this link.
 
http://clrsecurity.codeplex.com/wikipage?title=Security.Cryptography.RSACng
 

 
thanks alot
GeneralIt is giving "Key not valid in use for specified state" Errormemberdhanashekar28 Oct '05 - 1:07 
In the line
rsa.Encrypt( cleartext, false );
 
It is giving error
"Key not valid in use for specified state"
 
What may be reason?
 
Thanks and regards
dhanasekar

Generalusing wse 2.0 or 1.0memberFPARRA812 Sep '05 - 13:17 

that one needs for the example code it works on wse 2.0 or it is better to use the version 1.0
 
HELLO
GeneralCode cannot work in WSE 2.0memberfrustrated4 Jan '05 - 12:59 
I've been trying for the better part of a day to make this code work using VS.NET 2003, and WSE 2.0, SP2, only to keep batting my head against the error message "Export of private parameters is not supported"
 
I finally broke out Reflector, and pulled apart the ExportParameters method on the RSACryptoServiceProvider that comes with WSE 2.0.
 
That code has the following in it (cut and pasted from Reflector's C# output window):
 
if (includePrivateParameters)
{
if (this._keyContents == X509KeyContainerContents.PublicOnly)
{
throw new InvalidOperationException("Private Key is not available");
}
throw new NotSupportedException("Export of private parameters is not supported");
}
 
Given this, there is no way the code in this project will ever work, as WSE 2.0 is activly preventing the export of private parameters from certificate files - regardless of security, availability, or anything else.
 
Ugh.
 
--
Chris Mullins
GeneralRe: Code cannot work in WSE 2.0memberdcoolidge2 Aug '05 - 9:37 
Look at my comment below. (wsdk becomes wse)
QuestionCryptography into Windows Service ?memberPattt9 Dec '04 - 7:40 
Well, I will try to explain my problem as simple as possible:
 
I have a Windows Service that receives Documents(files), Digitaly Sign them and return the signature. The Signature is computed using a SmartCard Key (Hardware).
 
So, in the Service, I select the CSP (Schlumberger Cryptographic Service Provider) and the container name I need.
 
- It works fine while running this Service as Local System Account. Roll eyes | :rolleyes:
 
For several "good reasons" (client needs), this service must be run under a Local Administrator account.
 
- Doing so, I am able to verify the signature, BUT not Signing. OMG | :OMG: (This also means using the public Key works, using the private key doesnt...) (signature works in this config on XP Roll eyes | :rolleyes: , not on Windows Server 2000/2003 OMG | :OMG: )
 
- Converting this service to a normal application and running it while logged with the same Local Administrator account ->> it works. Roll eyes | :rolleyes:
 

So my question is: What should I do to have this Service working with Admin on a WinServer2003 ??
 
I am bit lost. If someone could help, would be great.. Thanks Roll eyes | :rolleyes:
 

AnswerRe: Cryptography into Windows Service ?memberjlandheer18 Jun '05 - 15:28 
The Windows Service does not have an profile loaded, therefore the encryption rotines (RSA, etc) do not work. Assign the service a user account and make sure the profile get's loaded. (See for an example of all this the MSDN library Data Protection Api sample)
 
Regards,
 

 
Jeroen.
AnswerRe: Cryptography into Windows Service ?memberAnouphab8 Dec '06 - 1:49 
I have the same problem, do you have solutions ?
Questionhow to remove a private key using CAPICOMmemberchenkaijiang@yahoo.com7 Dec '04 - 2:42 
Hi, I'm using Capicom 2.0. I need to remove a certificate from a store, including its private/public key entirely, so that this computer will no longer has the private key -- it is necessary, for example, you import a .pfx in some machine and you want to clear the info.
 
I first let the user to choose the certificate and then
1) get the private key and remove it because from MSDN, the IStore.Remove method requires that you first remove the associate private key:
IPrivateKeyPtr spPrivateKey = spCert->PrivateKey;
spPrivateKey->Delete();
2) call IStore's method to remove the selected certificate.
spStore->Remove(spCert);
 
Then I can't see the private key in the store.
 
But the problem is that: I found the private key actually still exists!
I prove this by:
1) import a .cer file (certificate that has only public key) corresponding to the private key that I just remove by the above method;
2) de-envelop some data that was enveloped by the certificate I just removed -- it can still de-envelop it, even after I restart my PC!
 
Could you told me how to remove the private key entirely from a specified computer?
 
Thanks a lots!
 

GeneralUsing more secure hash algorithmmembergceaser14 Oct '04 - 4:16 
In the example provided, the code is using SHA1 - I need to use a more robust hashing algorithm such as SHA256 or higher. However, everytime I try to pass in anything other than an SHA1 object to the signdata function, I receive an error message stating the OID is not known. Any suggestions?
GeneralProblem signing a serilized object using CAPICOM.SignedDatamemberEscroto5 Aug '04 - 23:54 
WTF | :WTF: Hello,
i am developing a web service which needs to sign serialized objects using CAPICOM.SignedData. Once i sign the object (serialized) i got from the CAPICOM.SignedData.Sign() method a string containing a PKCS#7 structure wich i send to the client.
 
In the client side i build a new CAPICOM.SignedData object to use its Verify method in order to get the content of the PKCS#7 structure (and with verifications aims). Since now it is impossible to deserialized the object.
 
Please help me!Confused | :confused:
 

GeneralRe: Problem signing a serilized object using CAPICOM.SignedDatamemberManuel Permuy6 Aug '04 - 13:10 
What's the error message (and number 08x????), when you call Veryfy?
 
To get to the source of the problem, try this:
--> Does it work when Can you call Veryfy()immediatley after Sign() --> If Yes, then the transport corrups the data...
 

GeneralRe: Problem signing a serilized object using CAPICOM.SignedDatamemberEscroto6 Aug '04 - 21:28 
In the server side, if i call Verify() inmediately after Sign() everithing goes all right. When the data arrive to the client and the verification is going to be done the exception System.IO.FileNotFoundException is thrown. Maybe the data are corrupted in the transport but o don´t think so because i can extract the certificates from the PKCS#7 structure.
GeneralRe: Problem signing a serilized object using CAPICOM.SignedDatamemberManuel Permuy9 Aug '04 - 3:26 
Might be the cretificates needed (private receiver or the one of the certificate issuer!) is not installed in the Windows Certificate Store (in the right place)...

Generalx509certficatestorememberLucia Melotti22 Apr '04 - 2:33 
HI!
I read your exemples in this web page.
I have to get the server'certificate from the CA store, and I would like to retrieve the public Key, I wrote:
 
x509store = x509store.CurrentUserStore("CA")
x509store.OpenRead()
x509cert = x509store.Certificates(0)
server_public = x509cert.Key.ExportParameters(False)
 
the problem is that in the server certiicate (x509cert)there are not informatin about the public key. The last instruction return error!!
Please cuold you help me?!?!?

 
Lucia Melotti
GeneralCAPICOM+CDOmemberrayback_29 Dec '03 - 7:13 
I am no expert in cryptography , but I had to do the digital signing of emails for some purpose I wrote the code below which constructed message usind CDO and then signed data to be sent with CAPICOM and then send teh data. Well the problem is : when I send email using code below it says "Message has been tampered with" , though there's no such thing of course ( at least while trying it). I guess I am doing something wrong with conversions but cant be sure, except that error message all other things work ok, mean certificate is verified against chain and etc.. but as I said the digitally signed message I send seems to be corrupted.If anyone can help I will be very pleased.
   Ur sincerely Ray
 
Here is the code
//***************************************************************************
 
CDO.MessageClass a = new CDO.MessageClass();
CDO.IBodyPart ibp;
CDO.IBodyPart ibp2;         
ADODB.Fields flds;
    
a.To = tbTo.Text ;
a.From = "someone@eomewhere.com";
a.Subject = tbKonu.Text.Trim();
 

a.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value   = CdoSendUsing.cdoSendUsingPort;
 
a.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value   = "MAILSERVERNAME";
a.Configuration.Fields.Update();
 
ibp = a;
flds = ibp.Fields;
a.MimeFormatted = true;
 
flds["urn:schemas:mailheader:Content-Type"].Value = "multipart/signed; protocol=application/x-pkcs7-signature; micalg=SHA1";
flds["urn:schemas:mailheader:thread-index"].Value = "";
flds["urn:schemas:mailheader:thread-topic"].Value = "";
flds["urn:schemas:mailheader:priority"].Value = "";
flds["urn:schemas:mailheader:importance"].Value = "";
flds["urn:schemas:mailheader:content-class"].Value = "";
 

flds["urn:schemas:mailheader:Content-Language"].Value ="tr";
flds["urn:schemas:mailheader:charset"].Value ="Cp1254";
 

flds.Update();
    
 
// Setup the first body part; this is the header
// plus the file contents.
 
ibp2 = a.AddBodyPart(1);
flds = ibp2.Fields;
 
flds["urn:schemas:httpmail:content-media-type"].Value   = "text/plain";
flds["urn:schemas:mailheader:content-type"].Value = "text/plain; charset=UTF-8";
flds["urn:schemas:mailheader:content-class"].Value   = "urn:content-classes:message";
flds["urn:schemas:mailheader:content-transfer-encoding"].Value   = "7bit";
flds.Update();
 
ADODB.Stream stm;
string strbase64;
 
string msgtosign = tbMAIL.Text;
stm = ibp2.GetDecodedContentStream();
stm.Type = ADODB.StreamTypeEnum.adTypeText;
stm.WriteText(msgtosign, ADODB.StreamWriteEnum.adWriteChar);
 
stm.Flush() ;
 
CAPICOM.StoreClass d1 = new CAPICOM.StoreClass();
CAPICOM.Certificate cert;
cert = null;
 

d1.IStore_Open(CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE,"MY",CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_READ_ONLY);
 
foreach(CAPICOM.Certificate   ff in d1.Certificates)
{
     list1.Items.Add(ff.GetInfo(CAPICOM_CERT_INFO_TYPE.CAPICOM_CERT_INFO_SUBJECT_EMAIL_NAME ));
 
     cert = ff;
}
 
CAPICOM.SignerClass osigner = new SignerClass();
CAPICOM.AttributeClass oattr = new AttributeClass();
 
osigner.Certificate = cert;
 
oattr.Name = CAPICOM_ATTRIBUTE.CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME ;
oattr.Value = DateTime.Now;
 
osigner.AuthenticatedAttributes.Add(oattr);
 
CAPICOM.SignedDataClass osigneddata = new SignedDataClass();
osigneddata.Content = ibp2.GetStream().ReadText(ibp2.GetStream().Size);
 
strbase64 = osigneddata.Sign(osigner,true, CAPICOM_ENCODING_TYPE.CAPICOM_ENCODE_BASE64);
 
//verifying certificate!!!!! IS IT OK TO USE IT LIKE THIS
try
{
     osigneddata.Verify(strbase64, true,CAPICOM_SIGNED_DATA_VERIFY_FLAG.CAPICOM_VERIFY_SIGNATURE_AND_CERTIFICATE);
}
catch(System.Exception e1)
{
     Response.Write(e1.ToString());
     Response.Write("\n");
     Response.Write("Sertifika bilgileri Eksik veya Sertifika Bulunamadı");
}
 
//CAPICOM
 
ibp2 = a.AddBodyPart(2);
flds = ibp2.Fields;
 
flds["urn:schemas:mailheader:Content-Type"].Value   = "application/x-pkcs7-signature; Name = smime.p7s";
flds["urn:schemas:mailheader:Content-Transfer-Encoding"].Value   = "base64";
flds["urn:schemas:mailheader:content-Disposition"].Value   = "attachment; FileName = smime.p7s";
flds["urn:schemas:mailheader:content-Description"].Value   = "S/MIME Cryptographic Signature";
flds.Update();
 

stm = ibp2.GetEncodedContentStream();
stm.Type = ADODB.StreamTypeEnum.adTypeText;
stm.WriteText(strbase64,ADODB.StreamWriteEnum.stWriteLine);
stm.Flush();    
 

a.Send();
 
//***************************************************************************

GeneralRe: CAPICOM+CDOmemberrayback_223 Dec '03 - 23:17 
Ok I have solved the problem that I sketched aove, the problem was with encoding. Now I can sign and send messages, but I cant send the Signed(message+attachment) , that is text and attachment I want to sign , but it gives me "the message has been trampered with" staff, so tell me what am I to do?
GeneralRe: CAPICOM+CDOsussgoayeh21 Apr '05 - 16:19 

I tried this code , either,
 
when I open the mail , It's told me:
 
" The Mail have changed "
 
what happens ? The source mail as follows:
 
charset: big5
From: "Me"
To: "You"
Subject: Here is a signed message
MIME-Version: 1.0
Content-Type: multipart/signed;
protocol="application/x-pkcs7-signature";
micalg=SHA1;
boundary="----=_NextPart_000_0005_01C54724.55C4C200"
Content-Transfer-Encoding: 7bit
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.3790.224
 
This is a multi-part message in MIME format.
 
------=_NextPart_000_0005_01C54724.55C4C200
Content-Class: urn:content-classes:message
Content-Type: text/plain;
charset="UTF-8"
Content-Transfer-Encoding: 8bit
 
aaaaaa?皜祈岫aaaaaaaaa
------=_NextPart_000_0005_01C54724.55C4C200
Content-Disposition: attachment;
filename="smime.p7s"
Content-Description: S/MIME Cryptographic Signature
Content-Type: application/x-pkcs7-signature;
name="smime.p7s"
Content-Transfer-Encoding: base64
 
嚜燐IIJJQYJKoZIhvcNAQcCoIIJFjCCCRICAQExCzAJBgUrDgMCGgUAMAsGCSqGSIb3
DQEHAaCCB3kwggd1MIIGXaADAgECAgobM/KUAAAAAAAFMA0GCSqGSIb3DQEBBQUA
.............................................................much
Yq6jn+hyopSqGCQbJ46nJzT7tKWe+U+3XdCQww8F+hb523KEGWHpnn0GXkDDjFtQ
DdGx7VSGk77BdUrlJiFtJ2wG7QwB1++9aUXG9GgW6jq5/G420mE56W4=
 
------=_NextPart_000_0005_01C54724.55C4C20
 


GeneralRe: CAPCIOM+CDO SendSignedMailmemberrayback_221 Apr '05 - 21:19 
Hi friend .I faced the same problem ,I remember struggling with line endings for a long time (it seemed that I put one extra line ending Smile | :) ).
I send here the modified code of what I wrote before and its code (at least work here ) hope it helps.
Sincerely Ray

Const cdoSendUsingPickup = 1
Const cdoSendUsingPort = 2
 
Const cdoBasic = 1
 
const CAPICOM_STORE_OPEN_READ_ONLY = 0
const CAPICOM_CURRENT_USER_STORE = 2
const CAPICOM_CERTIFICATE_FIND_SHA1_HASH = 0
const CAPICOM_CERTIFICATE_FIND_EXTENDED_PROPERTY = 6
const CAPICOM_CERTIFICATE_FIND_TIME_VALID = 9
const CAPICOM_CERTIFICATE_FIND_KEY_USAGE = 12
const CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME = 0
const CAPICOM_INFO_SUBJECT_SIMPLE_NAME = 0
const CAPICOM_CERT_INFO_SUBJECT_EMAIL_NAME = 2
const CAPICOM_ENCODE_BASE64 = 0
const CAPICOM_ENCODE_BINARY = 1
const CAPICOM_E_CANCELLED = -2138568446
const CERT_KEY_SPEC_PROP_ID = 6
 
Const vbFromUnicode = 128
Const vbUnicode = 64

Const cdoIMessage = "IMessage"
'*****************************************************************************************
'*********** Send Signed email Message **************************
'***********Attachments if any are given as comma separated paths (physical paths of the file)**
'*****************************************************************************************
Public Function SendSignedMail(ByVal fromstr, ByVal tostr , ByVal subjectstr , ByVal bodystr , ByVal Attchmnt)

Set oSignedMsg = CreateObject("CDO.Message")
Set oSignedData = CreateObject("CAPICOM.SignedData")
Set oUtilities = CreateObject("CAPICOM.Utilities")
Set oAttribute = CreateObject("CAPICOM.Attribute")
set oStore = CreateObject("CAPICOM.Store")
set oSigner = CreateObject("CAPICOM.Signer")
set oReciepents = CreateObject("CAPICOM.Certificates")
Dim szNames
 

' select the signer certificate
oStore.Open CAPICOM_CURRENT_USER_STORE, "My", CAPICOM_STORE_OPEN_READ_ONLY
Set cSignerCertificates = oStore.Certificates

Select Case cSignerCertificates.Count
Case 0
MsgBox "No certificate found"
Exit Function
Case 1
oSigner.Certificate = cSignerCertificates(1)
Case Else
Set cSignerCertificates = cSignerCertificates.Select("Certificates", "Select certificate for signing")
If (cSignerCertificates.Count = 0) Then
msgbox "Error : Certificate selection canceled"
Exit Function
End If
oSigner.Certificate = cSignerCertificates(1)
End Select
 
'assign certificate chosen by user to object for signing
SelectCertificate = oSigner.Certificate.GetInfo(CAPICOM_CERT_INFO_SUBJECT_EMAIL_NAME)

'set the signing time in UTC time
oAttribute.Name = CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME
oAttribute.Value = oUtilities.LocalTimeToUTCTime(Now)



oSigner.AuthenticatedAttributes.Add oAttribute

'REGION ATTACHMENTS

'if there are no attachments

If Len(Trim(Attchmnt)) = 0 Then
Set oBodyPart = oSignedMsg.BodyPart.AddBodyPart
Set cFields = oBodyPart.Fields
cFields.Item("urn:schemas:mailheader:content-type") = "text/html"
cFields.Update

Set oStream = oBodyPart.GetDecodedContentStream
oStream.WriteText bodystr
oStream.Flush
End If

'if there are attachments

If Len(Trim(Attchmnt)) <> 0 Then

'add text part
Set oBodyPart = oSignedMsg.BodyPart.AddBodyPart
Set cFields = oBodyPart.Fields
cFields.Item("urn:schemas:mailheader:content-type").Value = "multipart/mixed;boundary=MIXEDBOUNDARY"
cFields.Update

Set oBodyPart = oSignedMsg.BodyPart.BodyParts(1).AddBodyPart
Set cFields = oBodyPart.Fields
cFields.Item("urn:schemas:mailheader:content-type") = "text/html"
cFields.Update

Set oStream = oBodyPart.GetDecodedContentStream
oStream.WriteText bodystr
oStream.Flush

'add attachments , the paths to attached files are separated by comma
Dim ekler
Dim ekcikler
Dim i
ekler = Split(Attchmnt, ",")

'replace \ character with /
For i = 0 To UBound(ekler)
ekcikler = Split(ekler(i), "\")
ekler(i) = Join(ekcikler, "/")
Next

For i = 0 To UBound(ekler)
Set oBodyPart = oSignedMsg.BodyPart.BodyParts(1).AddBodyPart
Set cFields = oBodyPart.Fields
cFields.Item("urn:schemas:mailheader:content-type").Value = "application/octet-stream" & vbCrLf & "Name = """ & ekler(i) & """"
cFields.Item("urn:schemas:mailheader:content-transfer-encoding").Value = "base64"
cFields.Item("urn:schemas:mailheader:content-disposition").Value = "attachment;" & vbCrLf & "FileName=""" & ekler(i) & """"
cFields.Update

Set oStream = oBodyPart.GetDecodedContentStream
oStream.LoadFromFile ekler(i)
oStream.Flush
Next

End If


'ENDREGION ATTACHMENT

ss = oSignedMsg.BodyPart.BodyParts(1).GetStream.ReadText
ss = Replace(ss, "This is a multi-part message in MIME format." + vbCrLf, "")



oSignedData.Content = StrConv(ss, 128)
 

' sign the content
dim szSignature
szSignature = oSignedData.Sign(oSigner, True, CAPICOM_ENCODE_BINARY)
byteSignature = oUtilities.BinaryStringToByteArray(szSignature)

' Attach the signature and let CDO base64 encode it
Set oBodyPart = oSignedMsg.BodyPart.AddBodyPart
Set cFields = oBodyPart.Fields
oBodyPart.Fields.Item("urn:schemas:mailheader:content-type").Value = "application/x-pkcs7-signature" & vbCrLf & "Name = ""smime.p7s"""
oBodyPart.Fields.Item("urn:schemas:mailheader:content-transfer-encoding").Value = "base64"
oBodyPart.Fields.Item("urn:schemas:mailheader:content-disposition").Value = "attachment;" & vbCrLf & "FileName=""smime.p7s"""
cFields.Update

Set oStream = oBodyPart.GetDecodedContentStream
oStream.Type = 1
oStream.Write(byteSignature)
oStream.Flush

' Set the messages content type, this needs to be done last to ensure it is not changed when we add the BodyParts
oSignedMsg.Fields.Item("urn:schemas:mailheader:content-type").Value = "multipart/signed;" & vbCrLf & "protocol=""application/x-pkcs7-signature"";" & vbCrLf & "micalg=SHA1;boundary=SIGNEDBOUNDARY"
oSignedMsg.Fields.Update
 
' Signing Was sucessfull
SignMessage = True

' set the from field based off of the selected certificate
oSignedMsg.From = oSigner.Certificate.GetInfo(CAPICOM_CERT_INFO_SUBJECT_EMAIL_NAME)
oSignedMsg.To = tostr
oSignedMsg.Subject = subjectstr
oSignedMsg.Fields.Update

'set sending parameters
oSignedMsg.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing").Value = cdoSendUsingPort
oSignedMsg.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver").Value = "MAILSERVERADRESS"
oSignedMsg.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport").Value = 25
oSignedMsg.Configuration.Fields.Update

'send message
oSignedMsg.Send
 
msgbox "Message succesfully sent"

End Function
 

'*****************************************************************************************
'*********** UNICODE to ASCII and BACK **************
'****************************************************************************
Public function StrConv(ByRef stringData, ByRef conversion)
Dim Stream
Set Stream = CreateObject("ADODB.Stream")
 
Const UnicodeCharaset = "Windows-1252"
Const BinaryCharset = "X-ANSI"
Select Case conversion
Case vbFromUnicode
' UNICODDAN ASCII'ye CEVIRME
With Stream
.Charset = UnicodeCharaset
.Type = 2
.Open
.WriteText stringData
.Position = 0
.Charset = BinaryCharset
.Type = 1
StrConv = MidB(.Read, 1)
End With

Case vbUnicode
' ASCII DEN UNICODA CEVIRME
Dim Length
Dim Buffer

if TypeName(stringData) = "Null" Then
CStrU = ""
Exit function
End if

stringData = MidB(stringData, 1)

Length = LenB(stringData)
Dim Rs
Set Rs = CreateObject("ADODB.Recordset")
Call Rs.Fields.Append("BinaryData", adLongVarBinary, Length)
Rs.Open
Rs.AddNew
Rs.Fields("BinaryData").AppendChunk(stringData & ChrB(0))
Rs.Update
Buffer = Rs.Fields("BinaryData").GetChunk(Length)
Rs.Close
Set Rs = Nothing
With Stream
.Charset = BinaryCharset
.Type = 1
.Open
Call .Write(Buffer)
.Position = 0
.Type = 2
.Charset = UnicodeCharaset
End With

StrConv = Stream.ReadText(-1)
End Select
Stream.Close
Set Stream = Nothing
End function

GeneralRe: CAPCIOM+CDO SendSignedMailmemberNoradYeh26 Apr '05 - 22:12 
Hi, Sir,
 
I tried your code several days,
 
but the function 'StrConv' is VB6's code,
 
I tried change it to vb.net, but failed....
 
could you help me if you have free time ...
 
Thank you very much !
GeneralRe: CAPCIOM+CDO SendSignedMailmemberrayback_226 Apr '05 - 22:26 
Hi.
 
Yes as u said the StrConv is the built in of VB 6.0 and it wont work for vbscript and vb.net (though in vb.net you have counterpart for that function doing the same thing).
I sent the vbscript version of the function too in the code I submitted previously (at the bottom of the page maybe u missed that). What it does is this : using the ADODB stream it converts the unicode characters to ascii and back. You should use that custom function in vbscript code because the built in StrConv is not available in vbscript (at least its how I know it to be)
 
Here I resent the function definition for StrConv
 
Const vbFromUnicode = 128
Const vbUnicode = 64
 
'*****************************************************************************************
'*********** From Unicode to ASCII and Back**************
'*****************************************************************************************
Public function StrConv(ByRef stringData, ByRef conversion)
Dim Stream
Set Stream = CreateObject("ADODB.Stream")
 
Const UnicodeCharaset = "Windows-1252"
Const BinaryCharset = "X-ANSI"
Select Case conversion
Case vbFromUnicode
' from unicode to ascii
With Stream
.Charset = UnicodeCharaset
.Type = 2
.Open
.WriteText stringData
.Position = 0
.Charset = BinaryCharset
.Type = 1
StrConv = MidB(.Read, 1)
End With

Case vbUnicode
' from ascii to unicode
Dim Length
Dim Buffer

if TypeName(stringData) = "Null" Then
CStrU = ""
Exit function
End if

stringData = MidB(stringData, 1)

Length = LenB(stringData)
Dim Rs
Set Rs = CreateObject("ADODB.Recordset")
Call Rs.Fields.Append("BinaryData", adLongVarBinary, Length)
Rs.Open
Rs.AddNew
Rs.Fields("BinaryData").AppendChunk(stringData & ChrB(0))
Rs.Update
Buffer = Rs.Fields("BinaryData").GetChunk(Length)
Rs.Close
Set Rs = Nothing
With Stream
.Charset = BinaryCharset
.Type = 1
.Open
Call .Write(Buffer)
.Position = 0
.Type = 2
.Charset = UnicodeCharaset
End With

StrConv = Stream.ReadText(-1)
End Select
Stream.Close
Set Stream = Nothing
End function
 

Sincerely Ray
 

P.S: also u can convert the code to vb.net but, theres a big but in that not technically but in principle. If you are writing a web application the certificate you are trying to access is on client machine and not server. So the only solution I saw is to write a script for it, because theres no way of bringing the certificate (wth the private key) to server (its not right thing to do ). So I guess if u are writing the web application you should do it in script.
 

GeneralRe: CAPCIOM+CDO SendSignedMailmemberabygm2 Nov '07 - 2:15 
Hi Ray..,
 
I am facing error when signing mail with embedded image. To embed image, it need to be a Part of the main body. If you put it as a Part of a Subpart (I mean, it should be oSignedMsg.BodyPart.AddBodyPart and not oSignedMsg.BodyPart.BodyParts(1).AddBodyPart) it will embed as well as show as an attachment.
 
Issue is, if we put image as part of a subpart signing is fine; Outlook validates it. Problem is it will embed the image as well as show it as an attachment. If we put it as part of body, signing fails; It is not recognised as a signed message.
 
Can you throw some light..?
 
Regards,
 
Aby.
Generaluse phone numbermembersmail belmokhtar19 Nov '03 - 1:51 
please i neede to this tips..
 
i neede how to communicate tow application (client-server)
by the phone number without using the internet
                                             thunks
QuestionWhich page is main source?memberStefan Pedersen3 Oct '03 - 11:07 
http://users.pandora.be/ahmadi/html/security.html[^]
 
This page is identical to your article and I wonder which page is to be considered the main source? There are no references on either to the other.
AnswerRe: Which page is main source?memberManuel Permuy5 Oct '03 - 7:03 
I'm the author of this article, so the other is a copy...
 
Some things changed and I quess it's about time to update this article anyway. Stay tuned Wink | ;-)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 10 Oct 2002
Article Copyright 2002 by Manuel Permuy
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid