Tải bản đầy đủ (.pdf) (78 trang)

Tài liệu Module 9: Encrypting, Hashing, and Signing. Data pptx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.1 MB, 78 trang )









Contents
Overview 1
Lesson: Encryption and Digital Signing
Libraries 2
Lesson: Using CAPICOM 9
Lesson: Using the
System.Security.Cryptography
Namespace to Hash Data 21
Lab 9: Hashing Data 26
Lesson: Using the
System.Security.Cryptography
Namespace to Encrypt and Sign Data 42
Review 62

Module 9: Encrypting,
Hashing, and Signing
Data




Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,


domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, place or event is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property

 2002 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, ActiveX, Active Directory, Authenticode, Hotmail,
JScript, Microsoft Press, MSDN, PowerPoint, Visual Basic, Visual C++, Visual Studio, and
Windows Media are either registered trademarks or trademarks of Microsoft Corporation in the
United States and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.


Module 9: Encrypting, Hashing, and Signing Data iii


Instructor Notes
This module explains to students how to strengthen the security of their Web
applications by incorporating the programmatic use of cryptography.

Depending on the programming platform, students will use one of several
cryptographic libraries to add encryption, hashing, and digital signing
functionality to their Web application. After completing this module, students
will be able to use the CAPICOM cryptographic library and the
System.Security.Cryptography namespace to encrypt, hash, and sign data.
After completing this module, students will be able to:
!
Choose the most appropriate cryptographic library for a given programming
platform.
!
Use CAPICOM to encrypt, decrypt, hash, and sign data in an Active Server
Pages (ASP) Web application.
!
Use the System.Security.Cryptography namespace to hash data in a
Microsoft
®
ASP.NET Web application.
!
Use the System.Security.Cryptography namespace to encrypt and decrypt
data by using both symmetric and asymmetric encryption, and sign data in
an ASP.NET Web application.

To teach this module, you need the following materials:
!
Microsoft PowerPoint
®
file 2300A_09.ppt
!
Hypertext Markup Language (HTML) code file 2300A_09_code.htm


To prepare for this module:
!
Read all of the materials for this module.
!
Complete the practices and lab.
!
Read Chapter 21, “Encrypting Data over the Network,” in ASP.NET
Unleashed by Stephen Walther (2002, Sams Publishing).
!
Read Chapter 7, ”Storing Secrets,” in Writing Secure Code by Michael
Howard and David LeBlanc (2002, Microsoft Press
®
).
!
Read the Microsoft MSDN
®
Magazine article, “Protect Private Data with
the Cryptography Namespaces of the .NET Framework,” which is available
at
!
Read the MSDN article, “The Cryptography API, or How to Keep a Secret,”
which is available at
html/msdn_cryptapi.asp.
!
Read the MSDN article, “Introducing CAPICOM,” which is available at

!
Read the TechNet article, “Authentication and Encryption,” which is
available at
Presentation:

75 minutes

Lab:
60 minutes
Required materials
Preparation tasks
iv Module 9: Encrypting, Hashing, and Signing Data


!
Read the TechNet article, “Data integrity with hash functions,” which is
available at
proddocs/sag_IPSec_Und6.asp.
!
Read about hashing and encryption algorithms at the SSH Communications
Security Web site at

The information in this section provides setup instructions that are required to
prepare the instructor computer or classroom configuration for the lab.
!
Prepare for the lab by updating the TailspinToys database (Glasgow
computer only)
On the Glasgow computer, run a Structured Query Language (SQL) script to
change the data type of the Password field in the Users table to be binary:
1. On the Start menu, click Programs, click Microsoft SQL Server, and then
click Query Analyzer.
2. In the Connect to SQL Server dialog box, type (local) in the SQL Server
box, click Start SQL Server if it is stopped, click Windows
Authentication, and then click OK.
3. On File menu, click Open.

4. In the Open Query File dialog box, in the File name box, type
C:\Program Files\Msdntrain\2300\Labfiles\Lab09\database
\update2300DB.sql and then click Open.
5. On the Query menu, click Execute.
6. Close SQL Query Analyzer.

Classroom setup
Module 9: Encrypting, Hashing, and Signing Data v


How to Teach This Module
This section contains information that will help you to teach this module.
Lesson: Encryption and Digital Signing Libraries
Although CAPICOM and the System.Security.Cryptography namespace
provide ways to perform some of the same cryptographic tasks, there are
features of each library that are mutually exclusive. For example, you can use
CAPICOM to work with certificates in the different certificate stores, but you
cannot use the System.Security.Cryptography namespace to do this. And you
can implement asymmetric encryption by using the
System.Security.Cryptography namespace, but not by using CAPICOM.
Briefly discuss each of the Windows
®
2000 Cryptographic Service Providers
(CSPs) and mention the algorithms that are supported by each CSP.
Cryptographic algorithms are discussed in more detail in the next topic.
You might mention that it is acceptable to employ a commonly used algorithm
that has a solid reputation. Remember that an attacker can be aware of the
algorithm that is used to encrypt the data, but unless the key is also known, it
will be virtually impossible to decrypt the data.
Recommend to the students that they hire a security professional to ensure the

correct usage of cryptography in their Web applications. Cryptography is a very
complex subject and this module covers only the basics.
Lesson: Using CAPICOM
Of the hashing algorithms that are supported by CAPICOM, SHA1 is
considered to be very good and it is the recommended algorithm.
After students have run the capicomHash.asp page, show the source code of the
Web page. There are four check boxes that use the four different hash
algorithms that are supported by CAPICOM. Point out how the length of the
SHA1 hash value is longer than the other hash algorithms.
Point out that you should use the Utilities.GetRandom method to create the
key.
Choosing a
Cryptography API
Windows 2000
Cryptographic Service
Providers
Choosing a
Cryptographic Algorithm
Hashing Data
Instructor-Led Practice:
Hashing Data Using
CAPICOM
Encrypting and
Decrypting Data
vi Module 9: Encrypting, Hashing, and Signing Data


After students have run the capicomEncrypt.htm and capicomDecrypt.asp Web
pages, show the source code of the pages:
1. In Microsoft Visual Studio

®
.NET, open the 2300Demos solution.
2. In Visual Studio .NET, in the Mod09 folder of the 2300Demos project, open
the capicomEncrypt.htm file.
The page has a text box that can be used for entering the data to be
encrypted and a Submit button that sends the data to the
capicomDecrypt.asp page.
3. In Visual Studio .NET, in the Mod09 folder of the 2300Demos project, open
the capicomDecrypt.asp file:
a. View the inline ASP code.
The capicomDecrypt.asp page first reads the string to be encrypted from
a form variable. The code then passes that string to the
EncryptTheString function, which returns the encrypted value. The
encrypted value is then passed to the DecryptTheString function, which
returns the decrypted value.
b. View the EncryptTheString function.
The EncryptTheString function has two parameters, the string that is
used to encrypt and an error flag. The EncryptTheString function uses
the EncryptedData object to encrypt the first parameter and then returns
the encrypted data to the calling ASP code. The key for encryption is
derived from the GetRandom method of the Utilities object and is then
stored in a Session variable; therefore, the key is valid only during the
session.
c. View the DecryptTheString function.
The DecryptTheString function has two parameters, the encrypted
string and an error flag. The DecryptTheString function uses the
EncryptedData object to decrypt the first parameter by using the key
that is stored in the Session variable. The function then returns the
decrypted data to the calling ASP code.


Instructor-Led Practice:
Encrypting and
Decrypting Data Using
CAPICOM
Module 9: Encrypting, Hashing, and Signing Data vii


When signing data, the process doing the signing (either the ASP process or the
ASPNET process, depending on where the code runs in a Web application)
must have access to the certificates.
To obtain a certificate from a different store, like the local computer store, and
to use that certificate to sign data, use the following code:
Function SignTheStringWithMachineCertificate()
Dim oSignedData
Set oSignedData = CreateObject("CAPICOM.SignedData")
oSignedData.Content = "Text to sign"

'open the local machine store
Dim Store
Set Store = CreateObject("CAPICOM.Store")
Store.Open(1) 'this opens the local machine store

'get the first certificate in the store
Dim Certificate
Set Certificate = Store.Certificates(1)

'sign the data
Dim strSignedData
Dim Signer
Set Signer = CreateObject("CAPICOM.Signer")

Signer.Certificate = Certificate
strSignedData = oSignedData.Sign(Signer)
End Function


Obtaining a certificate from a different store is beyond the scope of
Course 2300, Developing Secure Web Applications.

After students have run the capicomSign.asp and capicomVerify.asp Web
pages, show the source code of the pages:
1. In Visual Studio .NET, in the Mod09 folder of the 2300Demos project, open
the capicomSign.asp file.
The page has a text box that can be used for entering the data to be signed.
2. View the HTML for the page.
The Submit button calls the SignTheString function, which signs the data
in the txtClear text box. The signed data is stored in a Hidden field and is
then passed to the capicomVerify.asp page.
3. Open the capicomVerify.asp page and view the HTML.
The ASP code retrieves the signed data and then calls the
VerifyTheSignedString function.

Signing Data
Note
Instructor-Led Practice:
Signing Data Using
CAPICOM
viii Module 9: Encrypting, Hashing, and Signing Data


Lesson: Using the System.Security.Cryptography Namespace to

Hash Data
In this lesson, students will learn how to hash data by using the
System.Security.Cryptography namespace.
After explaining how to hash data by using the
System.Security.Cryptography namespace, talk about how to compare two
hashed values. Show the code at the end of the topic that loops through the
hashed values and compares each element.
After students have run the NEThashData.aspx page, show the source code of
the Web page:
1. In Visual Studio .NET, in the Mod09 folder of the 2300Demos project, open
the NEThashData.aspx file.
The page has a text box on a form that can be used for entering the data to
be hashed, and a second text box on the same form that can be used to enter
a second string for comparison.
2. In the code-behind page, view the cmdHash_Click event procedure.
The cmdHash_Click event procedure uses the SHA1Managed hash
algorithm to hash data in the txtClear text box on the form, and then
displays the hash of the data in a second text box.
3. In the code-behind page, view the cmdCompare_Click event procedure.
The cmdCompare_Click event procedure uses the SHA1Managed hash
algorithm to hash data in the txtCompare text box on the form, and then
compares the two hash values to determine whether they are equivalent.

Lab 9: Hashing Data
To start the lab, the instructor must update the TailspinToys Microsoft
SQL Server

database to change the data type of the Password field in the
Users table to be binary. Part of the database update process is to remove and
then re-create the Users table. Students must use a new page in the

TailspinToysAdmin Web application, CreateAccount, to create new reseller
accounts in the Users table. In the first exercise of the lab, students must add
the CreateAccount page to the TailspinToysAdmin Web application and update
the other files in the Web applications that interact with the Users table.
At the end of the lab, use SQL Server Enterprise Manager to show how
passwords are now stored in the Users table in a binary format.
Hashin
g
Data
Instructor-Led Practice:
Hashing Data
Module 9: Encrypting, Hashing, and Signing Data ix


Lesson: Using the System.Security.Cryptography Namespace to
Encrypt and Sign Data

The last lesson in this module is very complex and may be too advanced
for some students. You can skip the rest of the module if you are running short
on time.

It is important to note that the new key and initialization vector (IV) that are
generated by the Microsoft .NET Framework should be generated for every
session, and the key and IV should not be stored for use in a later session.
Discuss the algorithms that are supported by the symmetric encryption classes.
You might return to the topic “Choosing a Cryptographic Algorithm,” which
appeared earlier in this module, and discuss the differences between the
algorithms.
If students are unfamiliar with streams, you should begin with an explanation of
streams. Then, you can use the illustration on the slide to explain how the

stream-based objects work together to encrypt data.
The Stream class is the abstract base class of all streams. A stream is an
abstraction of a sequence of bytes, such as a file, an input/output device, an
interprocess communication pipe, or a Transmission Control Protocol/Internet
Protocol (TCP/IP) socket. The Stream class and its derived classes provide a
generic view of these different types of input and output, isolating the
programmer from the specific details of the operating system and the
underlying devices.
Streams involve three fundamental operations:
!
Read from streams. Reading is the transfer of data from a stream into a data
structure, such as an array of bytes.
!
Write to streams. Writing is the transfer of data from a data structure into a
stream.
!
Seeking. Seeking is the querying and modifying of the current position
within a stream. Seek capability depends on the kind of backing store (a
storage medium, such as a disk or memory) that a stream has. For example,
network streams have no unified concept of a current position, and
therefore, they typically do not support seeking.

There are four stream-based objects in the .NET Framework that can be used
with encryption: BufferedStream, FileStream, MemoryStream, and
NetworkStream. The examples in the lesson and demonstrations use a
MemoryStream object.
Use the illustration on the slide to explain how the stream-based objects work
together to decrypt data.
Note
Overview of Symmetric

Encr
y
ption
Performing Symmetric
Encryption
Performing Symmetric
Decryption
x Module 9: Encrypting, Hashing, and Signing Data


After students have viewed the NETSymmetricEncryption.aspx and
NETAsymmetricEncrpyption.aspx Web pages, show the source code of the
Web pages:
1. In Visual Studio .NET, in the Mod09 folder of the 2300Demos project, open
the NETSymmetricEncryption.aspx file.
The page has a text box on a form that can be used for entering the data to
be encrypted.
2. In the code-behind page, view the cmdEncrypt_Click event procedure.
The cmdEncrypt_Click event procedure converts the text in the txtClear
text box into a byte array, encrypts it by using a
DESCryptoServiceProvider object, and then stores the encrypted data in a
Session variable.
3. In the NETSymmetricEncryption.aspx.vb code-behind page, view the
cmdDecrypt_Click event procedure.
The cmdDecrypt_Click event procedure decrypts the encrypted data that is
stored in the Session variable by using the cmdEncrypt_Click event
procedure.
4. In Visual Studio .NET, open the NETAsymmetricEncryption.aspx.vb code-
behind page and view the following event procedures:
• cmdCreateKey_Click

• cmdEncrypt_Click
• cmdDecrypt_Click

You can run the NETAsymmetricEncryption.aspx page in the
Visual Studio .NET debugger to show the flow of the code.


Instructor-Led Practice:
Using Symmetric and
As
y
mmetric Encr
y
ption
Note
Module 9: Encrypting, Hashing, and Signing Data xi


The scenario of asymmetric encryption that is used in this topic and in the
asymmetric encryption demonstration page is to encrypt a symmetric
encryption key. Make sure this scenario is clear to the students.
In most cases, you will not need to use the CspParameters object. Every new
RSACryptoServiceProvider and DSACryptoServiceProvider class will
create a new temporary key container that will be deleted when the process
exits. You will want to use CspParameters in the following cases:
!
You need to persist the key; in this case, specify either the
KeyContainerName property or set the Flags property to
UseDefaultKeyContainer.
!

You are running as a service, or as a user without a profile (as in the case of
ASP.NET Web applications); in this case, you will want to set the Flags
property to UseMachineKeyStore.
In ASP.NET Web applications, you cannot use keys from the local user
store because the ASPNET user account does not have rights to read from
that store. To use the local computer store, you must have a user account
that the code is running under to read keys for that user and configure the
Web application to use impersonation (which was discussed in Module 4,
“Internet Information Services Authentication,” in Course 2300, Developing
Secure Web Applications).
!
You would like to use a non-default CSP, such as Gemplus smartcard CSP;
as such, you can specify the full provider name in the ProviderName.

Review how digital signing works, as introduced in Module 8, “Protecting
Communication Privacy and Data Integrity,” in Course 2300, Developing
Secure Web Applications.
Before a digital signature can be verified, you must have the public key of the
user who signed the data, the digital signature, the data that was signed, and the
hash algorithm that was used by the signer.
After students have run the NETSigning.aspx Web page, show the source code
of the Web page. The cmdSign_Click event procedure uses the
RSACryptoServiceProvider object to create a key pair and store it in a key
container named SignKeyContainer. The digital signature is stored in a
Session variable so that it can be verified by the cmdVerifyHashSig_Click
event procedure.
Performing Asymmetric
Encryption
Si
g

nin
g
Data
Verifying a Signature
Instructor-Led Practice:
Si
g
nin
g
Data
xii Module 9: Encrypting, Hashing, and Signing Data


Customization Information
This section identifies the lab setup requirements for a module and the
configuration changes that occur on student computers during the labs. This
information is provided to assist you in replicating or customizing Microsoft
Official Curriculum (MOC) courseware.
Lab Setup
To complete this lab, the TailspinToys database, on the Glasgow computer,
must be updated to change the data type of the Password field in the Users
table to be binary. In Exercise 1, students will update the files in the
TailspinToys and TailspinToysAdmin Web applications that interact with the
Users table in the TailspinToys database.
!
Configure SQL Server on Glasgow
• If you did not perform the “Adding Roles and Logins to SQL Server”
demonstration in Module 7, “Securing Microsoft SQL Server,” in Course
2300, Developing Secure Web Applications, you must do it now.


!
Update the TailspinToys database (Glasgow computer only)
On the Glasgow computer, run an SQL script to change the data type of the
Password field in the Users table to be binary:
1. On the Start menu, click Programs, click Microsoft SQL Server, and then
click Query Analyzer.
2. In the Connect to SQL Server dialog box, type (local) in the SQL Server
box, click Start SQL Server if it is stopped, click Windows
Authentication, and then click OK.
3. On File menu, click Open.
4. In the Open Query File dialog box, in the File name box, type
C:\Program Files\Msdntrain\2300\Labfiles\Lab09\database\
update2300DB.sql and then click Open.
5. On the Query menu, click Execute.
6. Close SQL Query Analyzer.

To complete this lab, students can continue working in the Tailspin Toys
Visual Studio .NET projects that they used in previous labs, or they can start
with new files.
To start with new files, students must complete the following steps.
!
Create the Web applications for the ASP exercises
1. Copy all of the contents of the ASP starter folder install_folder\Labfiles\
Lab09\ASP\Starter\TailspinToys to the TailspinToys Internet Information
Services (IIS) virtual directory at C:\Inetpub\wwwroot\TailspinToys.
2. Copy all of the contents of the ASP starter folder install_folder\Labfiles\
Lab09\ASP\Starter\TailspinToysAdmin to the TailspinToys IIS virtual
directory at C:\Inetpub\wwwroot\TailspinToysAdmin.

Module 9: Encrypting, Hashing, and Signing Data xiii



!
Create the Web applications for the ASP.NET exercises
1. Copy all of the contents of the ASP.NET folder install_folder\Labfiles\
Lab09\ASPXVB\Starter\TailspinToys.NET to the TailspinToys.NET IIS
virtual directory at C:\Inetpub\wwwroot\TailspinToys.NET.
2. Copy all of the contents of the ASP.NET folder install_folder\Labfiles\
Lab09\ASPXVB\Starter\TailspinToysAdmin.NET to the
TailspinToysAdmin.NET IIS virtual directory at C:\Inetpub\wwwroot\
TailspinToysAdmin.NET.
3. Edit the file c:\Inetpub\wwwroot\TailspinToysAdmin.NET\Web.config and
change the <allow roles="London\TailspinAdmins"/> tag to be <allow
roles="machineName\TailspinAdmins"/>, where machineName is the name
of your computer.

!
Configure IIS authentication
1. Run the IIS administrative tool.
2. Expand the computer node and the Default Web Site node in the tree.
3. Right-click the TailspinToysAdmin virtual directory, and then click
Properties.
4. Click Directory Security.
5. In the Anonymous access and authentication control group, click Edit.
6. Clear the Anonymous access check box.
7. Click OK twice to save your changes.
8. Right-click the TailspinToysAdmin.NET virtual directory, and then click
Properties.
9. Click Directory Security.
10. In the Anonymous access and authentication control group, click Edit.

11. Clear the Anonymous access check box.
12. Click OK twice to save your changes.

Lab Results
Performing the labs in this module introduces the following configuration
changes:
1. The CreateAccount.asp and UsersDB.inc pages are added to the private
folder of the TailspinToysAdmin Web application.
2. A new version of the UsersDB.inc page is added to the TailspinToys Web
application.
3. The CreateAccount.aspx page is added to the private folder of the
TailspinToysAdmin.NET Web application.
4. New versions of the Tailspin_ReadDBUtils and Tailspin_WriteDBUtils
class libraries are placed in the C:\Documents and Settings\2300Student\
My Documents\Visual Studio Projects\2300Labs.NET folder.


Module 9: Encrypting, Hashing, and Signing Data 1


Overview
!
Encryption and Digital Signing Libraries
!
Using CAPICOM
!
Using the System.Security.Cryptography Namespace to
Hash Data
!
Using the System.Security.Cryptography Namespace to

Encrypt and Sign Data

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
You can strengthen the security of your Web applications by incorporating the
programmatic use of cryptography. Depending on your programming platform,
you will use one of several cryptographic libraries to add encryption, hashing,
and digital signing functionality to your Web application.

Cryptography is a vast subject, and not all aspects of cryptography are
covered in this module. For example, this module does not cover Microsoft
®

Authenticode
®
, which allows developers to include information about
themselves and their code with their programs through the use of digital
signatures. For more information about cryptography, search for
“Cryptography” in the Platform software development kit (SDK).

After completing this module, you will be able to:
!
Choose the most appropriate cryptographic library for a given programming
platform.
!
Use CAPICOM to encrypt, decrypt, hash, and sign data in an Active Server
Pages (ASP) application.

!
Use the System.Security.Cryptography namespace to hash data in a
Microsoft

ASP.NET Web application.
!
Use the System.Security.Cryptography namespace to encrypt and decrypt
data by using both symmetric and asymmetric encryption, and sign data in
an ASP.NET Web application.


The code samples in this module are provided in both Microsoft
Visual Basic
®
.NET and C#.

Introduction
Note
Objectives
Note
2 Module 9: Encrypting, Hashing, and Signing Data


Lesson: Encryption and Digital Signing Libraries
!
Choosing a Cryptography API
!
Windows 2000 Cryptographic Service Providers
!
Choosing a Cryptographic Algorithm


*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
There are a number of cryptographic libraries that you can use to add
cryptography to a Web application. The cryptographic library that you choose
to use in your Web applications will depend on your programming background
and the platform that you are developing your Web application on.
After completing this lesson, you will be able to:
!
Select a method of encryption and data verification, including CryptoAPI,
CAPICOM, and the System.Security.Cryptography namespace.
!
Describe the Cryptographic Service Providers (CSPs) that are provided by
Microsoft Windows
®
2000.
!
Select a hashing and encryption algorithm from a set of industry-standard
algorithms.

Introduction
Lesson ob
j
ectives
Module 9: Encrypting, Hashing, and Signing Data 3



Choosing a Cryptography API
CAPICOM
CAPICOM
System.Security.Cryptography
System.Security.Cryptography
Namespace
Namespace
CryptoAPI
CryptoAPI
Cryptographic Service Providers
Cryptographic Service Providers
!
Download CAPICOM from
!
Register the CAPICOM DLL with regsvr32

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
A CSP contains implementations of cryptographic standards and algorithms. At
least one CSP is required with each Web application that uses cryptographic
functions. A single application can occasionally use more than one CSP.
Each CSP provides a different implementation of the cryptographic support that
is provided to CryptoAPI. Some CSPs provide stronger cryptographic
algorithms, whereas others contain hardware components, such as smart cards.
CryptoAPI, CAPICOM, and the System.Security.Cryptography namespace
are the application programming interfaces (APIs) that you use to interact with
a CSP. CAPICOM and the System.Security.Cryptography namespace share

some, but not all, of the same cryptographic features. You should use the API
that best meets the needs of your Web application.
A CSP implements cryptographic standards and algorithms through a dynamic-
link library (DLL) that implements the functions in CryptoSPI (a system
programming interface). Most CSPs implement of all of their own functions;
however, some CSPs implement their functions mainly in a Windows-based
service program that is managed by the Windows service control manager.
Others CSPs implement functions in hardware, such as a smart card or secure
coprocessor. If a CSP does not implement its own functions, the DLL acts as a
pass-through layer, thereby facilitating the communication between the
operating system and the actual CSP implementation.
CryptoAPI is an unmanaged API that provides services that you can use to add
cryptography to Windows-based applications. CryptoAPI includes the
functionality that can be used for encrypting and decrypting data, hashing data,
creating digital signatures, and interacting with digital certificates.
Introduction
Cryptographic Service
Providers
Cr
y
ptoAPI
4 Module 9: Encrypting, Hashing, and Signing Data


CAPICOM is a Component Object Model (COM) component that is built on
CryptoAPI and provides cryptographic services, such as encrypting and
decrypting data, hashing data, and interacting with digital certificates.
CAPICOM requires one of the following system configurations:
!
Microsoft Windows 98 or later, with Microsoft Internet Explorer version 5

or later
!
Microsoft Windows NT
®
version 4.0 with Service Pack 4 or later

CAPICOM is available as a redistributable file that can be downloaded from

Before you can use CAPICOM, you must register the Capicom.dll, as shown in
the following example:
regsvr32 CAPICOM.dll

The Microsoft .NET Framework provides a managed wrapper for CryptoAPI
called the System.Security.Cryptography namespace that you can use if you
are building a Web application that will run on Microsoft .NET.
The System.Security.Cryptography namespace provides cryptographic
services, including secure encryption and decryption of data, hashing of data,
random number generation, and message authentication.
The classes in the .System.Security.Cryptography namespace manage many
details of cryptography for you. Some classes are wrappers for the unmanaged
CryptoAPI, whereas other classes are purely managed implementations.
CAPICOM
System.Security.Crypto
graphy namespace
Module 9: Encrypting, Hashing, and Signing Data 5


Windows 2000 Cryptographic Service Providers
!
Microsoft Base Cryptographic Provider

!
Microsoft Strong Cryptographic Provider
!
Microsoft Enhanced Cryptographic Provider
!
Microsoft DSS Cryptographic Provider
!
Microsoft Base DSS and Diffie-Hellman Cryptographic
Provider
!
Microsoft Base DSS and Diffie-Hellman/Schannel
Cryptographic Provider
!
Microsoft RSA/Schannel Cryptographic Provider
!
Schlumberger CSP and GEMPlus CSP

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
CryptoAPI implements cryptographic operations by calling CSPs. When you
perform a cryptographic operation programmatically, you use a specific CSP.
Windows 2000 supplies the CSPs that are described in the following table.
CSP Description

Microsoft Base
Cryptographic Provider
Supports data encryption and digital signatures by using

the following algorithms: Rivest-Shamir-Adleman
(RSA), RC2, RC4, Message Digest Algorithm 5 (MD5),
and Secure Hash Algorithm (SHA-1).
Microsoft Strong
Cryptographic Provider
Supports all of the algorithms that are in the Microsoft
Enhanced Cryptographic Provider; however, the key
lengths are the same as in the Microsoft Base
Cryptographic Provider. This CSP supports the RSA,
Data Encryption Standard (DES), Triple-DES, RC2,
RC4, MD5, and SHA-1 algorithms.
Microsoft Enhanced
Cryptographic Provider
Supports stronger security through longer keys and
additional algorithms than the Microsoft Base
Cryptographic Provider. This CSP supports the RSA,
DES, Triple-DES, RC2, RC4, MD5, and SHA-1
algorithms.
Microsoft DSS
Cryptographic Provider
Supports hashing, data signing, and signature
verification by using the SHA-1 and Digital Signature
Standard (DSS) algorithms.
Microsoft Base DSS and
Diffie-Hellman
Cryptographic Provider
A superset of the Microsoft DSS Cryptographic
Provider that also supports Diffie-Hellman key
exchange, hashing, data signing, and signature
verification by using the SHA-1 and DSS algorithms.


Introduction
CSPs provided by
Windows 2000
6 Module 9: Encrypting, Hashing, and Signing Data


(continued)
CSP Description

Microsoft Base DSS and
Diffie-Hellman/Schannel
Cryptographic Provider
The same as the Microsoft Base DSS and Diffie-
Hellman Cryptographic Provider, but it is used for SSL3
and TLS1 protocols when the application uses Diffie-
Hellman key exchange.
Microsoft RSA/Schannel
Cryptographic Provider
Similar to the Microsoft Base DSS and Diffie-
Hellman/Schannel Cryptographic Provider in that it
works with SSL3 and TLS1, but it uses the RSA suite o
f

algorithms rather than Diffie-Hellman.
Schlumberger CSP and
Gemplus CSP
Used with smart cards.



For more information about public key algorithms, symmetric encryption
algorithms, and hash algorithms, see the Microsoft MSDN
®
article “Supported
Algorithms.”

Note
Module 9: Encrypting, Hashing, and Signing Data 7


Choosing a Cryptographic Algorithm
!
Hashing algorithms
"
MD2, MD4, MD5, and SHA-1
"
Proposed algorithms SHA-256, SHA-384, and SHA-512
!
Symmetric encryption algorithms
"
DES, RC2, Triple-DES, and Rijndael (or AES)
!
Asymmetric encryption algorithm
"
RSA

*****************************
ILLEGAL FOR NON
-
TRAINER USE

******************************
The goal of every algorithm is to make it as difficult as possible to decrypt the
generated ciphertext (or a message that has been encrypted) without using the
key. When selecting an encryption algorithm, it is often a good idea to choose
one that has been in use for a while, and that has successfully resisted all
attacks.
Some decisions that you need to make when choosing an algorithm include:
!
Do you want speed or stronger security?
!
Do you need the result of the hash to be a limited length?
!
Do you need to encrypt a small piece of data or a binary large object
(BLOB)?

For example, the Triple-DES algorithm is faster than Rijndael, but Rijndael is
more secure. Or, if you want to encrypt data that will lose its importance fast
(for example, stock quotes), you could use DES, as long as you change the key
often.
The following table describes the different algorithms that you can use for
hashing.
Hash algorithm Description

MD2 Creates a 128-bit hash value. This algorithm was optimized for use
with 8-bit computers.
MD4 Creates a 128-bit hash value. This algorithm was optimized for
32-bit computers, but it is now considered flawed because
collisions can be found too quickly.
MD5 Creates a 128-bit hash value. This algorithm was optimized for
32-bit computers.

SHA-1 Creates a 160-bit hash value. This algorithm is a standard hashing
algorithm developed by the National Institute of Standards and
Technology (NIST) and by the National Security Agency (NSA).
Introduction
Hashing algorithms
8 Module 9: Encrypting, Hashing, and Signing Data


Currently, SHA-1 is the preferred hash algorithm. NIST has proposed three new
variations of SHA-1: SHA-256, SHA-384, and SHA-512, which produce larger
hash values.

For more information about the proposed hash algorithms, go to the
Web site.

The following table describes the different algorithms that you can use for
symmetric encryption.
Symmetric encryption
algorithms
Description

DES Uses 56-bit keys. This algorithm was developed about 25
years ago, and it is vulnerable to a brute-force attack in
which an attacker tries all key values.
RC2 Uses a variable-length key (8 bits to 128 bits) and a 64-bit
block. This algorithm is easy to implement on a 16-bit
computer and was designed for bulk encryption.
Triple-DES A variant of DES that uses DES three times with three
different keys. Triple-DES is stronger than DES, but it is
slower than other block ciphers.

Rijndael (or AES) Uses a 128-bit block size and 128-bit, 192-bit, or 256-bit
keys. This algorithm is approved by NIST and performs
very well in hardware and software implementations.

Private key algorithms, called block ciphers, are typically used to encrypt one
block of data at a time. Block ciphers (like RC2, DES, TripleDES, and
Rijndael) cryptographically transform an input block of n bytes into an output
block of encrypted bytes. If you want to encrypt or decrypt a sequence of bytes,
you must do it block by block. Because the size of n is small (n = 8 bytes for
RC2, DES, and TripleDES; n = 16 bytes (the default); n = 24 bytes; or n = 32
bytes for Rijndael), values larger than n must be encrypted one block at a time.
RSA is the most commonly used asymmetric encryption algorithm. This
algorithm can be used both for encryption and for digital signatures. The key
size should be greater than 1,024 bits for a reasonable margin of security. For
example, keys of size 2,048 bits should be given security for decades.

For more information about cryptographic algorithms, see the SSH
Communications Security Web site at
algorithms.html.

Note
Symmetric encryption
al
g
orithms
Asymmetric encryption
algorithms
Note
Module 9: Encrypting, Hashing, and Signing Data 9



Lesson: Using CAPICOM
!
Hashing Data
!
Instructor-Led Practice: Hashing Data Using CAPICOM
!
Encrypting and Decrypting Data
!
Instructor-Led Practice: Encrypting and Decrypting
Data Using CAPICOM
!
Signing Data
!
Instructor-Led Practice: Signing Data Using CAPICOM

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
CAPICOM is a COM component that exposes cryptographic and x.509
certificate-based functionality in several easy-to-use objects. CAPICOM is built
on CryptoAPI. CAPICOM can be used in applications that are created in many
programming languages, including Microsoft Visual Basic
®
, Microsoft
Visual Basic .NET, Microsoft Visual Basic, Scripting Edition (VBScript), C++,
and C#, to perform fundamental cryptographic tasks, such as encrypting and
decrypting data, hashing data, using digital certificates, signing and verifying

data by using Authenticode, generating random numbers, and performing
base64 encoding and decoding on data.
You can use CAPICOM in both ASP and ASP.NET Web applications.

For more information about using CAPICOM, search for the topic
“CAPICOM” in the Platform SDK documentation.

After completing this lesson, you will be able to:
!
Hash data by using CAPICOM.
!
Encrypt and decrypt data by using CAPICOM.
!
Sign data by using CAPICOM.

Introduction
Note
Lesson objectives
10 Module 9: Encrypting, Hashing, and Signing Data


Hashing Data
Dim oHash, hxHashedData
Set oHash = CreateObject("CAPICOM.HashedData")
oHash.Algorithm = 0 'SHA1
oHash.Hash strClearText
hxHashedData = oHash.Value
Dim oHash, hxHashedData
Set oHash = CreateObject("CAPICOM.HashedData")
oHash.Algorithm = 0 'SHA1

oHash.Hash strClearText
hxHashedData = oHash.Value
!
Hash algorithms
"
SHA1, MD2, MD4, MD5
!
Using the HashedData object
!
Using the Utilities object
Dim oUtils, binHashedData
Set oUtils = CreateObject("CAPICOM.Utilities")
binHashedData = oUtils.HexToBinary(hxHashedData)
Dim oUtils, binHashedData
Set oUtils = CreateObject("CAPICOM.Utilities")
binHashedData = oUtils.HexToBinary(hxHashedData)

*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
A hash value is a digital fingerprint of data. A hash value is a unique and
extremely compact numerical representation of a piece of data. If you hash a
paragraph of plain text and change even one letter of the paragraph, a
subsequent hash will produce a different value. It is computationally
improbable to find two distinct inputs that hash to the same value.
A hash value is derived by applying a mathematical algorithm on arbitrary-
length binary data. These mathematical algorithms are called hash functions.
The result is a fixed-length hash value, which is then associated with the

original data.
You can use the HashedData object to hash a string. The HashedData object
supports the following hash algorithms:
!
SHA1 (the default)
!
MD2
!
MD4
!
MD5

The HashedData object provides a Hash method to hash data. You set the
Algorithm property to the hash algorithm and then call Hash method by
passing in the data to be hashed. The result of the hash, a hexadecimal string, is
stored in the Value property of the HashedData object.
Introduction
HashedData object
Module 9: Encrypting, Hashing, and Signing Data 11


The following example hashes data from a text box that is on a form by using
the SHA1 algorithm. The Hash method takes a string as a parameter. You
reference the Value property of the HashedData object to retrieve the hashed
data, which is a string that contains a hexadecimal value, as shown in the
following code:
<%
Dim oHash
Dim hxHashedData
Set oHash = CreateObject("CAPICOM.HashedData")

oHash.Algorithm = 0 'use SHA1
oHash.Hash strClearText
hxHashedData = oHash.Value
%>

CAPICOM has a Utilities class with utility methods that can be used to convert
the hexadecimal string to formats. For example, the HexToBinary method
converts the value into a binary format, as shown in the following code:
<%
Dim oUtils
Dim binHashedData
Set oUtils = CreateObject("CAPICOM.Utilities")
binHashedData = oUtils.HexToBinary(hxHashedData)
%>

Example

×