©2004 (harteris plc

Cbarteri. !bite Paper
Cryptographic Algorithms -
Guidance for Developers
Version 1.0
(hris Searv
1¯ September 2004



1¯ September 2004
Version 1.0
(rvptographic Algorithms: Guidance lor De·elopers Page 2 oí 29

CON1LN1S
CON1LN1S 2
J. IN1RODUC1ION 3
J.J Summary 3
J.2 Glossary 4
2. 1HL NLLD IOR CRYP1OGRAPHY 5
3. GLNLRAL APPROACH 1O USING CRYP1OGRAPHY 7
3.1.1 (onstruction oí Algorithms ¯
3.1.2 (omputing Power and Algorithms ¯
3.1.3 Kev Liíetimes ¯
3.1.4 Svmmetric ·s Asvmmetric ¯
3.1.5 \hen to Use (rvptographic lunctions ¯
3.1.6 (oníigurabilitv 8
3.1.¯ Storing Secrets 9
3.1.8 Generating Random Numbers 9
4. HASHING JJ
4.J Overview JJ
4.2 Algorithms JJ
4.3 Recommendations J2
5. SYMML1RIC CRYP1OGRAPHY J4
5.J Overview J4
5.1.1 Llectronic (ode Book Mode L(B, 15
5.1.2 (ipher Block (haining (B(, 15
5.1.3 (ipher leedback mode (lB, 16
5.1.4 Stream (iphers 16
5.1.5 Block Padding 16
5.1.6 Kev Size 16
5.1.¯ Kev Generation 16
5.2 Algorithms J7
5.2.1 Data Lncrvption Standard DLS, 1¯
5.2.2 1riple DLS 3DLS, 1¯
5.2.3 Ad·anced Lncrvption Standard ALS, 1¯
5.2.4 R(2 1¯
5.3 Recommendations J8
6. ASYMML1RIC CRYP1OGRAPHY 20
6.J Overview 20
6.1.1 Kev Lxchange 20
6.1.2 Non-repudiation 20
6.2 Algorithms 2J
6.3 .NL1 Asymmetric Lncryption classes 2J
6.4 CAPICOM 22
6.5 1he Windows Certificate Store 24
6.6 Recommendations 24
7. QUICK GUIDL 26
8. BIBLIOGRAPHY 28



1¯ September 2004
Version 1.0
(rvptographic Algorithms: Guidance lor De·elopers Page 3 oí 29

J. IN1RODUC1ION
J.J Summary
Guidance on the usage oí crvptographv is necessarv íor all de·elopers as the onlv trulv secure
application is one that is designed and coded to be secure. and the use oí crvptographv is a kev element
in ensuring this.
Much oí the iníormation a·ailable íor the .NL1 crvptographic classes is gi·en in isolation and írom a
purelv technical point oí ·iew. Anv de·eloper applving such iníormation without considering the
broader context is in danger oí creating a serious securitv hole.
Uníortunatelv. there are íew simple guides a·ailable to assist the de·eloper in gaining an o·er·iew oí
the approach s´he should adopt when using crvptographic algorithms in the Microsoít de·elopment
en·ironments. 1his paper is intended to be a primer íor de·elopers to bridge this gap. \hilst some
detail regarding the crvptographic principles is pro·ided. this is done onlv to support the main íocus:
setting out a pragmatic approach to using crvptographv in general and pro·iding speciíic
recommendations on lashing. Asvmmetric (rvptographv and Svmmetric (rvptographv.
1he content assumes the user is de·eloping in (4 or Visual Basic.NL1. using the .NL1 íramework
·ersion 1.1.
It is important that the reader re·iews the subject oí crvptographv at regular inter·als. 1he industrv
standards. such as the new Ad·anced Lncrvption Standard and SlA512. are continuallv being
enhanced to ensure that it can be relied upon íor the íuture. As these become accepted thev íind their
wav into en·ironments such as the .NL1 íramework.
A Ouick Guide íor De·elopers has been included at the back oí the document - this should be read in
conjunction with all oí the rele·ant Recommendations`.


1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 4 oí 29


J.2 Glossary
PKI Public Kev Inírastructure. 1his is a centralised trusted authoritv íor
authentication. using asvmmetric crvptographv and certiíicates. It enables
both authentication and digital signatures.
Algorithm A step bv step procedure - tvpicallv an established computation íor sol·ing
a problem within a set number oí steps
Cryptographic
Algorithm
A procedure íor carrving out encrvption
Cryptographic
Iunction
See (rvptographic Algorithm
Secret A piece oí iníormation that must not be disclosed. 1vpicallv a kev íor
encrvption´decrvption
Digest Another name íor a hash see section 4,
Attack Using crvptanalvsis or other techniques to íind either plaintext or a
crvptographic kev
Crack 1o successíullv obtain either a kev or the original plaintext írom a piece oí
ciphertext or one oí the asvmmetric kevs
Plaintext A piece oí iníormation in its normal state. beíore being encrvpted
Ciphertext 1he encrvpted ·ersion oí a piece oí iníormation
Cipher lor the purposes oí this document. a crvptographic algorithm
Lncryption Applving an algorithm to a piece oí iníormation so that it can onlv be read
bv the holder oí the appropriate kev secret or pri·ate,. 1his is an arbitrarv
deíinition íor the purposes oí this document.




1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 5 oí 29

2. 1HL NLLD IOR CRYP1OGRAPHY
De·elopers need to emplov crvptographv to address potentiallv hostile or sometimes unintentional,
misuse oí the applications being de·eloped. 1he nature oí this misuse. or the threat`. can be broken
down into íour íundamental tvpes:
♦ Masquerading
♦ Unauthorised interception
♦ Unauthorised modiíication
♦ Interruption
(rvptographv can be emploved to address the íirst three oí these threats bv ensuring. respecti·elv:
♦ Authenticitv
♦ Pri·acv
♦ Integritv
1he corollarv oí Interruption is to ensure A·ailabilitv. lowe·er. crvptographv does not tvpicallv plav a
central role in pro·iding the mechanisms to ensure a·ailabilitv.
1he o·erall threat picture can be ·isualised as íollows:
Masquerade
Authorised User or Datastore Authorised User or Datastore
Normal 1ransmission or
1ransaction
Interception
Modiíication Interruption
A
u
t
h
e
n
t
i
c
i
t
v
I
n
t
e
g
r
i
t
v
P
r
i
·
a
c
v
A
·
a
i
l
a
b
i
l
i
t
v




1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 6 oí 29

An email sent that purports to be írom a ·alid user but is in íact sent bv another partv pretending to be
that user is an example oí a masquerade. (rvptographv is used here in the íorm oí a digital signature.
which is checked bv the recei·er and ·alidated against a trusted authoritv see section 6.1.2,.
Ií an intruder used tools such as network monitor to spv on traííic across the network. this would be
an example oí interception. 1his can be countered bv using crvptographv to encrvpt the message so
that it cannot be read without the correct decrvption kev see section 5.1,.
Another intruder might intercept a message. alter it. and then send it on to the intended recipient. 1his
would be an example oí modiíication. (rvptographv can counter this bv including a hash oí the
original message. so that the two can be compared and integritv guaranteed ií thev correspond see
section 4.1,.



1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page ¯ oí 29

3. GLNLRAL APPROACH 1O USING CRYP1OGRAPHY
1his section sets out what (harteris íeels is best practice when de·elopers are considering the use oí
crvptographv in general. Later sections deal with speciíic recommendations around the detailed
implementation oí lashing. Asvmmetric and Svmmetric crvptographv.
3.1.1 Construction of Algorithms
De·elopers should not attempt to implement their own encrvption algorithms. It is unlikelv that a
de·eloper would be able to create an algorithm that is both saíe and gi·es the períormance oí
implementations oí the industrv standard algorithms alreadv pro·ided bv Microsoít. Also. there is no
beneíit to be achie·ed írom creating a new algorithm.
3.1.2 Computing Power and Algorithms
It is important to re·iew anv document recommending crvptographic techniques írequentlv. as the
increase in processing power oí computers can render crvptographic methods and algorithms more
·ulnerable to attack o·er time.
As mathematical knowledge progresses. ílaws can be íound in algorithms which reduce their
eííecti·eness. A search on the internet will íind a great deal oí discussion on the Ad·anced Lncrvption
Standard section 5.2.3,. 1his doesn`t necessarilv indicate that this is a ílawed algorithm. it rather points
to the íact that more scrutinv is placed on ALS simplv because it is becoming the industrv standard.
3.1.3 Key Lifetimes
Do not relv on one kev íor too long. Kevs can be retrie·ed through crvptanalvsis. and so kevs should
be changed at regular inter·als.
1here are a number oí íactors that aííect how oíten a kev should be changed:
♦ 1he coníidentialitv needed íor the data being protected
♦ 1he length oí the kev in use the size oí the kev space,
♦ 1he relati·e strength oí the encrvption algorithm in use
Bear in mind that it mav be necessarv to keep a copv oí anv kevs that reach the end oí their liíetime.
otherwise it will be impossible to reco·er anv data that was encrvpted using the old kevs.
3.1.4 Symmetric vs Asymmetric
Asvmmetric algorithms are not stronger than svmmetric algorithms - íor most oí the commonlv used
ciphers. the opposite is true. In íact. the nature oí asvmmetric algorithms means that no plaintext is
required to break an asvmmetric cipher.
Asvmmetric algorithms are also slower computationallv than svmmetric see J&J lenghi work entitled
Secure Networking with \indows 2000 and 1rust Ser·ices. íor íurther detail and some numbers,.
lor this reason. asvmmetric íunctions are best used íor kev exchange and digital signatures.
3.1.5 When to Use Cryptographic Iunctions
1here are manv uses oí crvptographv within \indows that are períormed automaticallv. Some
examples are:
♦ Negotiation oí SSL with client and ser·er side certiíicates. 1his is achie·ed through coníiguration
oí Internet Iníormation Ser·er IIS,. It works at the application le·el and allows integration with
the N1lS íile svstem securitv.
♦ Lncrvption using secret kevs within Kerberos. Anv workstation or ser·er that can connect to the
Kev Distribution (entre íor the domain can take ad·antage oí this transparentlv.
♦ (hallenge-handshake protocols íor authentication. 1his is a·ailable through Routing and Remote
Access RRAS,



1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 8 oí 29

♦ Negotiation oí secure point to point communications ·ia IPSec. Anv communication across the
wire can ha·e integritv and´or encrvption using this technologv.
♦ 1he Lncrvpted lile Svstem LSl, allows data to be encrvpted as it is sa·ed bv a user. Onlv the
same user and the Reco·erv Agent can decrvpt the data.
♦ SSL can be used bv the Net Libraries oí SOL Ser·er to encrvpt anv communications between
client and database ser·er
♦ Use oí S´MIML within email clients. 1his is also built into Ser·er tools such as Biz1alk.
It is best to allow \indows to períorm these tasks. Bear in mind that the \indows operating svstem
has been certiíied bv independent securitv accreditation bodies.
Ií using the \indows implementations. take into account that there is a certain amount oí
coníiguration necessarv to ensure securitv. lor instance. S´MIML a protocol used íor email securitv,
deíaults to 40 bit R(2. Make sure that this is set to use 3DLS ií vour application relies on email.
Also keep in mind the exact nature oí the protection aííorded bv \indows ser·ices. lor instance.
IPSec will onlv gi·e point-to-point coníidentialitv´integritv between machines, - it will not gi·e end-
to-end protection.
An example oí end-to-end protection is PGP. a secure email application. Lncrvption takes place at the
application le·el. and anv data sa·ed to disc is encrvpted.
Microsoít produces a number oí ·erv good reíerences íor securing its products - it is important to
research anv íunctionalitv that vou wish to relv upon to make sure that it is coníigured saíelv.
1here would ha·e to be a ·erv pressing reason íor a de·eloper to code this íunctionalitv. but there mav
be times when it necessarv. Ií it is íelt that deíault \indows securitv íunctionalitv in·ol·ing
crvptographv is not appropriate. ad·ice should be obtained írom indi·iduals either internal or
external, with appropriate securitv expertise beíore creating similar íunctionalitv. lurther independent
accreditation oí anv work undertaken mav be necessarv - this can be ·erv expensi·e and time
consuming. Alwavs look to certiíied third partv products íirst beíore undertaking these sorts oí
implementations.
An example oí where the existing \indows íunctionalitv mav not be appropriate could be íor the
storage oí X509 certiíicates on client workstations that are not secured see section 6.4 íor more
details,. Some public sector organisations ha·e created their own certiíicate stores to o·ercome some
oí the \indows limitations. 1his allows digital signatures to be used bv the general public ·ia the
internet. 1his is a diííicult route. as a high degree oí ·erv expensi·e and time-consuming certiíication
has to be undertaken.
3.1.6 Configurability
In order to make applications íuture prooí. it is recommended that anv code using crvptographic
libraries be as coníigurable as possible.
1his is oíten achie·ed bv instantiating a base algorithm class and allowing alteration oí the particular
algorithm ·ia coníiguration. Lxamples are shown oí this elsewhere in the document.
Make sure that anv coníiguration iníormation is secure - securitv could be compromised ií an attacker
was able to change required kev lengths írom 128 bit to 40 bit.
1he deíault implementations returned bv the (reate method oí the SvmmetricAlgorithm and
lashAlgorithm classes can be coníigured within machine.coníig as íollows:

·coníiguration·
·!-- Other coníiguration settings. --·
·mscorlib·
·crvptographvSettings·



1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 9 oí 29

·crvptoNameMapping·
·crvpto(lasses·
·crvpto(lass MvSlA1lash~"MvSlA1lash(lass. MvAssemblv
(ulture~'en'. PublicKev1oken~a5d015c¯d5a0b012.
Version~1.0.0.0"´·
·´crvpto(lasses·
·nameLntrv name~"SlA1" class~"MvSlA1lash"´·
·nameLntrv name~"Svstem.Securitv.(rvptographv.SlA1"
class~"MvSlA1lash"´·
·nameLntrv name~"Svstem.Securitv.(rvptographv.lashAlgorithm"
class~"MvSlA1lash"´·
·´crvptoNameMapping·
·´crvptographvSettings·
·´mscorlib·
·´coníiguration·

3.1.¯ Storing Secrets
A secret can be anv iníormation that should be kept coníidential such as a connection string íor a
database,. but in this paper it generallv reíers to pri·ate or session kevs used in crvptographv. Kev
exchange using an asvmmetric algorithm sa·es ha·ing to store svmmetric kevs íor encrvpting
communication sessions. but there mav be occasions when a svmmetric kev needs to be sa·ed see
Building Secure ASP.NL1 Applications`,. lowe·er. the golden rule is to a·oid ha·ing to store
secrets in the íirst place.
Ií it is absolutelv necessarv. there are a number oí wavs to store secrets:
♦ Using \indows DPAPI
♦ Storing a hash oí the secret. rather than the secret itselí
♦ Kev Lscrow
lowe·er. there are wavs that secrets should ne·er be stored.
♦ Do not think that bv storing something in a place that no-one will look will guarantee saíetv íor
instance. a strangelv named íile,.
♦ Do not think that bv obíuscating the access to the secret that it is saíe.
1his is called securitv bv obscuritv`. and is held in ·erv low regard bv the I1 securitv communitv.
Remind de·elopers oí this whene·er thev choose not to show vou their source code because oí
securitv reasons`.
Obíuscation is used in the protection oí Intellectual Propertv Rights bv making code harder to re·erse
engineer. Do not make the mistake oí thinking that it will gi·e anv securitv to iníormation being used
bv the application.
Do not pass secrets around írom machine to machine. 1he more places that a secret is stored. the
more likelv it will be retrie·ed.
3.1.8 Generating Random Numbers
Generating random numbers íor svmmetric algorithms. obtaining ·alues such as the secret kev or
initialisation ·ector should be undertaken using the RNG(rvptoSer·icePro·ider class in .NL1. 1his is
a wrapper class around the \indows (rvptoAPI. 1he deíault implementation returned bv the
RandomNumberGenerator.(reate method can be coníigured ·ia (rvpto(oníig see section 3.1.6,. 1he
standard deíault is the RNG(rvptoSer·icePro·ider. Standard random number generation íunctions.
such as rava. are not as random as thev mav seem. so thev cannot be relied upon íor production oí
session kevs.



1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 10 oí 29

private byte[] GetRandomNumber(int keyLength)
{

//create an instance of the default random number generator
RandomNumberGenerator rng = RandomNumberGenerator.Create();


//obtain the required length of the byte array - 128 bits
//divided by 8 is 16
int btLength = keyLength / 8;

//create a byte array for the random number
byte[] bt = new byte[btLength];

//fill the byte array with the random number
rng.GetBytes(bt);

return bt;

}




1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 11 oí 29

4. HASHING
4.J Overview
Ií a message has been recei·ed bv a partv. how can that partv be sure that the message has not been
tampered with· (ould an ea·esdropper ha·e tampered with the message in transit·
1his issue can be generalised íurther - how do we ·eriív that something has been tampered with· It
would be ·erv time-consuming to ha·e to check e·erv character in a íile to see ií anv oí them ha·e
been changed.
lashing algorithms are used to ·eriív the integritv oí data. while using a minimal amount oí computing
power - when producing digital signatures. it is less resource intensi·e to encrvpt a hash oí a message
than the entire message.
lashing is a technique in which an algorithm hash íunction, is applied to data to create a digital
íingerprint` that is a íixed length binarv stream.
Ií anvone changes data bv so much as a single binarv digit. the hash íunction will produce a diííerent
output. lashes. or message digests. are used to demonstrate that plaintext has not been tampered with
- ií the message cannot produce the hash supplied with it. then it has been altered.
As the hash íunction produces output oí a íixed size. which allows a íinite number oí hashes. and the
number oí pieces oí plaintext is oí an iníinite space. íor anv single hash ·alue there mav be more than
one piece oí plaintext which hashes to that ·alue. 1his is known as a collision. lowe·er. it requires
great deal oí computing power to íind plaintexts that gi·e the same hash. 1his means that changing the
data. e·en bv one character. can be relied on to change the hash that is produced.
lashing is írequentlv reíerred to as one-wav encrvption. although it does not íit the deíinition oí
encrvption within this document. 1his is important. as manv reíerences reíer to encrvpted and
plaintext storage oí passwords. 1hev generallv mean either the hash oí the password or the plaintext
password.
Salting` oí the hash means adding an initial string to the beginning oí what is being hashed. or the
salt` is used as the íirst input block to the hash. One example oí where this is used is in
reauthentication scenarios. \hen using (hallenge landshake Protocols (lAP,. reauthentication is
demanded at irregular inter·als during a session. 1he ser·er sends a diííerent salt` ·alue to the client
each time. so that a diííerent hash is produced. 1his ensures that the same authentication iníormation
cannot be captured and reused bv a third partv pretending to be the client.
4.2 Algorithms
1he íunctions íor the most commonlv used algorithms SlA-1 and MD5, diííer. but thev both íollow
the same basic principle.
♦ 1he original message is broken up into íixed size blocks.
♦ 1he hash algorithm is applied to the íirst block.
♦ 1he result is íed through with the next message block.
1his creates what is termed the ripple eííect`. As the size oí message gets longer. the initial bvtes tend
to ha·e less eííect on the íinal hash than those at the end oí message. Because oí this. manv
implementations oí hashing algorithms impose an upper limit on the length oí the message. .NL1
imposes limits oí 2
64
bits. which is suííicient íor most projects. Ií it is necessarv to hash a longer piece
oí iníormation. it can be split into shorter segments and each section can be hashed indi·iduallv. 1he
resulting outputs can be appended together.
1he main hash algorithms are MD5 and SlA-1.
A ·ariable can be íed into a hashing algorithm. 1here are a number oí wavs to do this - a common
method is to combine the ·alue with the message. and then pass the resulting text through the



1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 12 oí 29

algorithm. Alternati·elv. a svmmetric encrvption algorithm can be used. using the ·ariable as the kev.
and all but the last íew bvtes oí the resulting encrvpted text are discarded.
A common wav oí combining the ·alue with the plaintext is ·ia the lMA( standard. which is
supported bv the .NL1 classes.
1he two keved hashing algorithms within the .NL1 namespace are:
♦ MA(1ripleDLS
♦ lMA(SlA1
\hich are both deri·ed írom the abstract KevedlashAlgorithm class.
1he lMA(SlA1 algorithm is recommended.
Keved hashing algorithms allow message integritv to be ·eriíied - ií a partv does not ha·e the kev. thev
cannot generate the message digest. and thus cannot alter the content oí the message.
1he National Securitv Agencv in the USA created the SlA Secure lash Algorithm, in 1993. and the
National Institute oí Standards and 1echnologv NIS1, published it as lederal Iníormation Processing
Standard lIPS, 180. permitting its use in go·ernment projects. 1he NSA withdrew the standard
shortlv aíter publication. replacing it with the SlA-1 algorithm. which dealt with securitv weaknesses
íound in the original SlA. 1hese weaknesses were ne·er made public.
MD5 is the íastest hashing algorithm a·ailable in .NL1. It was created bv Ronald Ri·est in 1991. 1here
ha·e been concerns about the compression part oí the algorithm and the shorter kev length 128 bit.
compared to the 160 bit length oí SlA-1,. which slightlv increases the likelihood oí collisions.
Both algorithms are tried and tested. so thev are known to be reliable.
NIS1 published lIPS 180-2 in 2001. 1his deíined SlA-256. SlA-384 and SlA-512. 1hese ha·e
larger bit-sizes íor the hash code. but thev are suííicientlv recent that íor a time their crvptographic
securitv was questioned. Recentlv. howe·er. the computing industrv has been incorporating these
algorithms into new products. .NL1 supports these new ·ersions oí the algorithm.
A common attack on hashing algorithms in·ol·es collisions two pieces oí plaintext that produce the
same hash,. Ií someone is able to control the contents oí a hash. then it is much easier computationallv
to íind two pieces oí text that hash to the same result. rather than trving to íind plaintext that matches
a gi·en hash. 1his is known as a birthdav attack. 1he main use oí this tvpe oí attack is to produce a
íraudulent digital signature.
4.3 Recommendations
SlA-1 and MD5 are both reliable hashing algorithms. 1here are two ·ersions oí each within the .NL1
classes. It is best not to use the managed ·ersions. as these are much slower.
SlA-1 is considered to be slightlv stronger than MD5. due to the kev length being 32 bits longer.
lowe·er. MD5 is the íastest oí the .NL1 hashing implementations. but onlv marginallv so.
SlA-1 should be the íirst choice íor hashing. lowe·er. ií períormance becomes an issue. the MD5
implementation can be up to 50° íaster íor large data blocks.
lMA(SlA1 is the recommended keved hashing algorithm.
Make sure that the algorithm is coníigurable see section 3.1.6,. Bv doing this. it would be possible in
íuture to change írom SlA-1 to the newer SlA algorithms at a later date without ha·ing to recompile
assemblies.
lere is an example oí the use oí the MD5 algorithm. which could be altered to use the SlA-1 bv
changing a coníigurable ·ariable.
//alg would actually be configurable in practice
string alg = "MD5";




1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 13 oí 29

//use System.Text.Encoding to convert to a byte array
byte[] inputText = System.Text.Encoding.Default.GetBytes(plainText);

//instantiate a base class, this allows either an SHA1Managed or
//MD5CryptoServiceProvider to be configured
HashAlgorithm ha = HashAlgorithm.Create(alg);

byte[] hashInput = null;

//create the hash
using (ha)
{
hashInput = ha.ComputeHash(inputText);
}
1his example shows how to create a hash using a kev. In this case. the base class is the
KevedlashAlgorithm class.
string plainText = "Here is the message";
string hashKey = "Here is the key";

//alg would be configurable in practice
string alg = "HMACSHA1";

//create the base class, so that different a different
//algorithm class can be configured
KeyedHashAlgorithm kha = KeyedHashAlgorithm.Create(alg);

//convert the key and plaintext to byte arrays
byte[] hashKeyBytes = System.Text.Encoding.Default.GetBytes(hashKey);
byte[] plainTextBytes = System.Text.Encoding.Default.GetBytes(plainText);

//set the key
kha.Key = hashKeyBytes;

byte[] hashResultBytes = null;

//compute the hash
using(kha)
{
hashResultBytes = kha.ComputeHash(plainTextBytes);
}



1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 14 oí 29

5. SYMML1RIC CRYP1OGRAPHY
5.J Overview
lashing pro·ides integritv íor a message. but how is coníidentialitv achie·ed· As two parties conduct a
con·ersation. exchanging iníormation. thev mav need to ensure that no other partv can read this
iníormation as it tra·els across the wire.
lor this sort oí interaction. svmmetric encrvption is used. Using svmmetric encrvption. the original
message can be retrie·ed as long as the recei·ing partv has the secret kev that was used to encrvpt it.
Svmmetric encrvption where both parties use the same kev íor encrvption and decrvption, is the saíest
and most eííicient wav to encrvpt communications. It relies on both parties sharing a secret kev with
each other and no-one else see section 6 íor iníormation on how this kev is passed saíelv írom one
partv to the other without anvone else intercepting it,.
A basic block cipher encrvpts blocks oí plaintext using a secret kev.
Message
data block
Cipher
function
Ciphertext
block
Secret key

1he original plaintext is restored bv re·ersing the transíormation. using the same kev.
Ciphertext
block
Cipher
function
Message
data block
Secret key

1here are three tvpes oí block cipher a·ailable within the .NL1 íramework:
♦ Llectronic (odebook Mode L(B,
♦ (ipher Block (haining (B(,
♦ (ipher leedback mode (lB,
1he other tvpe oí svmmetric encrvption is a stream cipher. íor which the .NL1 lramework (lass
Librarv pro·ides no implementations.



1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 15 oí 29

5.1.1 Llectronic Code Book Mode (LCB)
Message
data block 1
Cipher
function
Ciphertext
block 1
Message
data block 2
Cipher
function
Ciphertext
block 2
Message
data block 3
Cipher
function
Ciphertext
block 3

1he plaintext is broken into blocks.
Lach block is encrvpted.
1he resulting ciphertext blocks are then appended together.
1he main weakness in this tvpe oí cipher are that anv blocks oí text that are repeated will gi·e the same
ciphertext. making it more easv to decrvpt ·ia statistical analvsis techniques.
1he ad·antage oí L(B is that large blocks oí plaintext can be encrvpted´decrvpted in parallel.
5.1.2 Cipher Block Chaining (CBC)
Message
data block 1
Cipher
function
Ciphertext
block 1
Message
data block 2
Cipher
function
Ciphertext
block 2
Message
data block 3
Cipher
function
Ciphertext
block 3
XOR
XOR
XOR
Initialisation
vector

Message blocks are encrvpted using the cipher íunction. but the result oí each encrvption is XORed
with the next message block prior to its encrvption.



1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 16 oí 29

1he encrvption algorithm is initialised with an Initialisation Vector IV,. IV is a block oí random data
that is the same size as the cipher íunction input block. 1he same IV is required íor decrvption. but it
is not necessarv to keep this secret onlv the secret kev should not be disclosed,.
5.1.3 Cipher Ieedback mode (CIB)
Processing plaintext data block bv block is not suitable íor all projects. A securitv risk mav be
introduced bv waiting íor a complete block oí plaintext to be assembled beíore it can be encrvpted.
lor example. ií a user is tvping in data to an application. using (B( and L(B would require that
complete blocks oí data be tvped in beíore thev are encrvpted. (lB is a technique íor using a block
cipher íunction to encrvpt plaintext in íragments smaller than the íunction block size. 1his allows data
to be encrvpted as it arri·es.
lor example. a 64 bit IV and 8 bit data chunks could be used. 1he 64 bit IV is placed on a queue. As
each piece oí 8 bit plaintext arri·es. the queue is encrvpted and then XORed with the plaintext. 1he 8
bit ciphertext output is then placed on the queue. and the queue is shiíted along`. losing its íirst eight
bits.
1he process is then repeated íor the next 8 bits.
1he ciphertext chunks are appended together to produce the output.
A similar mode is Output leedback mode. a ·ariant on (lB. which uses a diííerent method to íill the
queue.
5.1.4 Stream Ciphers
Stream ciphers are svmmetric algorithms that operate on plaintext bit bv bit. 1hev are extremelv íast
compared with block ciphers. and are generallv designed íor embedded applications. Stream ciphers
are not part oí the .NL1 íramework crvptographv classes.
5.1.5 Block Padding
As it is unlikelv that anv message will íall neatlv into the chunk sizes required íor encrvption. the
message is padded. PK(S 4¯ padding is one oí the more reliable methods.
5.1.6 Key Size
1he larger the size oí the kev. the greater the strength oí the encrvption. due to the larger kev space.
1his is the bit size mentioned in discussions about encrvption - anvone discussing 128 bit encrvption
means a kev size oí 128 bits. 1hev are not reíerring to the block size used in the cipher.
5.1.¯ Key Generation
It is best to a·oid basing kev generation on a password. Kevs should be genuinelv random ií the
theoretical securitv oí a svmmetric algorithm is to be achie·ed. Passwords are oíten chosen badlv íor
instance mother`s maiden name. ía·ourite íootball team,. Anv soítware that períorms dictionarv
attacks uses a database that is likelv to include most weak user passwords. Ií it is absolutelv necessarv
to base a kev on a password. it is best to use a passphrase a group oí words concatenated, and add an
arbitrarv length string to the end. such as a number. to make it harder to períorm a dictionarv attack. A
case when this might be used eííecti·elv is the password protection íor a \ord or Lxcel document.
1he most common scenario íor use oí svmmetric algorithms is as íollows:
♦ Asvmmetric crvptographv is used to saíelv exchange svmmetric kevs
♦ 1he svmmetric kev is used íor encrvption oí communications between the parties
In these circumstances. a íresh session kev should be generated íor each communication session. It
mav be ad·isable to change this kev during the session ií there is a large amount oí communication.
Passwords should be used íor authentication. rather than as encrvption kevs. Once a user has
authenticated. the securitv subsvstem can gi·e access to anv kevs that the user requires. 1his can be
achie·ed bv using the DPAPI see Building Secure ASP.NL1 Applications,. Storing oí svmmetric kevs



1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 1¯ oí 29

is commonlv used when crvptographv is used to protect iníormation such as a database connection
string. rather than íor communications between parties.
Do not re-use session kevs. lor instance. IPSec can be coníigured to renew session kevs during a
session to reduce the amount oí encrvpted text a·ailable íor crvptanalvsis. 1his mav be ad·isable ií
long sessions with large amounts oí data are to take place.
5.2 Algorithms
1he svmmetric algorithms a·ailable ·ia the .NL1 namespaces are:
♦ Data Lncrvption Standard DLS,
♦ 1riple DLS 3DLS,
♦ Ri·est (ipher 2 R(2,
♦ Ad·anced Lncrvption Standard ALS,
5.2.1 Data Lncryption Standard (DLS)
1his is one oí the oldest algorithms. and was the US go·ernment standard írom 19¯6 to 2001. 1he
National Bureau oí Standards NBS, in the USA speciíied that DLS was to be recertiíied e·erv íi·e
vears. It passed in 1983. but the NSA reíused to recertiív it in 198¯. lowe·er. as there was no
alternati·e íor manv businesses. the NSA and NBS were íorced to recertiív it again.
DLS is a block cipher. segmenting the data into blocks oí 64 bits. It uses a kev size oí 56 bits.
5.2.2 1riple DLS (3DLS)
3DLS uses multiple encrvption ie. encrvpting using the same algorithm more than once. each time with
diííerent kevs. 3DLS uses a more eííecti·e method. which is to encrvpt with one kev. decrvpt with the
second kev. and then encrvpt with the third kev.
In some implementations. the íirst and third kev are the same. somewhat reducing the strength oí the
encrvption.
1he .NL1 implementation classes allow two or three 56 bit kevs. expressed as 64 bit numbers.
Some reíerences state that the eííecti·e kev size is 168 bit ie.3 x 56 bit,.
It should be noted that ií the three kevs used are the same. then the encrvption will onlv be DLS.
rather than 3DLS.
3DLS was seen as a good interim step beíore ALS replaced it as the industrv standard.
5.2.3 Advanced Lncryption Standard (ALS)
ALS deíined a new algorithm to replace DLS and its deri·ati·es. 1he National Institute oí Standards
and 1echnologv NIS1, in the USA accepted proposals íor re·iew in 199¯.
Aíter whittling down to a shortlist. the next part oí the selection process took o·er a vear.
1he Rijndael algorithm was e·entuallv pronounced the winner in October 2000 because oí its high
períormance in both hardware and soítware implementations and its small memorv requirement.
Note: Anv discussion reíerring to Rijndael is a discussion oí ALS.
Most tests ha·e shown that ALS is at least twice as íast 3DLS.
It is a·ailable in 128. 192 and 256 bit kev lengths.
ALS is rapidlv being adopted bv hardware and soítware ·endors.
(rvptographers ha·e not vet established the long term securitv oí the ALS algorithm. Various papers
are a·ailable on the internet discussing new attacks on the algorithm. lowe·er. thev generallv agree
that ALS is preíerable to using DLS. but the important issue is to íind a better replacement should anv
oí the theories oí attacking ALS be pro·en thev ha·e not so íar,.



1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 18 oí 29

It should be noted that the .NL1 SvmmetricAlgorithm class will instantiate a RijndaelManaged class bv
deíault ií no argument is speciíied.
5.2.4 RC2
1his algorithm was produced bv Ronald Ri·est. R(2. R(4. R(5 and R(6 are all working algorithms.
but onlv R(2 is implemented in managed code.
R(2 is up to three times íaster than DLS.
1he .NL1 crvptographv namespaces allow 40. 48. 56. 64. ¯2. 80. 88. 96. 104. 112. 120 and 128 bit kev
lengths.
A problem with this algorithm is the abilitv to accept ·erv small kev sizes. Ií a small kev is chosen. then
modern computing power will be able to retrie·e the plaintext easilv.
5.3 Recommendations
3DLS is a saíe algorithm to use íor svmmetric encrvption.
ALS is being taken up bv manv soítware and hardware ·endors and is also a saíe algorithm. although it
should be born in mind that it is comparati·elv new and some publications recommend that it should
be used with caution. 1he US go·ernment ha·e chosen this algorithm as a replacement íor DLS and
its deri·ati·es. More importantlv. e·en though the National Securitv Agencv initiallv had doubts about
the algorithm. thev ha·e now adopted it. Also remember that there is a choice oí kev lengths - make
sure that a 256 bit kev is used.
Speciíicallv a·oid using DLS.
1he diííerent block modes can be set íor the svmmetric algorithms. and so can the padding.
PK(S 4¯ should be used íor padding.
1he diííerent block modes should be set according to requirements - the criteria are discussed in
section 5.1 and its subsections. 1he onlv mode that should be a·oided is Llectronic (ode Book L(B,.
as it is less resistant to crvptanalvsis.
Generating random numbers íor either secret the kev or the initialisation ·ector should be undertaken
using the RandomNumberGenerator class see section 3.1.8,.
Use a (rvptoStream object íor encrvption and decrvption.
1rv to a·oid basing encrvption kevs on passwords see 5.1.¯,.
Microsoít ha·e pro·ided an article in MSDN comparing the períormance oí the algorithms mentioned
here. but it does not seem altogether accurate as diííerent kev sizes ha·e been chosen íor diííerent
algorithms. 1he statistics mav be questionable. but make interesting reading. 1he article is entitled
Períormance (omparison: Securitv Design (hoices and is written bv Priva Dhawan.
lere is an example íunction which allows íor coníiguration oí all oí the important parameters:

private byte[] EncryptSymmetric(
byte[] key,
string plainText,
byte[] IV,
int blockSize,
string alg,
CipherMode mode)
{

//calculate keysize based on length of array
int keySize = key.Length * 8;





1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 19 oí 29

//convert the text to a byte array
byte[] btPlainText =
System.Text.Encoding.Default.GetBytes(plainText);

//use a base class so that the algorithm used is configurable
SymmetricAlgorithm sa = SymmetricAlgorithm.Create(alg);

MemoryStream ms = null;

using(sa)
{

//set the blocksize and keysize for the symmetric
//algorithm class
sa.BlockSize = blockSize;
sa.KeySize = keySize;

//set the initialisation vector
sa.IV = IV;

//set the padding to PKCS#7
sa.Padding = PaddingMode.PKCS7;

//no parallel computation, no requirement to encrypt
//as data is assembled, so use CBC mode
//It may be good practice to configure this
sa.Mode = mode;

//set the secret key for the encryption
sa.Key = key;

//the ICryptoTransform interface exposes details to the
//algorithm for handling data in blocks
ICryptoTransform ict = sa.CreateEncryptor();

//the encrypted data is written to a memory stream
ms = new MemoryStream();

//CryptoStream transforms blocks of data
//using the ICryptoTransform object
CryptoStream cs = new CryptoStream(
ms,
ict,
CryptoStreamMode.Write);

//perform the encryption
using (cs)
{
cs.Write(btPlainText, 0, btPlainText.Length);
}

}

return ms.GetBuffer();

}

It is important to note that no crvptographv iníormation should be leít in memorv aíter the calculation
has been períormed. A using` block was created íor the SvmmetricAlgorithm and (rvptoStream
objects.



1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 20 oí 29

Remember that most oí the parameters should be coníigurable. so that kev lengths. algorithms. etc can
be updated at a later date without recompiling the assemblies.
A similar íunction to decrvpt can be created bv changing the íunction call sa.(reateLncrvptor, to
sa.(reateDecrvptor,. or perhaps passing another parameter to the same íunction to select which
method to call.



1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 21 oí 29

6. ASYMML1RIC CRYP1OGRAPHY
6.J Overview
low can a secret kev be exchanged between parties so that thev can communicate in coníidence· 1his
is one oí the most important uses íor asvmmetric crvptographv.
Asvmmetric crvptographv is based on íunctions that use two diííerent kevs íor encrvption and
decrvption. 1hese pro·ide the crvptographic in·erse íor each other - ií the íirst kev is used íor
encrvption. the second kev is used íor decrvption. Alternati·elv. the second kev can be used íor
encrvption. so that the íirst kev will decrvpt the resulting ciphertext.
Generallv. íor the purposes oí communication. one kev is distributed publiclv the public kev, and the
other kev is kept securelv bv the owner oí the kevs the pri·ate kev,.
1heir main use is íor kev exchange and non-repudiation as thev períorm more slowlv than svmmetric
algorithms. and attacking these algorithms is actuallv less resource intensi·e than attacking the industrv
standard svmmetric algorithms.
Also bear in mind that no brute íorce attack or gathering oí plaintext´ciphertext is necessarv íor
breaking an asvmmetric cipher - the attack is done bv íactoring large prime numbers.
6.1.1 Key Lxchange
In kev exchange using the RSA íunction,. the public kev is passed to the indi·idual whom vou wish to
send data to. 1his indi·idual encrvpts the secret svmmetric session kev using the public kev and sends
it back. 1he original sender can then decrvpt the session kev using his´her pri·ate kev. 1his session kev
is then used íor the rest oí the communication.
6.1.2 Non-repudiation
Asvmmetric crvptographv also pro·ides a means to achie·e non-repudiation the sender oí a message
cannot denv ha·ing sent it,. Bv encrvpting the message with a pri·ate kev. the act oí decrvpting it with
the public kev that is in the public domain gi·es e·idence that the originator was the owner oí the
pri·ate kev. 1his authenticates the sender and guarantees integritv.



1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 22 oí 29

Message text
Asymmetric
encryption of
text using party
A’s private key
Ajsadvdvcl
Party A sends a message
Bbjbdc&&$
Message text
Bbjbdc&&$
Public Key Cert
Message, encrypted
hash and Party A’s
public key are
enveloped together
Message sent
to Party B
Public Key Cert
Message text
Bbjbdc&&$
Public Key Cert
Public key
certificate
extracted and
VERIFIED -
this is VERY
IMPORTANT
Encrypted hash
extracted
Ajsadvdvcl
Bbjbdc&&$
Encrypted hash
decrypted
using public
key from
certificate
Message text
Message text
extracted
Hash created
from message
text
Ajsadvdvcl
Do the two
hashes match?
If yes, then the
signature has
been verified
Party B has verified the digital
signature
Hash created
from message
text


lowe·er. digital signatures will also need to relv on trust aííorded bv some authoritv. such as a Public
Kev Inírastructure. so that we ha·e some authentication oí the owner oí the pri·ate kev. 1he diagram
demonstrates the ·eriíication oí a digital signature using a PKI.
6.2 Algorithms
1here are a number oí diííerent tvpes oí asvmmetric algorithms. which include:
♦ RSA. named aíter Ri·est. Shamir and Adleman. 1his was íirst published in 19¯¯.
♦ Digital Signature Algorithm DSA, - published as a lIPS in 1994. 1his can onlv sign messages.
and cannot pro·ide coníidentialitv or kev establishment.
1he onlv implementations in the .NL1 classes are íor RSA and DSA.
6.3 .NL1 Asymmetric Lncryption classes
1he .NL1 asvmmetric classes ha·e limitations due to the íact that thev are not integrated with anv
íorm oí authentication íor instance. X509,.
Ií the .NL1 kev exchange classes are used without strong authentication a serious securitv ·ulnerabilitv
írom a Man in the Middle` attack is exposed.
1his is what is intended to happen with kev exchange:
♦ User A sends her public kev to User B.
♦ User B encrvpts the secret svmmetric session kev using A`s public kev.
♦ User B sends the encrvpted kev back to User A.
♦ Onlv User A can decrvpt the secret session kev with her pri·ate kev.



1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 23 oí 29

lowe·er. this is what happens ií the kevs are intercepted and there is no proper authentication:
♦ User A sends her public kev to User B
♦ User ( intercepts this public kev
♦ User ( instead sends his public kev to User B
♦ User B encrvpts the svmmetric session kev using User (`s public kev User B thinks this is User
A`s public kev,
♦ User B sends the encrvpted session kev back to user A
♦ User ( intercepts this. and decrvpts it using his pri·ate kev which can decrvpt iníormation
encoded bv User B. who encrvpted using User (`s public kev,
♦ User ( then encrvpts the iníormation using User A`s public kev
♦ User ( sends the encrvpted kev back to User A
♦ User A decrvpts the session kev using her pri·ate kev
1he result is that User ( has obtained the secret session kev. User A and User B think their session kev
is secure.
IMPOR1AN1: if the .NL1 asymmetric encryption classes are used, mutual authentication
must take place via another mechanism.
A possible wav oí achie·ing this is to use Kerberos authentication. lowe·er. authentication would not
be bound to the asvmmetric kev as it is when using certiíicates. 1hus. this scenario will not allow non-
repudiation when using asvmmetric crvptographv íor digital signatures. Also. it likelv that anv
application períorming crvptographic communications is not running under the identitv oí the user
that needs authentication. 1his will certainlv be the case when using the trusted subsvstem model íor
large scalable web applications. linallv. Kerberos authentication will onlv work within a pri·ate
intranet. not across the internet.
Alternati·elv. one oí the samples included with (API(OM see section 6.4, shows how to use the
(rvpto API to access kevs held in certiíicates in the certiíicate store. but this requires the use oí a
librarv written in ( the code íor this DLL is included in the (API(OM download,.
Another important point is that it is essential to use the RSAOALPKevLxchangelormatter class. as
the íormatting scheme used bv this class makes kev exchange resistant to some tvpes oí attack.
An OALP encoded message consists oí a masked data` string concatenated with a masked random
number`. 1he eííect is that the attacker has to be able to break RSA to íind the encrvpted text. 1he
RSA website gi·es a íuller mathematical explanation.
Although Microsoít readilv admit that the .NL1 implementations are not vet complete. the next
·ersion oí the lramework is likelv to ha·e a richer set oí íunctions. Using the classes downloaded in
the \ebSer·ices Lnhancements 2 package. it can be seen that an X509(ertiíicateStore object is
a·ailable. and a more mature X509(ertiíicate class are a·ailable in the Microsoít.\eb.Ser·ices2
namespace.
1his is ·erv encouraging íor the íuture. but limitations are currentlv still present. 1he pri·ate kev oí the
X509 certiíicate class cannot be extracted írom the certiíicate store. and no chain-building oí the
certiíicates takes place.
1he new ·ersion oí Visual Studio \hidbev, will allow íull access to the certiíicate store and building
oí certiíicate chains. Speciíicallv. .NL1 exposes the APIs that are part oí \indows in order to pro·ide
these íeatures. Some ad·antages are:
♦ XML Digital Signatures will actuallv be proper digital signatures ie. the asvmmetric kev used to
encrvpt will be tied to a ·alidated certiíicate



1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 24 oí 29

♦ (ertiíicates can be used íor authentication during kev exchange
As at the time oí writing this paper. the beta ·ersion oí \hidbev is code complete as regards the
encrvption classes. lowe·er. as proper documentation is scarce. anv code samples constructed could
not be guaranteed to be an example oí best practice. As more details become a·ailable. this document
should be updated.
6.4 CAPICOM
(API(OM is a component that is a (OM wrapper around manv \indows (rvptoAPI íunctions.
It allows asvmmetric algorithms to be integrated with certiíicate stores. which gi·es the stronger
authentication required íor kev exchange and digital signatures.
lere is an extract írom MSDN:
CAPICOM uses digital certificates to create signatures, encrypt session encryption keys when creating
enveloped messages, and decrypt encrypted session keys when an enveloped message is received.
By default, CAPICOM uses certificates in the My store that have an associated private key for both
digital signatures creation and session key decryption. In most cases, an application would never
need to open or otherwise directly deal with a certificate store.
However, applications creating enveloped messages use the public key of each intended recipient of
an enveloped message. These keys are retrieved from the certificates of the intended recipients.
Thus, to create enveloped messages for a group of intended recipients, the certificates of those
recipients would be collected in a certificate store.
The following table lists the standard certificate stores normally persisted on a user station.
Store Description
My Contains personal certificates. These certificates will usually have an associated private key.
Other
People
Contains the certificates of those that the user normally sends enveloped messages to or receives signed messages
from.
CA and
Root
Contains the certificates of certificate authorities that the user trusts to issue certificates to others. Certificates in these
stores are normally supplied with the operating system or by the user's network administrator. Certificates in the Root
store are typically self-signed.

1he (API(OM distributable is obtainable írom:
http:´´www.microsoít.com´downloads´details.aspx·lamilvID~860ee43a-a843-462í-abb5-
íí88ea5896í6&DisplavLang~en
1he (AB íile contains manv examples íor using (API(OM. and e·en some tools to bridge the
shortcomings oí the .NL1 implementations.
lere is an example where (API(OM has been used to digitallv sign a message. using lred Bloggs`s
certiíicate írom the current user store:
//name of certificate to use for signature
string certName = "fred bloggs";
//create an instance of the store class
Store certStore = new StoreClass();
//open the current user store
certStore.Open(CAPICOM_STORE_LOCATION.CAPICOM_CURRENT_USER_STORE,
"MY",
CAPICOM_STORE_OPEN_MODE.CAPICOM_STORE_OPEN_READ_ONLY);
//certificate object to hold fred bloggs's certificate
Certificate x509cert = null;
//iterate through certs to find certificate



1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 25 oí 29

foreach (Certificate cert in certStore.Certificates)
{
//obtain the name of the certificate
string name =
cert.GetInfo(CAPICOM_CERT_INFO_TYPE.CAPICOM_CERT_INFO_SUBJECT_SIMPL
E_NAME);
//is this the certificate we wish to use?
if (name == certName)
{
x509cert = cert;
}
}
//create a signer
Signer messageSigner = new SignerClass();
//set the certificate to use
messageSigner.Certificate = x509cert;
//create a signed data class
SignedData sd = new SignedDataClass();
//text to sign
sd.Content = "This is the piece of text that requires signing";
//sign the message
string signedMessage = sd.Sign(messageSigner,
false,
CAPICOM_ENCODING_TYPE.CAPICOM_ENCODE_BASE64);

1his message will contain the original text. the signed text and the digital certiíicate. 1he padding is
PK(S4¯ stvle.
PK(S4¯ íormatting is an industrv standard. which allows interoperabilitv with other platíorms.
lere is some code showing how to ·eriív the signature and retrie·e the message írom the base64
encoded message:
//create the signeddata class
SignedDataClass sd = new SignedDataClass();
//call the verify method - signedText is the string that has to be
verified
sd.Verify(signedText,
false,
CAPICOM_SIGNED_DATA_VERIFY_FLAG.CAPICOM_VERIFY_SIGNATURE_AND_CERTIF
ICATE);

//to check the signatures, we have to iterate through all of the
signatures.
//Messages can be cosigned
foreach (Signer sr in sd.Signers)
{

Signer s = sr;

//call the IsValid.Result property to see if the signature is valid
MessageBox.Show(
s.Certificate.GetInfo(
CAPICOM_CERT_INFO_TYPE.CAPICOM_CERT_INFO_SUBJECT_SIMPLE_NAME)
+ ":" + s.Certificate.IsValid().Result);

//this is useful - CAPICOM will also check CRL status
//If you set the CheckFlag parameter
//it will also obtain CRL from the certificate's CRL
//Distribution Point
s.Certificate.IsValid().CheckFlag =



1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 26 oí 29

CAPICOM_CHECK_FLAG.CAPICOM_CHECK_TRUSTED_ROOT |
CAPICOM_CHECK_FLAG.CAPICOM_CHECK_TIME_VALIDITY |
CAPICOM_CHECK_FLAG.CAPICOM_CHECK_SIGNATURE_VALIDITY |
CAPICOM_CHECK_FLAG.CAPICOM_CHECK_ONLINE_REVOCATION_STATUS ;

//call the IsValid.Result property again
MessageBox.Show(s.Certificate.GetInfo(CAPICOM_CERT_INFO_TYPE.CAPICO
M_CERT_INFO_SUBJECT_SIMPLE_NAME) + ":" +
s.Certificate.IsValid().Result.ToString());

}

6.5 1he Windows Certificate Store
Anv solution in·ol·ing certiíicates would also require maintenance oí the certiíicate store used. It
would be necessarv to make sure that the target computer has access to anv root and intermediate
certiíicates in the trust chain. 1his is not períormed automaticallv - anv solution that is created must
make sure that all certiíicates required are downloaded and installed into the certiíicate store. 1his also
includes (RL certiíicates.
Ií a solution needs to take ad·antage oí more recent technologies such as Online (ertiíicate Status
Protocol,. it will be necessarv to code this manuallv.
(aution must be exercised with the \indows certiíicate store oíten reíerred to as the (API store,:
♦ 1here is no requirement íor strong passwords in the certiíicate store
♦ 1here is no Lockout Policv íor the store when entering passwords to access the pri·ate kev
♦ A deíault can be set on the store so that passwords are not required
1his does not pose a threat ií the certiíicate store is on a ser·er that is not accessible to the public. and
that ser·er has been locked down securelv.
lowe·er. anv solution that deplovs to a client workstation that uses a certiíicate store mav not be saíe.
It is important to bear in mind that anv soítware that is distributed to users could be installed on
unsaíe workstations. Do not be surprised ií certiíicates that vou distribute to members oí the public
end up being installed on a P( in the local internet caíé.
6.6 Recommendations
Do not use asvmmetric algorithms íor encrvpting large amounts oí data. Onlv use them íor kev
exchange or digital signatures.
\hen períorming kev exchange or creating a digital signature. make sure that the user is properlv
authenticated.
IMPOR1AN1: If there is no proper authentication of the owner of the private key, then
creating a digital signature is as useful as signing a paper document with the name ´William
Shakespeare¨.
It is not possible to create kevs using a random number generator due to the mathematical nature oí
the algorithm. Ií vour solution integrates with PKI. then the algorithm and parameters will be part oí
the X509 certiíicate. Ií using the .NL1 asvmmetric classes. instantiation oí the asvmmetric algorithm
class will automaticallv create the parameters íor the encrvption´decrvption.
Bv themsel·es. the asvmmetric encrvption classes in the .NL1 namespaces do not pro·ide anv íorm oí
authentication íor the kev exchange - ií vou wish to use these. then vou will ha·e to include vour own
authentication. One possible wav would be to use Kerberos. lowe·er. remember that this would not
allow non-repudiation íor digital signatures.



1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 2¯ oí 29

Make sure vou use the RSAOALPKevLxchangelormatter class íor kev exchanges ií using the .NL1
asvmmetric classes.
1he simplest. and thus the most reliable. wav íorward would be to use (API(OM and integrate with
the certiíicate store. lowe·er. this will onlv allow the creation oí a PK(S4¯ en·elope íor the message
íormat. Ií other digital signature íormats are required such XMLDSIG,. then it is necessarv to access
some oí the (rvptoAPI íunctions to extract the necessarv iníormation írom the certiíicate. and then
use the .NL1 classes íor creation oí the signature.
1he next ·ersion oí the .NL1 íramework will extend crvptographic íunctionalitv to include proper
integration with the certiíicate store. 1his document will be updated as more iníormation becomes
a·ailable.
Onlv relv on the certiíicate store when it is used on a secure ser·er. ne·er when it is distributed to anv
client workstation that is not locked down properlv. It mav be worth creating a secure certiíicate store
to eníorce password usage and strength. but ií this is undertaken it mav be necessarv to achie·e a high
degree oí certiíication bv independent bodies íor the product. 1his has been undertaken bv some
organisations to allow the use oí digital signatures íor transactions. but it would be preíerable to
choose írom anv certiíied third partv products a·ailable.



1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 28 oí 29

7. QUICK GUIDL
1his guide is pro·ided to clariív decision making regarding which algorithm to use and how to use it.
I need to... Recommendation
Lnsure that
communication is secure
Preíerablv use implementations oí crvptographic algorithms pro·ided
bv Microsoít or an accredited third partv. (heck the coníiguration oí
the tools used section 3.1.5,.
Ií using crvptographic algorithms directlv. use the recommendations
in this document.
Ne·er write vour own algorithms.
(reate íunctionalitv similar
to that alreadv pro·ided bv
\indows as the Microsoít
implementation is not
appropriate
(onsult securitv expert internal or external,
Preíerablv use third partv products
Make sure oí accreditation and certiíication requirements íor both
bespoke and third partv solutions section 3.1.5,
Make sure that encrvpted
iníormation stavs secure in
the íuture
(hoose the encrvption algorithm careíullv
(hange kevs at regular inter·als see section 3.1.3,
Lncrvpt communications
between parties
(heck to see ií \indows incorporates a technologv which encrvpts
communications eg. IPSec see section 3.1.5.
Lxchange svmmetric session kevs using asvmmetric algorithms with
mutual authentication section 6,.
User must be authenticated beíore períorming kev exchange section
6.3. 6.4,
(hoose the correct svmmetric algorithm and kev length section 5,.
Lnsure integritv oí a
communication
Use a keved hashing íunction see section 4,
(hoose a hashing
algorithm
Use SlA-1 ií it is a·ailable. MD5 ií it is not section 4.3,
Use non-repudiation to
guarantee that a user sent a
particular message
Use (API(OM to create a digital signature section 6.4,
Make sure that a trusted authoritv is used to ·eriív the owners oí
pri·ate kevs - preíerablv ·ia PKI section 6,
(hoose an appropriate
svmmetric algorithm íor
encrvption
(hoose ALS or 3DLS. with the largest possible kev lengths section 5,
lollow the recommendations íor padding. algorithms. cipher modes
section 5.3,
Make sure the kev size. algorithm. IV is coníigurable section 3.1.6.
5.3,
(hoose an appropriate
asvmmetric algorithm
Use (API(OM section 6.4,
Ne·er use anv implementation that does not incorporate mutual
authentication. Preíerablv use PKI íor authentication. as this is the
simplest approach.
Ií using PKI and certiíicates íor authentication. there will be no choice
oí algorithm - it will be part oí the certiíicate section 6.6,.
Make sure that vou read through the Recommendations sections throughout this document beíore
attempting an implementation.



1¯ September 2004
Version 1.0
(rvptographic Algorithms - Guidance lor De·elopers Page 29 oí 29

8. BIBLIOGRAPHY
♦ Secure Networking with \indows 2000 and 1rust Ser·ices: Jalal and Jalil lenghi. Published bv
Addison-\eslev
♦ Programming .NL1 Securitv: Adam lreeman. Allen Jones. Published bv O`Reillv
♦ SS(P Studv Guide: Josh Jacobs. Lee (lemmer. Michael Dalton. Russ Rogers. Jeíírev Posluns.
Published bv Svngress
♦ Securitv & (ertiíication Lxam Guide: Published bv Osborne Press
♦ Secure (ode: Michael loward. Da·id LeBlanc. Published bv Microsoít Press
♦ Designing Microsoít \indows 2000 Network Securitv: Published bv Microsoít Press
♦ MSDN article: Períormance (omparison: Securitv Design (hoices: Priva Dhawan
♦ MSDN article: Introducing (API(OM: John Lambert
♦ National Institute oí Standards and 1echnologv NIS1, web site:
http:´´csrc.nist.go·´(rvpto1oolkit´aes´rijndael´
♦ New Attacks on ALS: http:´´www.minrank.org´aes´
♦ Impro·ed (rvptanalvsis oí Rijndael: Niels lerguson. John Kelsev. Steían Lucks. Bruce Schneier.
Mike Stav. Da·id \agner. Doug \hiting
♦ Building Secure ASP.NL1 Applications - Microsoít Patterns and Practices: JD.Meier. Alex
Mackman. Srinath Vasireddv. Michael Dunner
♦ RSA laboratories web site - http:´´www.rsasecuritv.com´rsalabs