Spiga
Showing posts with label Code Snippets. Show all posts
Showing posts with label Code Snippets. Show all posts

Cryptographically Random Password Generator

Introduction

Creating a password is easy. However, creating a strong password is not easy. Most passwords are simple variations of dictionary words, often with random numbers at the end of them or are simple substitutions (1s for I's, the "@" symbol for A's, and so forth). The problem with this scheme is that it is easily guessable by sophisticated password-guessing software. Such software, such as that by Access Data, can crack open passwords that follow such simplistic patterns, even if those passwords include multiple intentionally misspelled words, random numbers, and other common patterns.
The Problem

The problem with passwords is that they are not random. They're based on predictable patterns. They're easy to remember and, consequently, easy to crack. Some passwords need not be complex. The complexity of the password should be commensurate with a) the possible attack vectors, and b) the value of the data or resource protected by that password. For example, ATM pins are 4-digit. But they're reasonably secure because they're not subject to brute force attacks.

So, when do you need to use non-trivial, random passwords? It's important to use such passwords when employing the use of encryption on data that can potentially be analyzed and where a brute force attack can be waged on the password protecting that data. AES-256 is meaningless if the password can be cracked in ten minutes.
The Solution

Use a cryptographically random password in cases where security is essential. The Cryptographically Random Password Generator provides such a service. How does it work? The first step is to get a cryptographically random 32-bit integer. There's a Random class provided by Microsoft in the System namespace (that you'll use), but the level of entropy (randomness) is minimal if you rely only on that class. Instead, you'll use the RNGCryptoServiceProvider namespace, provided in System.Security.Cryptography:

byte[] randomBytes = new byte[4];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
Int32 randomInt=BitConverter.ToInt32(randomBytes, 0);
return randomInt;

Good; you now have a 32-bit integer that is totally random. You safely can use this cryptographically random integer as a seed in the Random class. In fact, you'll generate a new random seed per iteration (per password character). Why? Because if you use the random value as the initial seed, the password entropy is still not cryptographically random. You've generated a random seed, but given that seed, the Random class's generated values are still pretty predictable. Hence, you generate a new seed every time you need a character, and Random uses that random seed.

So, why do you need Random if you have the RNGCryptoServiceProvider class? The answer is that you'll need to map a randomly generated value to an array. The array will hold a character set—a list of allowable characters in our password. By default, that list will include the letters a-z, A-Z, and also 0-9 and some special characters (ten of them). Hence, the list includes a total of 72 distinct characters. The main iteration loop that populates the final password string looks something like this:

for (int i = 0; i < len; i++)
{
// Get our cryptographically random 32-bit integer & use it
// as a seed in the Random class
// NOTE: The random value is generated PER ITERATION, meaning
// that the System.Random class is re-instantiated every
// iteration with a new, cryptographically random numeric seed.
int randInt32 = RandomInt32Value.GetRandomInt();
Random r = new Random(randInt32);

int nextInt=r.Next(possibleChars.Length);
char c = possibleChars[nextInt];
builder.Append(c);
}

The static method call to RandomInt32Value accomplishes the task of getting the random 32-bit integer because that class encapsulates the necessary calls to the RNGCryptoServiceProvider class. For utility's sake, the application provided includes the ability to set the password length and the set of possible characters, as in the screen shot below:

Finally, note that the application provides the capability of viewing the statistical frequency distribution of the generated password. Why would you need this? For testing sake, you could generate a 10,000 character password using the available characters (or, for simplicity, just certain characters, like 0-9). Theory suggests that, roughly speaking, the generated characters will have an equal chance of being selected in the final passphrase. For example, I generated a 10,000 character passphrase using the characters 0 through 9. The values selected were roughly equal in frequency (a good sign of randomness, meaning that the randomness algorithm does not show statistical favoritism).

Conclusion

Data that is meant to be secure and that relies on user-generated passwords to secure the data are at risk. You can use a secure password generation mechanism, like the Cryptographically Random Password Generator, to generate random passwords using a variable character set and a length of your choosing. Write your password down and put it in a secure location. Rest assured that if the medium that contains your data is lost, your data will nonetheless be secure because the encryption key will be impossible to break with today's technology (or even tomorrow's?).

Comments and feedback on this article and the application are welcome. If you have suggestions, please don't hesitate to let me know at your leisure.

About the Author

I am a software engineer based in Raleigh, NC. I have experience in C, C++, Java, C#, and other languages.

I am married and have a beautiful wife named Amanda. Absent of kids, we have three house cats.

In my spare time, I also write a blog on political topics and current events (www.gmgdesign.com/go).

Downloads

# RandPasswordGen_demo.zip - Executable
# RandPasswordGen_src.zip - Source code

Email Sending

Email Sending

This article will focus on following concept
* Simplest way of sending email
* Writing HTML Email
* Creating Email with attachment

Simplest Way of Sending Email
try

{

SmtpClient smtpMailObj = new SmtpClient();

//eg:localhost, 192.168.0.x, replace with your server name

smtpMailObj.Host = "myMailServer";

smtpMailObj.Send(txtFrom.Text, txtTo.Text, txtSubject.Text, txtComment.Text);

Response.Write("Your Message has been sent successfully");

}

catch (Exception ex)

{

Response.Write("Message Delivery Fails");

}

Sending Email with MailMessage Object
MailMessage Mail = new MailMessage();
MailAddress ma = new MailAddress(txtFrom.Text,txtName.Text);
Mail.From = ma;
Mail.To.Add(txtTo.Text);
Mail.Subject = txtSubject.Text;
Mail.Body = txtComment.Text;
try
{
SmtpClient smtpMailObj = new SmtpClient();
//eg:localhost, 192.168.0.x, replace with your server name
smtpMailObj.Host = "myMailServer";
smtpMailObj.Send(Mail);
Response.Write("Your Message has been sent successfully");
}
catch (Exception ex)
{
Response.Write("Message Delivery Fails");
}

Sending Email with CC and BCC options
MailMessage Mail = new MailMessage();
MailAddress ma = new MailAddress(txtFrom.Text,txtName.Text);
Mail.From = ma;
Mail.To.Add(txtTo.Text);
if(txtCC.Text.Trim().Length != 0)
Mail.CC.Add(txtCC.Text);
if(txtBCC.Text.Trim().Length != 0)
Mail.Bcc.Add(txtBCC.Text);
Mail.Subject = txtSubject.Text;
Mail.Body = txtComment.Text;
try
{
SmtpClient smtpMailObj = new SmtpClient();
//eg:localhost, 192.168.0.x, replace with your server name
smtpMailObj.Host = "myMailServer";
smtpMailObj.Send(Mail);
Response.Write("Your Message has been sent successfully");
}
catch (Exception ex)
{
Response.Write("Message Delivery Fails");
}

Sending Email with Reply-To options
MailMessage Mail = new MailMessage();
MailAddress ma = new MailAddress(txtFrom.Text,txtName.Text);
Mail.From = ma;
Mail.To.Add(txtTo.Text);
if(txtCC.Text.Trim().Length != 0)
Mail.CC.Add(txtCC.Text);
if(txtBCC.Text.Trim().Length != 0)
Mail.Bcc.Add(txtBCC.Text);
Mail.Subject = txtSubject.Text;
Mail.Body = txtComment.Text;
//Setting Reply address.
if (txtReplyTo.Text.Trim().Length != 0)
{
Mail.Headers.Add("Reply-To", txtReplyTo.Text);
}
else
{
Mail.Headers.Add("Reply-To", txtFrom.Text);
}
try
{
SmtpClient smtpMailObj = new SmtpClient();
//eg:localhost, 192.168.0.x, replace with your server name
smtpMailObj.Host = "myMailServer";
smtpMailObj.Send(Mail);
Response.Write("Your Message has been sent successfully");
}
catch (Exception ex)
{
Response.Write("Message Delivery Fails");
}

Sending Email with HTML output options
MailMessage Mail = new MailMessage();
MailAddress ma = new MailAddress(txtFrom.Text,txtName.Text);
Mail.From = ma;
Mail.To.Add(txtTo.Text);
if(txtCC.Text.Trim().Length != 0)
Mail.CC.Add(txtCC.Text);
if(txtBCC.Text.Trim().Length != 0)
Mail.Bcc.Add(txtBCC.Text);
Mail.Subject = txtSubject.Text;
//Note: When you make "IsBodyHtml" to true make
//ValidateRequest="false" in page derective
//As to make HTML content passed.
Mail.IsBodyHtml = true;
Mail.Body = txtComment.Text;
//Setting Reply address.
if (txtReplyTo.Text.Trim().Length != 0)
{
Mail.Headers.Add("Reply-To", txtReplyTo.Text);
}
else
{
Mail.Headers.Add("Reply-To", txtFrom.Text);
}
try
{
SmtpClient smtpMailObj = new SmtpClient();
//eg:localhost, 192.168.0.x, replace with your server name
smtpMailObj.Host = "myMailServer";
smtpMailObj.Send(Mail);
Response.Write("Your Message has been sent successfully");
}
catch (Exception ex)
{
Response.Write("Message Delivery Fails");
}

Sending Email with Attachment facility
MailMessage Mail = new MailMessage();
MailAddress ma = new MailAddress(txtFrom.Text,txtName.Text);
Mail.From = ma;
Mail.To.Add(txtTo.Text);
if(txtCC.Text.Trim().Length != 0)
Mail.CC.Add(txtCC.Text);
if(txtBCC.Text.Trim().Length != 0)
Mail.Bcc.Add(txtBCC.Text);
Mail.Subject = txtSubject.Text;
if (txtAttachment.Text.Trim().Length != 0)
{
string sAttach = txtAttachment.Text.Replace("\\","\\\\");
Mail.Attachments.Add(new Attachment(sAttach));
}
//Note: When you make "IsBodyHtml" to true make
//ValidateRequest="false" in page derective
//As to make HTML content passed.
Mail.IsBodyHtml = true;
Mail.Body = txtComment.Text;
//Setting Reply address.
if (txtReplyTo.Text.Trim().Length != 0)
{
Mail.Headers.Add("Reply-To", txtReplyTo.Text);
}
else
{
Mail.Headers.Add("Reply-To", txtFrom.Text);
}
try
{
SmtpClient smtpMailObj = new SmtpClient();
//eg:localhost, 192.168.0.x, replace with your server name
smtpMailObj.Host = "myMailServer";
smtpMailObj.Send(Mail);
Response.Write("Your Message has been sent successfully");
}
catch (Exception ex)
{
Response.Write("Message Delivery Fails");
}

Simplest Way of Sending Email from Gmail

protected void btnSendEmail_Click(object sender, EventArgs e)

{

//Create Mail Message Object with content that you want to send with mail.

System.Net.Mail.MailMessage MyMailMessage = new System.Net.Mail.MailMessage("dotnetguts@gmail.com","myfriend@yahoo.com",

"This is the mail subject", "Just wanted to say Hello");



MyMailMessage.IsBodyHtml = false;



//Proper Authentication Details need to be passed when sending email from gmail

System.Net.NetworkCredential mailAuthentication = new

System.Net.NetworkCredential("dotnetguts@gmail.com", "myPassword");



//Smtp Mail server of Gmail is "smpt.gmail.com" and it uses port no. 587

//For different server like yahoo this details changes and you can

//get it from respective server.

System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com",587);



//Enable SSL

mailClient.EnableSsl = true;



mailClient.UseDefaultCredentials = false;



mailClient.Credentials = mailAuthentication;



mailClient.Send(MyMailMessage);

}

Creating PDF file in C Sharp (C#): example "Hello, PDF!"

This page contains a step-by-step tutorial that will teach you how to create PDF files from Visual C# application using PDF Creator Pilot library.

1) Install PDF Creator Pilot library on your computer and run Microsoft Visual Studio.

Go to New menu and click Project... to create a new project

Microsoft Development Environment main menu

You will see the New Project Wizard. Select Windows Application in Visual C# Projects:

New Project wizard

2) New project will be created. Visual C# will generate new project Project1 and will automatically open the main form of the newly generated project:

Visual C# project form

3) Now we should add a reference to PDF Creator Pilot to be able to use pdf library in C#.NET project. Select Project in main menu and click Add Reference:

Project menu

Switch to COM tab and find PDF Creator Pilot in the list of available COM objects:

Add Reference dialog: list of available COM objects

Click the Select button to add a reference to PDF Creator Pilot and click OK

4) Now we should implement the code that will generate "Hello, PDF!" PDF document function. Double-click Form1 to create Form1_Load procedure:

VB.NET Application Form

The source code editing window will be opened:

Form1_Load procedure edit window

5) Now you have to implement the code that will generate your PDF file using PDF Creator Pilot.

To generate PDF document you have to do the following:

1. connect to the PDF Creator Pilot library;
2. set the file name for your PDF document;
3. draw "Hello, PDF!" message on the PDF page;
4. disconnect from the library.

Here is the source code:

private void Form1_Load(object sender, System.EventArgs e)

{

PDFCreatorPilot3Lib.PDFDocument3Class PDF = new PDFCreatorPilot3Lib.PDFDocument3Class();

// initialize PDF Engine

PDF.StartEngine("demo@demo", "demo");

// set filename

PDF.FileName = "TestCSHARP.PDF";

PDF.AutoLaunch = true; // auto-open generated pdf document

// start document generation

PDF.BeginDoc();

// draw "HELLO, PDF" message on the current PDF page

PDF.PDFPAGE_SetActiveFont("Verdana", true, false, false, false, 14, 0);

PDF.PDFPAGE_TextOut(10, 20, 0, "HELLO, PDF!");

// finalize document generation

PDF.EndDoc();

}

This function will generate PDF document and save it as "TestCSHARP.PDF" file in the application's folder.

Hint: You can simply copy the source code from the snippet above and then paste it in the Visual C# code editor:

Visual C# source code editor

6) Press F5 to run the application (you can also use "Debug" | "Start" menu command).
Visual C# will run the application. The application will generate "TestCSHARP.PDF" document.

If you have any PDF viewer (for example, Adobe Reader) installed on your computer, the library will launch it to open the generated PDF document:

Adobe Reader window




PDF Creator Pilot can be used with different languages to generate PDF files. See "Hello, PDF" example for:

* Visual Basic Script (VBScript)
* Visual Basic (VB)
* Visual Basic.NET (VB.NET)
* C Sharp (C#)
* Active Server Pages (ASP)
* Active Server Pages for .NET (ASP.NET)
* Delphi
* Visual C++

See also:

* PDF documents and PDF files. Introduction and short description
* PDF Creator Pilot technology
* PDF Creator Pilot FAQ

You can download the source code for the example project here: Visual Studio 2003 (8 Kb), Visual Studio 2005 (6.5 Kb).

Creating and Opening Microsoft Word Document from .NET Using C#

Creating and Opening Microsoft Word Document from .NET Using C#

This article is being written in response to a couple inquiries on the question, "How do I open a word document from .NET?"

Figure 1 - Word Launched from .NET Form

This article is being written in response to a couple inquiries on the question, "How do I open a word document from .NET?". I guess after people read my excel article, they were under the impression that I knew how to do this in Word. Luckily, after some hunting around on the forums and feedback from other C# Corner members I got the gist of it.

The First Step in manipulating Word in .NET is that you'll need to add a COM reference to your project by right clicking in the solution explorer on References->Add Reference. Click on the COM tab and look for the Microsoft Word 9.0 Object Library. Click Select and OK.



This will automatically place an assembly in your application directory that wraps COM access to Word. Now we are ready to create a word object in our code. To instantiate an instance of a Word application, you just declare the line below in your class:

private Word.ApplicationClass WordApp = new Word.ApplicationClass();

Now you can call the interesting methods and properties that Microsoft Word provides to you to manipulate documents in Word. Personally, I never want to figure the Microsoft Word code out myself, because the Word hierarchy and properties, although rich in features, has a bit of a learning curve. So in order to jump straight over the learning curve, I simple turn the Macro Recorder on in Word and let Word write the code for me. (Of course this is VBA code, but...close enough). To start the macro recorder in Word, go to Tools->Macro->Record New Macro inside Microsoft Word. Now anything you type, open, delete, or format, will get recorded in VBA, so you have a clue how to write your Word Interoperability code.

The application in this particular article is divided into two methods based on the button that is pressed in the form. The first button opens an existing Word Document and adds a copyright line to the document. The second button creates a new document, and brings up a dialog to allow you to enter a title to the document.

Below is the code for the first button event handler:

private void button1_Click(object sender, System.EventArgs e)
{
// Use the open file dialog to choose a word document
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
// set the file name from the open file dialog
object fileName = openFileDialog1.FileName;
object readOnly = false;
object isVisible = true;
// Here is the way to handle parameters you don't care about in .NET
object missing = System.Reflection.Missing.Value;
// Make word visible, so you can see what's happening
WordApp.Visible = true;
// Open the document that was chosen by the dialog
Word.Document aDoc = WordApp.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible);
// Activate the document so it shows up in front
aDoc.Activate();
// Add the copyright text and a line break
WordApp.Selection.TypeText("Copyright C# Corner");
WordApp.Selection.TypeParagraph();
}
}

The code above opens a document based on the file chosen in the OpenFileDialog. Notice the parameters passed to the Document.Open method are all references. Don't ask me why it was done this way, but it seems like when Microsoft goes through a call with optional parameters, they had no choice but to make everything a variant so on the C# side of the parameter list looks like a bunch of references to objects. If you want to skip over a parameter in the call to Open, use the System.Reflection.Missing.Value and assign it to an object. Once you know this trick, the rest of the interoperability used with Word is pretty straightforward.

Below is the code for creating a document from scratch:

private void button2_Click(object sender, System.EventArgs e)
{
// Use the custom dialog to get the title of the document from the user
TitleQuery theQueryDialog = new TitleQuery();
if (theQueryDialog.ShowDialog() == DialogResult.OK)
{
// vba code generated from recorded macro to "remind me" how to do it.
//**********************************************************
// Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
// Selection.Font.Bold = wdToggle
// Selection.TypeText Text:="Creating a Title"
// Documents.Add Template:="C:\My Documents\CSharp Book Project\Normal.dot",
// NewTemplate:=False, DocumentType:=0
// **********************************************************
// Set up all the parameters as generic objects so we can pass them in Documents.Add
object missing = System.Reflection.Missing.Value;
object fileName = "normal.dot"; // template file name
object newTemplate = false;
object docType = 0;
object isVisible = true;
// Create a new Document, by calling the Add function in the Documents collection
Word.Document aDoc = WordApp.Documents.Add(ref fileName, ref newTemplate, ref docType, ref isVisible);
// need to see the created document, so make it visible
WordApp.Visible = true;
aDoc.Activate();
// Global Constant enumerations are members of Word and can be assigned to Properties
// Set alignment to the center of the document
WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
// Toggle the title to a Bold Font
WordApp.Selection.Font.Bold = (int)Word.WdConstants.wdToggle;
// Type the Text of the Title that was inputted by the user in the Custom Dialog
WordApp.Selection.TypeText(theQueryDialog.Title);
}
}

The code above is a little less intuitive, so I used the Macro Recorder in VBA to spit out the VBA code for creating a document. Creating a document is done through the Documents Collection. The Add method of the Documents Collection creates a new document and brings it up in Word. The Add method allows you to specify the template to use and the document type. Note that the Add method also takes optional parameters, so as a result, you need to pass it a series of references to objects that box the types you would normally pass.

The title being placed in the document is formatted using some of the existing Word global enumeration constants. These constants tend to be constants nested in constants for organizational purposes. Although VBA gives you a clue to the relative name of the constants, you need to hunt for them a little bit using intellisense to find the parent enumeration. The code above uses the global enumerations to first center the title and then make it bold. The final line is similar to the previous listing in that it types the title into the Document.