ASP.NET Code
  Home arrow ASP.NET Code arrow Get Up and Running with .NET Cryptography ...
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  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
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
     
     
    ADVERTISEMENT


     

    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! Evaluate IBM Rational Developer for System i V7.1

    Download a free trial version of IBM Rational Developer for System i V7.1, which provides a complete development environment for traditional i5/OS application development. IBM Rational Developer for System i is a new eclipse-based workstation offering for i5/OS application development that provides a comprehensive Integrated Development Environment for edit/compile/debug of traditional RPG/COBOL/C/C++ i5/OS applications.
    FREE! Go There Now!


    NEW! Evaluate Rational Business Developer V7.1

    Visit IBM developerWorks to download a free trial version of IBM Rational Business Developer V7.1. Rational Business Developer offers rapid and simplified development of business applications and services through Enterprise Generation Language (EGL) tools, generating Java or mainframe solutions while shielding developers from technical complexities.
    FREE! Go There Now!


    NEW! Evaluate WebSphere Extended Deployment Compute Grid V6.1

    Visit IBM developerWorks to download a free trial version of WebSphere Extended Deployment Compute Grid, which lets you schedule, execute, and monitor batch jobs. Because online transaction processing and batch jobs execute simultaneously on the same server resources, you can avoid costly duplication of resources. Compute Grid supports job types of Java transactional batch, compute-intensive and a new type called "native execution", which enables non-Java workloads to run on distributed end points.
    FREE! Go There Now!


    NEW! IBM Enterprise Modernization Sandbox for System z

    IBM Enterprise Modernization solutions help organizations evolve core IT systems towards modern architectures and technologies—reducing the burden of maintenance and freeing up resources to develop new business requirements and capabilities. With the IBM Enterprise Modernization Sandbox for System z you can evaluate IBM Enterprise Modernization solutions focused on five key areas: Assets, Architectures, Skills, Processes and Infrastructures, and Investment. Each solution is based upon real customer experiences and offers a proven path to get you started with your modernization projects.
    FREE! Go There Now!


    NEW! Project and Portfolio Management Executive Resource Kit

    Portfolio Management is about effectively managing portfolio value by aligning portfolio investments with business goals. This complimentary e-kit provides a collection of materials that can help you understand how IBM Rational enables and automates best practices for improved governance and clear visibility into portfolio and project performance across the entire IT project lifecycle.
    FREE! Go There Now!


    NEW! Trial download: IBM Rational Manual Tester V7.0.1

    Try the latest version of IBM Rational Manual Tester V7.0.1 by downloading a free trial from IBM developerWorks. This manual test authoring and execution tool promotes test step reuse to reduce the impact of software change on testers and business analysts and addresses the needs of teams performing at least a portion of their testing manually.
    FREE! Go There Now!


    NEW! Try the IBM SOA Sandbox for People

    Visit IBM developerWorks to try the IBM SOA Sandbox for people. The SOA Sandbox for people provides a trial environment with the necessary tooling and components required to enable consistent human and process interaction and collaboration, showing how you can improve user experience and business productivity.
    FREE! Go There Now!


    NEW! Webcast: IBM Rational Build Forge - Beyond the Build

    The discipline of assembling and delivering software is maturing beyond standard developer-centric compile/test software builds. The end-to-end software development lifecycle is emerging as the new focus moves “Beyond the Build.” Join this on demand webcast to learn about methods for streamlining software delivery and key capabilities of the IBM Rational Build Forge framework for automating build and release management in environments of any size.
    FREE! Go There Now!


    NEW! Whitepaper: Achieving consistency between business process models and operational guides

    Explore how Rational and WebSphere software enable enterprise documentation in SOA environments. Specifically, a new integration between IBM WebSphere® Business Modeler and IBM Rational® Method Composer software can help technical writers more easily keep enterprise operations manuals in sync with changes that are made to business processes, resulting in more accurate and timely documentation that benefits the entire enterprise.
    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





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 1 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek