Archive

Archive for January, 2010

Adding captcha “Recaptcha Umbraco Blog”

22/01/2010 Leave a comment

So after i my self got spammed by a lot of robots on my blog i browsed the internet to find an easy way to add captcha for the comment part of my blog.

So i found the easiest way to do was using recaptcha, which can be found here recaptcha.net. So before we start head over there and create an account.

Step 1:

Create recaptcha.net account  recaptcha.net

Step 2:

Download the .Net package containing the recaptcha.dll

Step 3:

Download from you site frmBlogComment.ascx placed in siteroot/usercontrols

Step4:

Edit frmBlogComment.ascx

add the following lines

These lines should be right after the “control tag” “<%@ Control …… %>”

Futher down you can now add the recaptcha usercontrol


<recaptcha:RecaptchaControl
 ID="recaptcha"
 runat="server"
 PublicKey=...
 PrivateKey=....
 />

ofcourse with your privatekey and publickey..

Step 5:

Upload recaptcha.dll to your webroot/bin

Upload the newly edited  frmBlogComment.ascx to you webroot/usercontrols/

And you should be all done and no more bots should spam your blog I hope.

This post is for them that dont want to recompile umbraco, it would be a much better solution to add an reference to the recaptcha.dll

Advertisements
Categories: .Net Tags: ,

Encrypting and signing Mail in .Net part 5/5 (Encrypting the content and sending the mail)

19/01/2010 4 comments

Final part in the serie c# encrypting mail.

So now we got the content build and signed. Now what is left to do i encrypting the content.

In this post we have a look at how the structure of the content should just before it is encrypted, and how to encrypt the content.

Link to part 1, part 2, part 3, part 4

To encrypt the content I will use the GetCert method that we did in part 4 of this series.

As with the signing part we will split this encryption into two bits. adding boundary to the content and encrypting part.

First the encrypting part:


public byte[] DoEncrypt(string message, X509Certificate2 encryptionCertificates)
{
byte[] messageBytes = Encoding.ASCII.GetBytes(message);

EnvelopedCms envelopedCms = new EnvelopedCms(new ContentInfo(messageBytes));

CmsRecipient recipients = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, encryptionCertificates);

envelopedCms.Encrypt(recipients);

return envelopedCms.Encode();
}

With this function done we can now ready the content for encryptions. We add a simple boundary to the content and specifies what type the innner boundary is of. Important that if you skipped the signing part that you change this accordingly to match the type of you content.

Here is the code for encrypting and sending the mail:


public void encrypt(string content)
{
MailMessage message = new System.Net.Mail.MailMessage();
string encryptedContentType = "application/x-pkcs7-mime; smime-type=enveloped-data; name=\"smime.p7m\"";
string signatureBoundry2 = "--PTBoundry=3";
StringBuilder fullUnencryptedMessageBuilder = new StringBuilder();
fullUnencryptedMessageBuilder.Append("Content-Type: ");
fullUnencryptedMessageBuilder.Append("multipart/signed; ");
fullUnencryptedMessageBuilder.Append(" boundary=\"");
fullUnencryptedMessageBuilder.Append(signatureBoundry2);
fullUnencryptedMessageBuilder.Append("\"; protocol=\"application/x-pkcs7-signature\"; micalg=SHA1; ");

fullUnencryptedMessageBuilder.Append("\r\n");
fullUnencryptedMessageBuilder.Append("Content-Transfer-Encoding: ");
fullUnencryptedMessageBuilder.Append(TransferEncoding.SevenBit);
fullUnencryptedMessageBuilder.Append("\r\n\r\n");
fullUnencryptedMessageBuilder.Append(content);

string fullUnencryptedMessage = fullUnencryptedMessageBuilder.ToString();

byte[] encryptedBytes = DoEncrypt(fullUnencryptedMessage, GetCert());

MemoryStream stream = new MemoryStream(encryptedBytes);
AlternateView view = new AlternateView(stream, "application/pkcs7-mime; smime-type=signed-data;name=smime.p7m");
message.AlternateViews.Add(view);
message.To.Add("youremail@yourdomain.com");

message.From = new MailAddress("someone@yourdomain.com");
message.Subject = "TEST";
SmtpClient smtp = new SmtpClient("smtp.yourdomain.com");
smtp.Send(message);

}

This function also sends out the mail you might wanna spilt this up to seperate methods. And do remember to give valide email adresses and a sane smtphost.

Now lets have a look at the result:

Yes there is a warning with the signature but rember in part 1 where did a selfsigned certificate this is the problem, but you cal always just accept the signature as trusted in your outlook.

Okay so how doesn’t the content that we build look like just before it is encrypted ?

If hightligthe the different steps we done in this series.

Also note the diffenrent boundary references from one part to underlaying content part.


Remember to change email smtp host and serial for certificat

Note you should implement all the explained methods in nice class’s that wraps all this functionality into one simple class. The code file you can download is constructed as a simple file so i would be easier to explain howto encrypt and sign emails. It is not intended to be used for production purposes.

Finished you now know ho to encrypt and sign mails with c#.

c# encrypting and signing mail

Categories: C# Tags: ,

Encrypting and signing Mail in .Net part 4/5 (Signing the content)

18/01/2010 1 comment

Okay so now we are done and have build the content of the mail. Now we need to sign it. If you dont want to sign the mail skip this part and jum straight to encrypting “which will be the next post”. I’ve found quite a few post on tje net on howto sign at encrypt mails but none of them worked for me. I’ve had to look at package and mail content to analyze how to to build the right content and signing part as well. For the signing part we off course need a certificate with access to the private key.

Link to part 1, part 2, part 3

NOTE AGAIN IF THE PROCESS RUNNING THE CODE DOESN’T HAVE ACCESS TO THE PRIVATE KEY YOU GET A KEYSET DOESN’T MATCH OR PRIVATE KEY COULD NOT BE FOUND ERROR WHEN TRYING TO SIGN THE MAIL.

See earlier post on howo to setup up security for certificates.

Now finaly to some code. First we gonna make a little helper method for signing the content. Also note that I use a simple helper function “GetCert()” all i does is returning the same certificate since i use the same certificate for signing and ecrypting. You should offcourse use the methode shown in part 2 of this series. My get cert is a like but just with an hardcode serial number. this should be replaced with the serial number for your certificate.

The little helper function:

public static X509Certificate2 GetCert()
{
//Sets up a new store to look for at certificat in.
X509Store localStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
localStore.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);

try
{
//NOTE FALSE IS ONLY USED FOR TESTS SHOULD BE CHANGED TO true

X509Certificate2Collection matches =
localStore.Certificates.Find(X509FindType.FindBySerialNumber, "a0 51 bf 0a bc 4a 11 8b 41 9d 56 47 92 b2 34 6c", false);
if (matches.Count > 0)
{
return matches[0];
}
else
{
return null;
}
}
finally
{
localStore.Close();
}

}

And here is how crypting part works. The signature calculation. Note that the function takes two certifactes one for signing the mail and the certificates used for encrypting the mail. Theese two could be the same. But you might have an certificat only for signing and the you need the extra one for encrypting the mail.

</pre>
public byte[] GetSignature(string message, X509Certificate2 signingCertificate, X509Certificate2 encryptionCertificate)
 {
 byte[] messageBytes = Encoding.ASCII.GetBytes(message);

SignedCms signedCms = new SignedCms(new ContentInfo(messageBytes), true);

CmsSigner cmsSigner = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signingCertificate);
 cmsSigner.IncludeOption = X509IncludeOption.WholeChain;

if (encryptionCertificate != null)
 {
 cmsSigner.Certificates.Add(encryptionCertificate);
 }

Pkcs9SigningTime signingTime = new Pkcs9SigningTime();
 cmsSigner.SignedAttributes.Add(signingTime);

signedCms.ComputeSignature(cmsSigner, false);

return signedCms.Encode();
 }

With this function we can start adding new boundary to the content so it will be correct signed. This part was nesscary for me  otherwise i could either encryot the mail or sign it not both. So before we sign the mail we add som new boundaries and finaly we gonna add the calculated signature. Again this function accept the content from we made in the laste post so as input you could give the method the result from “buildcontent()”. Againg note this is build in simple function so we can got a simple reference when we wnat to encrypt the content.

</pre>
public string signed(string Content)
 {
 string signatureBoundry = "--PTBoundry=2";
 string signatureBoundry2 = "--PTBoundry=3";
 StringBuilder fullUnsignedMessageBuilder = new StringBuilder();

fullUnsignedMessageBuilder.Append("Content-Type: ");
 fullUnsignedMessageBuilder.Append("multipart/mixed;");
 fullUnsignedMessageBuilder.Append(" boundary=\"");
 fullUnsignedMessageBuilder.Append(signatureBoundry);
 fullUnsignedMessageBuilder.Append("\"\r\n");
 fullUnsignedMessageBuilder.Append("Content-Transfer-Encoding: ");

fullUnsignedMessageBuilder.Append(TransferEncoding.SevenBit);
 fullUnsignedMessageBuilder.Append("\r\n");
 fullUnsignedMessageBuilder.Append(Content);

string fullUnsignedMessage = fullUnsignedMessageBuilder.ToString();

byte[] signature = GetSignature(fullUnsignedMessage, GetCert(), GetCert());

StringBuilder signedMessageBuilder = new StringBuilder();

signedMessageBuilder.Append("--");
 signedMessageBuilder.Append(signatureBoundry2);
 signedMessageBuilder.Append("\r\n");
 signedMessageBuilder.Append(fullUnsignedMessage);
 signedMessageBuilder.Append("\r\n");
 signedMessageBuilder.Append("--");
 signedMessageBuilder.Append(signatureBoundry2);
 signedMessageBuilder.Append("\r\n");
 signedMessageBuilder.Append("Content-Type: application/x-pkcs7-signature; name=\"smime.p7s\"\r\n");
 signedMessageBuilder.Append("Content-Transfer-Encoding: base64\r\n");
 signedMessageBuilder.Append("Content-Disposition: attachment; filename=\"smime.p7s\"\r\n\r\n");
 signedMessageBuilder.Append(Convert.ToBase64String(signature));
 signedMessageBuilder.Append("\r\n\r\n");

signedMessageBuilder.Append("--");
 signedMessageBuilder.Append(signatureBoundry2);
 signedMessageBuilder.Append("--\r\n");

return signedMessageBuilder.ToString();
 }

It is now posssible to return and signed message string ready to be encrypted by calling :

signed(buildcontent())

Do note the reference the tells we the content boundary start is different form the boundary for the signing part, and boundary for the signature is offcourse the same as for the signing boundary. So it is important to have acces to the different boundaries for between each steps. And when we want to encryp the content we also need the referencs for the signing boundary.

Okay with the content now signed we should be ready to encrypt the mail and send it see next post Where we also will look at how the final content should look just before it is send, This will also help one to build the mailcontent for your own purposes.

Now whe signed the mail.

Categories: C# Tags: ,

Encrypting and signing Mail in .Net part 3/5 (Building the content – with attachments)

16/01/2010 3 comments

Lets get startet with the real stuff on how to encrypt mail with c#

Now we have created the certificats and we have the methods for retrieving them. So before we can sign and encrypt the mail we need to prepare there content for security operations. When sending encrypted mail with attachment the content should be included as a part of the content. If add an attahcment to an email with  using the normal “System.net.mail – message.attachments.add() ” breaks the encryption. To overcome this the attachments are added to the maincontent of message but seprated with boundries.

Link to part 1, part 2

Since there are different ways to fetch filecontent and bodycontent i’ve have focused only on howto message data should be build, so there are left some work for you to do. Implementing functions for retrieving filecontent into byte[] fx.

To make the next couple of step easier to connecto to this one which is the backbone in encrypting the mail, I will make a simple builcontent() function that builds a simple text/plain mail and adds an attachment called snebar.jpg placed on the root of my c drive.

public string buildMessageContent()
{
string messageBoundry = "--PTBoundry=2";
StringBuilder message = new StringBuilder();
message.Append("\r\n");
message.Append("\r\n");
message.Append("--");
message.Append(messageBoundry + "\r\n");
message.Append("Content-Type: text/plain; charset=us-ascii\r\n");
//could use text/html as well here if you want a html message
message.Append("Content-Transfer-Encoding: ");
message.Append(TransferEncoding.QuotedPrintable);
message.Append("\r\n\r\n");
message.Append("TEST AF kryptering")//BODY TEXT GOES HERE

message.Append("\r\n");

//ADD file section
//could be filename or whatever
//foreach (string filename in attachments){
//Read file part implement your own
byte[] buff = null;
FileStream fs = new
FileStream("c:\\snebaer.jpg", FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
long numBytes = new FileInfo("c:\\snebaer.jpg").Length;
buff = br.ReadBytes((int)numBytes);
byte[] bytes = buff;
//Setup filecontent
String filecontent =
Convert.ToBase64String(bytes,Base64FormattingOptions.InsertLineBreaks);

message.Append("--");
message.Append(messageBoundry);
message.Append("\r\n");
message.Append("Content-Type: ");
message.Append("application/octet-stream;");
message.Append("name=c:\\snebaer.jpg");
message.Append("\r\n");
message.Append("Content-Transfer-Encoding: base64\r\n\r\n");
message.Append(filecontent);
message.Append("\r\n\r\n");
//} //END FILSECTION

message.Append("--");
message.Append(messageBoundry);
message.Append("--\r\n");
return message.ToString();
}<br>

Note that there isout comment foreach loop which could added if you need to add multiple attachments. I will also be a good idee to ad at method for building unique boundaries that could be used you can use Guid or what ever you like. I use theese static one so it easier to refence them in the next post. the string returned here is now readyto be signed. Look

Categories: C# Tags: ,

Encrypting and signing Mail in .Net part 2/5 (retrieving certificats)

13/01/2010 4 comments

Part two in the series of 5 on howto c# encrypt and sign mail

So in this post we will looking at howto fetch the security certs we installed in the last post. There are a few attributes you can use for this, but for now i’m gonna settle with the serial number for the certificate.

Link to post 1

The serial number can be found on the certificate it self so open up mmc and add a snap in for the local computer, if you forgot howto do this have a look in part 1 of series. Once you you found your recently installed certificate double click the cert and choose the fan details, click on serial number to allow you to see the entire key.

Okay now we got the serial number.
now we gonna fetch it out with through .Net


using System;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using System.Text;
<br>
/// Finds a certificates on Localmachines  local store based on its serial number
///
/// The serial number of the certificate to retrieve
/// The requested certificate, or null if the certificate is not found
public X509Certificate2 FindCertificateFromSerial(string serialNumber)
{
//Sets up a new store to look for at certificat in.
X509Store localStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
localStore.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);<br>

try
{
//NOTE FALSE IS ONLY USED FOR TESTS SHOULD BE CHANGED TO true<br>
X509Certificate2Collection matches = localStore.Certificates.Find(
X509FindType.FindBySerialNumber,
serialNumber,
false);
if (matches.Count > 0)
{
return matches[0];
}
else
{
return null;
}
}
finally
{
localStore.Close();
}

}


Note the false parameter passed to Certificates.Find this should be change to true on live system that certificate that has expired or a like, would also be returned. Also note you need a referencens to System.Security  so you can use the


using System.Security.Cryptography.Pkcs;

There are other possible ways to find the certifcate but i leave that to you find thefindtype that fits your purpose best.

Categories: C# Tags: ,

Encrypting and signing Mail in .Net part 1/5

12/01/2010 5 comments

So the following couple of blog post will be about encrypting mails with attachments.

Today we start with creating certificates for signing the mails and encrypting them.

For this to make sensse we need to certificates, one for signing and on for each reciever of the mail in this example there will be only one reciever. I will be using win 7 so all screenshots shown will be from win 7 .

First we create two certificates, we do this by opening the visual studio command prompt.

the first certificate we create will be the signing certificate using this line

makecert -n “CN=SigningCert” -ss -sr Currentuser -pe -r


This will create a selfsigned certificates where there privatekey can be exported.

next we will create the certificate for encrypting and decrypting the mail content.

makecert -n “CN=Encrypting” -ss -sr Currentuser -pe -r

NOTE: CERTIFICATS ARE ONLY VALID FOR TEST

Note i’ve tried installing the certificates on the localmachine but every time it fails, with a write error, and yes I have logged in as administrator.

So now we need to setup the certificates for localmachine open mmc.exe.

Now we add to snap-ins one for the currentuser and one for the localmachine and snap-in for both should be certificates.

Do this by File-> Add/remove Snap-in

When you are done with this step you should have one snap-in fo currentuser and one for localmachine see image below

Next we will export the two certificates, same procedure for both certificates so i will only do it for the signing certificate open the currentuser personal certificate find the signingcert “right mouse click choose copy”, next go to the Localcomputer ->personal-Certificates and choose paste. Volia you should now be able to se the certificate. in your iis-manger.

HERE starts one of the most important steps i’ve had and error one trying to signing mails with a cert where the .Net user doesn’t have acces to the private key.

Right click the certificate. choose  All task Manage Private Keys and give you .Net user full access. Or everyone for TEST ONLY.

The more correct way to do this step is on your current user right click your cert choose alltaks export and choose to export private key. This should work.

If this step is missing you will get the following error KEYSET DOES NOT EXIST OR CANNOT FIND PRIVATE KEY

Categories: C# Tags: ,