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!


    NEW! Rational Build Forge Express eKit

    Rational Build Forge Express Edition is an automation framework that packages the latest enterprise-grade technologies into a reliable, flexible and robust configuration designed and priced specifically for small to midsize businesses. The new Rational Build Forge Express eKit provides you with valuable resources – including a case study, podcast, demo, and articles – to help you increase staff productivity, compress development cycles and deliver better software, fast.
    FREE! Go There Now!


    NEW! Test terminal-based applications with Rational Functional Tester

    Regression testing -- in which code is thoroughly tested to ensure that changes have not produced unexpected results -- is an important part of any development process. But many testing environments neglect the terminal-based applications that still form the backbone of many industries. In this tutorial, you'll learn how the Rational Functional Tester Extension for Terminal-Based Applications works with other Rational Functional Tester to help test terminal-based applications quickly and easily.
    FREE! Go There Now!


    NEW! Download DB2 9.5 for Linux, Unix, and Windows

    Download a free trial version of IBM DB2 9.5 for Linux, UNIX, and Windows. DB2 9 is the result of a five-year development project that transformed traditional (static) database technology into an interactive data server that merges the high performance and ease of use of DB2 with the self-describing benefits of XML.
    FREE! Go There Now!


    NEW! Download IBM Data Studio V1.1

    Visit IBM developerWorks to download the latest trial version of IBM Data Studio V1.1 at no cost. IBM Data Studio is a comprehensive data management solution that helps you effectively design, develop, deploy and manage your data, databases, and database applications throughout the data management life cycle utilizing a consistent and integrated user interface. Unlike other client-side data management solutions that focus on only one aspect of the application lifecycle or database administration, Data Studio complements the Rational Software Delivery platform, providing unparalleled flexibility for a heterogeneous data server environment across platforms.
    FREE! Go There Now!


    NEW! Rational Talks to You: Manage RUP-based CMMI initiatives

    Join this Rational Talks to You teleconference on December 4 at 1:00 pm ET to discuss how Rational Method Composer can help meet your compliance objectives. Get your questions answered!
    FREE! Go There Now!


    Role of Integrated Requirements Management in Software Delivery

    As organizations integrate software into every aspect of business, they are constantly pressured to deliver faster, better, and cheaper results. Unfortunately, a “dis-integrated” software delivery approach reduces returns while increasing costs. This IBM Rational White Paper shows how Integrated Requirements Management aligns organizations around maximizing value and keeping pace with change.
    FREE! Go There Now!


    NEW! Application Development Tools for the Mainframe Developer

    You probably have thousands of lines of COBOL code loaded with business intelligence and being used to run your business, along with an army of developers maintaining these applications. Learn how to prepare your applications and developers so you can keep that competitive edge and move to a service-oriented architecture with the IBM Rational Enterprise Modernization solutions. Replay is available for 9 months.
    FREE! Go There Now!


    Be the first to hear about i5/OS V6R1!

    Hold your calendar on January 30, 2008 for this free webcast on the new i5/OS. Rational's Enterprise Modernization products will be discussed at this webcast as they help to drive the application development environment for this new System i OS. <br />And learn how i5/OS will take you to the next step of efficient, resilient business processing. You will hear about the new i5/OS capabilities as it will be the most significant i5/OS release in years. If you cannot join the webcast on 1/30/08 you can still use this link to listen to the replay.<br />
    FREE! Go There Now!


    NEW! Webcast: Application security testing and Web compliance

    Join the IBM Watchfire team for an informative discussion on techniques and best practices to proactively manage Web application security and how to effectively build application security testing into the software development lifecycle (SDLC). In this Software Delivery Platform webcast you will learn: How to better understand potential web application security vulnerabilities, best practices and how to effectively integrate application security testing into the software development lifecycle, the importance of detecting and removing software vulnerabilities during application development.
    FREE! Go There Now!


    IBM DB2 Deep Compression ROI Tool

    The IBM DB2 Deep Compression ROI tool is designed for DBA’s and IT management personnel to perform a clinical analysis of the cost savings gained from the Storage Optimization feature of DB2 9 for Linux, UNIX and Windows. The feature, also known as Deep Compression, compresses data that lies within a database by up to 80% at times.
    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...
    - .NET LinkButton web control
    - .NET Static VariablesBetter than Applicatio...
    - .Net to Oracle Connectivity using ODBC .NET
    - A sample code to Add two DataTables in a dat...





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