asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search








Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

How to Send Secure Mail in ASP-Based E-Commerce Applications - Part II, Cont'd
By Peter Persits


  • email this article to a colleague
  • suggest an article

    Automatic Generation of PDF Documents

    It may come as a surprise for you, but PDF is essentially an ASCII format. Most PDF files contain "pockets" of binary data, such as embedded images, fonts, or compressed PostScript code, but the overall document structure is defined by ASCII text.

    Being an ASCII file, a simple PDF document can be generated even with plain-vanilla VBScript, let alone C#. Surely, some heavy-duty coding would be required, but it's doable.

    Unfortunately, secure PDF is a whole other story. Classic VBScript is out, and even the mighty .NET framework won't give us all the pieces we need right off the shelf. Specifically, .NET does not implement the RC4 cipher, which is what PDF security is based on. Even if we could put together, or find on the Web, an RC4 encryption object, let me just put it plain and simple: this stuff is too damn hard. Fuhgeddaboudit. Period. End of story.

    And why bother? There are tons of free and commercial PDF components on the market, and let's not forget the SDK from Adobe itself.

    I will demonstrate how to build a simple encrypted text PDF document using AspPDF, an ASP component from Persits Software Inc. However, any other PDF component supporting encryption can be used instead. Several of them are listed below.

    VBScript Code Sample

    Here is ASP code based on AspPDF and AspEmail. For the sake of brevity, the HTML form invoking this script is not shown here. The entire project can be downloaded from here. To see this code in action, go to http://support.persits.com/pdf/demo_email.asp.

    1

    Set PDF = Server.CreateObject("Persits.PDF")

    2

    Set Doc = PDF.CreateDocument

    Set Page = Doc.Pages.Add

    3

    ' We will use Arial font which supports many alphabets.

    ' Use another if Arial does not support your language (such as Chinese)

    Set Font = Doc.Fonts("Arial")

    4

    ' Create table with 4 rows and 2 cols, no border. Initial height not important.

    Set Table = Doc.CreateTable("width=500; height=20; Rows=4; Cols=2; Border=0; CellBorder=0; CellSpacing=-1; cellpadding=2 ")

    Table.Font = Font

     

    ' Make left column smaller

    Table.Rows(1).Cells(1).Width = 100

    Table.Rows(1).Cells(2).Width = 400

    5

    ‘ Fill table cells with email message data

    ' create a parameter object

    Set Param = PDF.CreateParam("size=20; expand=true")

     

    Table.Rows(1).Cells(1).AddText "From:", Param

    Table.Rows(1).Cells(2).AddText "AspPDF Live Demo", Param

     

    Table.Rows(2).Cells(1).AddText "To:", Param

    Table.Rows(2).Cells(2).AddText Request("Email"), Param

     

    Table.Rows(3).Cells(1).AddText "Subject:", Param

    Table.Rows(3).Cells(2).AddText Request("Subject"), Param

     

    Table.Rows(4).Cells(1).AddText "Message:", Param

    Table.Rows(4).Cells(2).AddText Request("Body"), Param

    Table.Rows(4).Cells(2).BgColor = "lightgray"

    6

    ' Render table on page

    Page.Canvas.DrawTable Table, "x=50; y=750"

    7

    ' Now handle attachments. Use "FileAttachment" annotations

    Set arrPaths = Session("arrPaths")

    Set arrNames = Session("arrNames")

    Names = arrNames.Items

    Paths = arrPaths.Items

    For i = 0 to arrPaths.Count - 1

           ' x, y, width, height are coordinates of the paperclip icon

           Param.Set "Type=FileAttachment; y=760;width=10; height=10;"

           Param("x") = 10 + 30 * i

           Set Annot = Page.Annots.Add(Names(i), Param, "PaperClip", Paths(i) )

    Next

    8

    ' Encrypt document with password specified, use 128-bit key

    Doc.Encrypt "", Request("Pwd"), 128

    9

    ‘ Save document under the name message.pdf

    Filename = Doc.Save( Server.MapPath("files") & "\message.pdf", False )

    10

     

     

     

     

     

     

     

    ‘ Now send message and attach this PDF file

    Set Mail = Server.CreateObject("Persits.MailSender")

    Mail.Host = "amsterdam"

    Mail.From = "info@persits.com"

    Mail.Subject = "Secure message from AspPDF live demo"

    Mail.Body = "Open PDF attachment to read the message"

    Mail.AddAddress Request("Email")

    Mail.AddAttachment Server.MapPath("files") & "\" & Filename

     

    ' Send message, trap errors

    On Error Resume Next

    Mail.Send

     

    If Err = 0 Then

           Response.Write "Success! A message was sent to " & Request("Email") & "."

    Else

           Response.Write "Message was not sent. The error is: " & Err.Description

    End If

    The code is fairly self-explanatory, but I will go over the highlights briefly.

    (1) creates an instance of AspPDF's main object, PdfManager
    (2) creates an instance of PdfDocument, an object representing an empty PDF document, and adds a page to it
    (3) obtains an instance of the PdfFont object representing the Arial font used throughout the document
    (4) creates a table with 2 columns and 4 rows, sets the first column's width to 100 pt and second to 400 pt (each point is 1/72 inch)
    (5) fills table cells with various components of a text message (From, To, Subject, message body)
    (6) draws the table on the PDF document's only page
    (7) obtains a list of attached files from a session variable, and creates a "File Attachment" annotation for each file to be attached to the message. A PDF annotation is an interactive element on a document. The most common type of annotation is a text note, which appears like a push pin or paperclip icon. Clicking on the icon opens up a box with text associated with the annotation. File Attachment annotations work in a similar fashion, except they contain arbitrary files as opposed to text.
    (8) encrypts the document with a 128-bit key derived from user-specified password. Here, we specify the user password only, leaving the owner password blank. Permission flags are not being used.
    (9) saves the PDF document to disk, generates a unique file name to avoid overwriting an existing file with the same name.
    (10) sends the PDF document to the intended recipient as a file attachment using a mailing component (AspEmail in this code sample).

    C# Code Sample

    This code sample uses .NET's built-in mailing object instead of AspEmail. The entire project can be downloaded from here.

    <%@ Import Namespace="System.Web" %>

    <%@ Import Namespace="System.Web.Mail" %>

    <%@ Import Namespace="System.Reflection" %>

    <%@ Import Namespace="ASPPDFLib" %>

     

    <script runat="server" LANGUAGE="C#">

     

    void Send(Object Source, EventArgs E)

    {

     

    try

    {

           // create instance of the PDF manager

           IPdfManager objPDF;

           objPDF = new PdfManager();

     

           // Create new document

           IPdfDocument objDoc = objPDF.CreateDocument(Missing.Value);

     

           // Add a page to document

           IPdfPage objPage = objDoc.Pages.Add(Missing.Value, Missing.Value, Missing.Value);

              

           // We will use Arial font which supports many alphabets.

           // Use another font if you Arial does not support your language (such as Chinese)

           IPdfFont objFont = objDoc.Fonts["Arial", Missing.Value];

     

           // create a parameter object

           IPdfParam objParam = objPDF.CreateParam("size=20; expand=true");

     

           // Create table with 4 rows  and 2 columns, no border. Initial height not important.

           IPdfTable objTable = objDoc.CreateTable("width=500; height=20; Rows=4; Cols=2; Border=0; CellBorder=0; CellSpacing=-1; cellpadding=2 ");

           objTable.Font = objFont;

     

           // Make left column smaller

           objTable.Rows[1].Cells[1].Width = 100;

           objTable.Rows[1].Cells[2].Width = 400;

     

           objTable.Rows[1].Cells[1].AddText( "From:", objParam, Missing.Value );

           objTable.Rows[1].Cells[2].AddText( "AspPDF Live Demo", objParam, Missing.Value );

     

           objTable.Rows[2].Cells[1].AddText( "To:", objParam, Missing.Value );

           objTable.Rows[2].Cells[2].AddText( txtEmail.Value, objParam, Missing.Value );

     

           objTable.Rows[3].Cells[1].AddText( "Subject:", objParam, Missing.Value );

           objTable.Rows[3].Cells[2].AddText( txtSubject.Value, objParam, Missing.Value );

     

           objTable.Rows[4].Cells[1].AddText( "Message:", objParam, Missing.Value );

           objTable.Rows[4].Cells[2].AddText( txtBody.Value, objParam, Missing.Value );

           objTable.Rows[4].Cells[2].BgColor = "lightgray";

     

           // Render table on page

           objPage.Canvas.DrawTable( objTable, "x=50; y=750" );

     

           // Now handle attachments. Use "FileAttachment" annotations

           ListDictionary arrPaths = (ListDictionary)Session["arrPaths"];

           ListDictionary arrNames = (ListDictionary)Session["arrNames"];

           int i = 0;

           foreach( int key in arrNames.Keys )

           {

                  // x, y, width, height are coordinates of the paperclip icon

                  objParam.Set( "Type=FileAttachment; y=760;width=10; height=10" );

                  objParam["x"].Value = 10 + 30 * i;

                  String strName =  (String)arrNames[key];

                  IPdfAnnot objAnnot = objPage.Annots.Add( strName, objParam, "PaperClip", arrPaths[key] );

                  i++;

           }

     

           // Encrypt document with password, use 128-bit key. Permission flags not used.

           objDoc.Encrypt( "", txtPwd.Text, 128, Missing.Value );

     

           String strFilename = objDoc.Save( Server.MapPath("files") + "\\message.pdf", false );

                 

           // Document created. Now send it via email as an attachment

           MailMessage objMail = new MailMessage();

           objMail.From =  "AspPDF Live Demo <info@asp-pdf.com>";

           objMail.To = txtEmail.Value;

           objMail.Body = "Open PDF attachment to read the message.";

           objMail.Subject = "Secure message from AspPDF live demo";

           objMail.Attachments.Add( new System.Web.Mail.MailAttachment( Server.MapPath("files") + "\\" + strFilename ) );

     

           SmtpMail.SmtpServer = "amsterdam";

           SmtpMail.Send( objMail );

                 

           lblResult.Text = "<font color=\"green\">Success! A message was sent to <i>" + txtEmail.Value + "</i></font>.";

    }

    catch(Exception e)

    {

           lblResult.Text = "<font color=\"red\">Error: " + e.Message + "</font>";

    }

     

    }

     

     

    </script>

    Adobe SDK Code Sample

    For those who prefer to develop their own ASP components, I have put together a simple application written in C that is based on the Adobe PDF Library SDK. This app simply creates an encrypted PDF document with the text "Hello World". Download it here. Note that you must have the Adobe SDK installed on your machine to compile and run this code sample. The SDK can be obtained at http://partners.adobe.com/asn/tech/pdf/pdfl/index.jsp.

    Fig. 3. This is what a secure message generated by the code above looks like in Acrobat Reader 6.0. Paperclip icons in the upper-left corner represent file attachments.

    << Once Upon a Time ... •       • Other PDF Components >>

  • Supporting Products/Tools
    AspEncrypt
    Built around the Microsoft CryptoAPI, AspEncrypt helps you harness all major encryption and hashing algorithms such as DES, Triple-DES, RC2, RC4, RSA, MD5 and SHA1 in just a few lines of code. The component can be used in tandem with AspEmail to send encrypted and signed mail in the industry-standard S/MIME format, or with AspUpload to encrypt files as they are being uploaded. AspEncrypt can also be used to issue and manage X.509 digital certificates.
    [Top]
    AspPDF
    AspPDF is an ASP/ASP.NET component which enables generation and management of documents in PDF format. Features include advanced text formatting, font embedding, form fill-in, images, tables, content and page extraction, document stitching, encryption, digital signatures, and more.
    [Top]
    Other Articles
    Feb 3, 2005 - ASP.NET Mixed Mode Authentication
    In many web applications it is desirable for both intranet users and external parties to be able to seamlessly log onto the system. The problem this raises is that it is not easy to allow intranet users to log in via Windows integrated authentication while also allowing external parties to log in to the same application using standard forms authentication. This article will show you one way to achieve the best of both worlds when it comes to authentication.
    [Read This Article]  [Top]
    Dec 8, 2004 - Designing Role-Based Security Models for .NET
    In this article, Michele Leroux Bustamante discusses authentication, authorization and role-based security in .NET. Along the way, he provides some best practices for implementing role-based security in some typical .NET application scenarios including rich clients, Web applications, and Web services.
    [Read This Article]  [Top]
    May 11, 2004 - SharePoint Security and .NET Impersonation
    When implementing custom components that require access to restricted resources, implicit impersonation must be used. Jay Nathan shows how to create a class that makes using .NET Impersonation a snap.
    [Read This Article]  [Top]
    Mar 10, 2004 - Intellectual Property Protection and Code Obfuscation
    Learn about the execution process of CLR-based programs and how to protect your applications from being easily disassembled back into source code.
    [Read This Article]  [Top]
    Feb 24, 2004 - How to Send Secure Mail in ASP-Based E-Commerce Applications - Part II
    Businesses that utilize encrypted e-mail may find Secure Multipurpose Internet Mail Extensions (S/MIME) to be somewhat restrictive. This article shows how to use security features in PDF as an alternative to S/MIME.
    [Read This Article]  [Top]
    Feb 2, 2004 - Fighting Spambots with .NET and AI
    Bill Gates, in a recent interview, predicted the end of spam by 2006. One of the methods he mentioned involved a challenge only a real live person could handle. Adnan Masood shows how to use AI and .NET to create a user verification scheme that incorporates similar concepts Gates alluded to.
    [Read This Article]  [Top]
    Jan 21, 2004 - Configuring .NET Code Access Security
    Code Access Security (CAS) is the .NET Framework security model that grants code permission to resources based on "evidence" pertaining to the encapsulating assembly. In this article, David Myers examines CAS and explains different configuration methods.
    [Read This Article]  [Top]
    Mar 10, 2003 - Platform Neutral and Transparent Encryption of Sensitive Customer Information
    Zhenlei Cai combines an open source C++ encryption library with SQL Server extended stored procedures to create a platform neutral, transparent encryption solution that resides at the database layer.
    [Read This Article]  [Top]
    Jan 15, 2003 - Exploring Machine.Config - User Security and More
    Christopher Spann offers a .NET configuration tip that should help ease system administrators' fears of security compromise and thus assuage growing developer demand for a .NET environment.
    [Read This Article]  [Top]
    Dec 10, 2002 - Encrypting Cookie Data with ASP.NET
    You don't have to be a cryptography expert or spend lots of money on third-party components to secure sensitive data in .NET. In this article, Wayne Plourde shows just how easy it is to encrypt cookie data using encryption classes in the .NET System.Security.Cryptography namespace.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers