ASP.NET Code
  Home arrow ASP.NET Code arrow Get Up and Running with .NET Cryptography ...
Iron Speed
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Dedicated Servers 
Download TestComplete 
Windows Web Hosting
 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
ASP.NET CODE

Get Up and Running with .NET Cryptography Providers
By: Derek Beyer
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 8
    2002-07-07

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    Iron Speed
     
    ADVERTISEMENT

    Free Web 2.0 Code Generator! Generate data entry and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!

     

    The example below shows the use of the RSA Cryptography provider. The typical private and public keys that you may normally associate with cryptography are generated while working with RSA cryptography provider. The owner of the key pair - you for example - issues the public key to anyone who wants it. The private key on the other hand must be kept secret in order to ensure the integrity of the encryption. Simply stated the process that this example goes through is as follows: Step 1: take the text out of the first textbox and encrypt it Step 2: store the resulting encrypted string in the second textbox Step 3: take the text out of the second textbox and decrypt it Step 4: show the resulting decrypted string in the third textbox. Please refer to the comments in the code for more detail. Note: The term "cryptography provider" refers to those classes in the System.Security.Cryptography namespace that implement their particular type of cryptography. As you look through the types in the Cryptography namespace, you will notice a few classes that sound like they implement the kind of cryptography that you are looking for. Many of these classes such as System.Security.Cryptography.RSA and System.Security.DES are abstract (or not-inheritable in Visual Basic.NET), meaning that you cannot directly create an instance of these classes. Each of these abstract classes have a corresponding provider (with "provider" in the class name) that you can work with.

     <%@ Page Language="C#"%><%@ Import namespace="System.Security.Cryptography" %>
    <
    META content="Microsoft Visual Studio 7.0" name=GENERATOR>
    <
    META content=C# name=CODE_LANGUAGE>
    <META content=JavaScript name=vs_defaultClientScript>
    <
    META content=http://schemas.microsoft.com/intellisense/ie5 
    name=vs_targetSchema>
    <
    SCRIPT language=C# runat="server">
        
    void btnEncrypt_Click(Object senderEventArgs e)
        {
            
    // structure that holds the public/private key pair
            
    RSAParameters rsaParam;

            
    // create an instance of the RSA cryptography provider
            // at this point a new public/private key pair has been created
            // You have to instruct RSACryptoServiceProvider or DSACryptoServiceProvider to use 
            // machine key store (as in the following sample 
            // code) in scenarios such as a Web service, ASP Page, or COM+, where the user profile 
            // is not loaded by the system for performance
            // reasons. You can use the CspParameters parameter in 
            // the RSACryptoServiceProvider() constructor, as follows: 
            // Refer to Q322371 @ http://support.microsoft.com/default.aspx?scid=kb;en-us;Q322371
            // Only other way to get around is run the aspnet_wp.exe worker process with SYSTEM 
            //credentials which I'd not recommend!

            
    CspParameters CSPParam = new CspParameters();
            
    CSPParam.Flags CspProviderFlags.UseMachineKeyStore;
            
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(CSPParam);

            
    // get a byte array representing the first string
            
    byte[] byteInput = (new System.Text.UnicodeEncoding()).GetBytes(textBox1.Text);

            
    // encrypt the string using the provider and save the result to the byteEncrypted array
            
    byte[] byteEncrypted rsa.Encrypt(byteInputfalse);

            
    // the rsaParam structure contains the public/private key pair. 
            // by passing true to ExportParameters, we tell the provider to include the private key 
            
    rsaParam rsa.ExportParameters(true);

            
    // for illustration purposes show the encrypted string in the second textbox
            // this string should not be readable.
            
    textBox2.Text = (new System.Text.UnicodeEncoding()).GetString(byteEncrypted);

            
    /*************************************************/
            // normally we would stop at this point 
            // and save the public/private key some where.
            // but let's go on to see how we would use the RSAParameters 
            // structure to decrypt the string
            /*************************************************/

            // import the RSAParameters structure that we used previously. 
            // normally at this point we would have to create another instance of the provider, 
            // which would generate another public/private key pair
            // that could not be used to decrypt the string. So we must use the original public/private 
            // key pair from the RSAParameters structure 
            
    rsa.ImportParameters(rsaParam);

            
    // get the encrypted string from the second textbox and store it in a byte array
            
    byte[] byteEncryptedString = (new System.Text.UnicodeEncoding()).GetBytes(textBox2.Text);

            
    // decrypt the data in the byte array using the provider
            // we pass false in the second parameter to tell the provider that we do not want to use 
            // OAEP padding, but don't worry about that for this example.
            
    byte[] byteDecryptedString rsa.Decrypt(byteEncryptedStringfalse);

            
    // assign the resulting decrypted string to the third textbox
            
    textBox3.Text = (new System.Text.UnicodeEncoding()).GetString(byteDecryptedString); 
        }
        
    </SCRIPT>

    <FORM id=Form1 method=post runat="server">string:<asp:textbox id=textBox1 
    runat="server"></asp:textbox>
    encrypted string:<asp:textbox id=textBox2 
    runat="server"></asp:textbox>
    decrypted string:<asp:textbox id=textBox3 
    runat="server"></asp:textbox>
    <asp:button id=btnEncrypt 
    onclick=btnEncrypt_Click runat="server" 
    text="Encrypt"></asp:button></FORM>

    Derek Beyer derek@derekbeyer.com
    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More ASP.NET Code Articles
    More By Derek Beyer

     

    IBM® developerWorks developerWorks - FREE Tools!


    Check out the new Jazz space on developerWorks

    <a href="http://zeus.developershed.com/shonuff.php?blackbird=3853&zoneid=442&source=&dest=http%3A%2F%2Fwww.ibm.com%2Fdeveloperworks%2Fspaces%2Fjazz%3FS_TACT%3D105AGY31%26S_CMP%3DDEVSHED&ismap="><img src="http://images.devshed.com/corp/img/news/jazz01.gif" alt="developerWorks Jazz space" align="left"></a>You've heard the buzz about Jazz... want to know more about it from a developer's perspective? Check out the Jazz space on developerWorks. This space is an up-to-date resource for developers, including technical information about Jazz and products built on Jazz, like Rational Team Concert Express. The Jazz space includes content from a wide variety of sources, including links, feeds, and comments from experts.
    FREE! Go There Now!


    NEW! Application development for the OLPC laptop

    The XO laptop (of the One-Laptop-Per-Child initiative) is an inexpensive laptop project intended to help educate children around the world. The XO laptop includes many innovations, such as a novel, inexpensive, and durable hardware design and the use of GNU/Linux as the underlying operating system. The XO also includes an application environment written in Python with a human interface called Sugar, accessible to everyone (including kids). Explore the Sugar APIs and learn how to develop and debug a graphical activity in Sugar using Python.
    FREE! Go There Now!


    NEW! Did you say mainframe? e-kit

    Learn how you can extend modern application lifecycle management to IBM System z through the IBM Rational Software Delivery Platform (SDP). The Did you say mainframe? e-kit includes podcasts, webcasts, tutorials, white and red papers, demos, and articles designed to help ease the challenges of modernizing your enterprise. This complimentary kit for mainframe developers is a practical, how-to guide for making the most of an existing development environment, including the skills and infrastructure already in place at an established enterprise.
    FREE! Go There Now!


    NEW! Expand the editing capabilities of OpenOffice with XSLT

    You might know that you can pull XML data into OpenOffice's spreadsheet program, Calc, but did you know that you can create a filter to make word-processing documents out of data stored as XML? This tutorial shows you how to use OpenOffice's import/export filters to open your XML data as though it's just a plain document. From there, users can edit the document much more naturally and then save it back to its native format. You can also use this feature to easily turn your documents into XML data.
    FREE! Go There Now!


    NEW! Info 2.0: Harnessing the power of Web 2.0 and Enterprise Mashups

    Listen to this webcast to get an overview of Info 2.0 and a technical demo of how to quickly build an enterprise mashup. IBM's Info 2.0 technology leverages emerging Web 2.0 technologies such as mashups, feeds, AJAX, and JSON in order to simplify assembly of information using feeds and services. Come learn about the technical elements of Info 2.0 including the Feed Generation framework, Mashup Engine, and mashup assembly components. Learn how to pull information from databases, departmental information, and the Web to create mashups critical to your company’s success. We will also discuss best practices to help you get started.
    FREE! Go There Now!


    NEW! Innovate don't duplicate! Asset reuse strategies for success

    Asset Reuse is a key strategy for companies looking to create innovative solutions to solve complex software development problems. Searching for, identifying, updating, using and deploying software assets can be a difficult challenge. Listen to this webcast, to learn about strategies and tools that you can leverage for a successful project, including Rational Asset Manager, Rational Software Architect and WebSphere Service Registry and Repository.
    FREE! Go There Now!


    NEW! Rational Modeling Extension for Microsoft.Net

    Rational Modeling Extension for Microsoft .NET enhances usability for code generation supporting a more intelligent refactoring. The latest enhancements enable organizations with Java and .NET systems and software development maintain architectural integrity across heterogeneous platforms.
    FREE! Go There Now!


    NEW! Travels with Mark: A Hitchhiker&apos;s Guide to the UniVerse, Part 5: Increase dynamic array processing performance in IBM UniVerse

    Investigate the effects of field-level caching in dynamic array access, in part 5 of the UniVerse performance series.
    FREE! Go There Now!


    NEW! Using IBM Rational Tester for SOA Quality: Using IBM Rational Tester for SOA Quality with IBM WebSphere MQ Version 6.0

    Learn how IBM Rational Tester for SOA Quality addresses IBM WebSphere MQ with Web services. You get hands-on experience in creating a test, handling the WebSphere MQ series protocol, configuring the test, and then replaying it.
    FREE! Go There Now!


    NEW! Webcast: Introducing the new Information Server and Solutions community: LeverageInformation

    User communities play an important role in communication and collaboration around products, solutions and other areas of special interest to members. Successful communities are able to provide the right mix of content and services to deliver a value proposition that resonates with each audience. Join Tom Inman, VP of Marketing for Information and Platform Solutions as he introduces the new LeverageINFORMATION community. During this webcast, learn about the value provided by the community and how customers and partners derive value from the community in addressing their own technical and business challenges.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    ASP.NET CODE ARTICLES

    - How to Use the ListBox Control in ASP.NET 2.0
    - How to Load XML Documents in ASP.NET 2.0
    - DataGrid Code
    - ASP.NET Guestbook
    - User Controls and Client Side Scripting
    - ASP.NET Programming with Microsoft's AS...
    - ASP.NET Basics (part 3): Hard Choices
    - ASP.NET Basics (part 2): Not My Type
    - ASP.NET Basics (part 1): Nothing But .Net
    - Directory Tree Browser
    - How to get the confirmation of Yes/No from a...
    - Complete example using custom errors and wri...
    - Paging Certain # records per page .NET style
    - General Methods of formatting and Subtractin...
    - .NET LinkButton web control

     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway