networksecurity all in onev2

172
Sandrine VATON Professor Télécom Bretagne Brest, France E-mail : [email protected] Network Security Course Material for lectures, practicals and exercices November 2014

Upload: tecnicoitca

Post on 19-Nov-2015

45 views

Category:

Documents


6 download

DESCRIPTION

network

TRANSCRIPT

  • Sandrine VATONProfessorTlcom BretagneBrest, FranceE-mail : [email protected]

    Network Security Course

    Material for lectures, practicals and exercices

    November 2014

    mailto:[email protected]

  • Table des matires

    Introduction to Cryptography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

    Crypto Lab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

    RSA Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

    RSA Lab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

    Public Key Cryptography Exercices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

    Attack Lab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89

    Network Audit Lab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97

    Introduction to IDS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105

    IDS Lab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163

    VPN Lab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167

  • An Introduction to Network Security

    S. Vaton & C.Fontaine

    Tlcom Bretagne

    November 2014

    S. Vaton & C.Fontaine (TB) November 2014 1 / 62

    Short BioDr Sandrine VATON

    Professor, Tlcom Bretagne (Brest, France), dept of ComputerScienceAs a lecturer I am teaching topics such as performance evaluation,statistical methods, cryptography and network security, algorithmicsand programming ...Research field : network monitoring

    I traffic measurement and analysis (in particular, statistical methods)I to discover threats in the traffic, to characterize the traffic

    (classification of the applications), to evaluate performance anddimension the network

    I design of monitoring architectures (in particular, hardware accelerationon FPGA)

    long term collaboration with the group of P.Belzarena (2 PhDco-advised, several internships) ; agreement for a double degree(engineers, PhDs) between IIE and Tlcom Bretagne ; sabbatical atIIE in 2010 (with my husband, Prof. Thierry Chonavel)

    S. Vaton & C.Fontaine (TB) November 2014 2 / 62

    5

    Introduction to Cryptography

  • Sommaire

    1 IntroductionRequirements in terms of securityWhy cryptography ?

    2 Confidentiality through Encryption

    3 Digital Signature

    4 Trusting Public Keys . . .

    5 Zero knowledge proofs

    6 In practiceAuthentication : KerberosAuthentification et cl de session : SSL/TLS et SSH

    7 Conclusion

    S. Vaton & C.Fontaine (TB) November 2014 3 / 62

    Sommaire

    1 IntroductionRequirements in terms of securityWhy cryptography ?

    2 Confidentiality through Encryption

    3 Digital Signature

    4 Trusting Public Keys . . .

    5 Zero knowledge proofs

    6 In practiceAuthentication : KerberosAuthentification et cl de session : SSL/TLS et SSH

    7 Conclusion

    S. Vaton & C.Fontaine (TB) November 2014 4 / 62

    6

  • Network Security

    DefinitionIn the field of networking, the specialist area of Network Security consistsof the provisions made in an underlying computer network infrastructure,policies adopted by the network administrator to protect the networkand the network-accessible resources from unauthorized access, andconsistent and continuous monitoring and measurement of itseffectiveness (or lack) combined together.Network Security and Networking Protocols, A.K.Sharma and C.S.Lamba

    S. Vaton & C.Fontaine (TB) November 2014 5 / 62

    The challenges of Information Systems SecurityConfidentiality : Only authorized people can access to information.Any undesirable access must be prohibited. [remark : here, access =access in terms of information]

    Availability : The system must operate without failures when it hasbeen planned to operate, services and ressources must be accessible(within a good throughput and response time).Integrity : Data must be consistent with what they should be, theyshould not be altered (by mistake or maliciously).Authentication : Users identification is a cornerstone to manage theaccess to appropriate workspaces and to maintain confidence in theexchanges.Non-repudiation and imputation : No user should be able tocontest the operations he has realized in the framework of authorizedactions, and no third party should be able to claim for himself theactions of another user.Source : Wikipedia

    S. Vaton & C.Fontaine (TB) November 2014 6 / 62

    7

  • The challenges of Information Systems SecurityConfidentiality : Only authorized people can access to information.Any undesirable access must be prohibited. [remark : here, access =access in terms of information]Availability : The system must operate without failures when it hasbeen planned to operate, services and ressources must be accessible(within a good throughput and response time).

    Integrity : Data must be consistent with what they should be, theyshould not be altered (by mistake or maliciously).Authentication : Users identification is a cornerstone to manage theaccess to appropriate workspaces and to maintain confidence in theexchanges.Non-repudiation and imputation : No user should be able tocontest the operations he has realized in the framework of authorizedactions, and no third party should be able to claim for himself theactions of another user.Source : Wikipedia

    S. Vaton & C.Fontaine (TB) November 2014 6 / 62

    The challenges of Information Systems SecurityConfidentiality : Only authorized people can access to information.Any undesirable access must be prohibited. [remark : here, access =access in terms of information]Availability : The system must operate without failures when it hasbeen planned to operate, services and ressources must be accessible(within a good throughput and response time).Integrity : Data must be consistent with what they should be, theyshould not be altered (by mistake or maliciously).

    Authentication : Users identification is a cornerstone to manage theaccess to appropriate workspaces and to maintain confidence in theexchanges.Non-repudiation and imputation : No user should be able tocontest the operations he has realized in the framework of authorizedactions, and no third party should be able to claim for himself theactions of another user.Source : Wikipedia

    S. Vaton & C.Fontaine (TB) November 2014 6 / 62

    8

  • The challenges of Information Systems SecurityConfidentiality : Only authorized people can access to information.Any undesirable access must be prohibited. [remark : here, access =access in terms of information]Availability : The system must operate without failures when it hasbeen planned to operate, services and ressources must be accessible(within a good throughput and response time).Integrity : Data must be consistent with what they should be, theyshould not be altered (by mistake or maliciously).Authentication : Users identification is a cornerstone to manage theaccess to appropriate workspaces and to maintain confidence in theexchanges.

    Non-repudiation and imputation : No user should be able tocontest the operations he has realized in the framework of authorizedactions, and no third party should be able to claim for himself theactions of another user.Source : Wikipedia

    S. Vaton & C.Fontaine (TB) November 2014 6 / 62

    The challenges of Information Systems SecurityConfidentiality : Only authorized people can access to information.Any undesirable access must be prohibited. [remark : here, access =access in terms of information]Availability : The system must operate without failures when it hasbeen planned to operate, services and ressources must be accessible(within a good throughput and response time).Integrity : Data must be consistent with what they should be, theyshould not be altered (by mistake or maliciously).Authentication : Users identification is a cornerstone to manage theaccess to appropriate workspaces and to maintain confidence in theexchanges.Non-repudiation and imputation : No user should be able tocontest the operations he has realized in the framework of authorizedactions, and no third party should be able to claim for himself theactions of another user.Source : Wikipedia

    S. Vaton & C.Fontaine (TB) November 2014 6 / 62

    9

  • Confidentiality

    DefinitionConfidentiality has been defined by the International Organization forStandardization (ISO) in ISO-17799 as ensuring that information isaccessible only to those authorized to have access"

    Related AttacksPassive attacks (e.g., eavesdropping)

    Possible solutions : cryptography, IPSec, SSL, TLS

    S. Vaton & C.Fontaine (TB) November 2014 7 / 62

    Availability

    DefinitionThe degree to which a system, subsystem, or equipment is operable and ina committable state at the start of a mission, when the mission is called forat an unknown, i.e., a random, time. Simply put, availability is theproportion of time a system is in a functioning condition.

    Related AttacksDenial of Service (DoS, Distributed Denial of Service DDoS)

    S. Vaton & C.Fontaine (TB) November 2014 8 / 62

    10

  • Integrity

    DefinitionData integrity is related to the state of data that, during their treatment,their storage, or their transmission, have not encountered any modificationor destruction (be it voluntarily or not). Data must be in a state that permittheir utilization, they should not have been modified. Data integrity coversfour elements : precision, completeness, exactitude/authenticity and validty.

    Integrity can be guaranteed by several security mechanisms (e.g., hashfunction, data authentication, digital signature)Trivial examples : checksums, error detection codes such as CRC inpacket/frame headers

    Related Attacksdownloading a malware instead of the expected program, modification ofthe amount of a bank operation, etc.

    S. Vaton & C.Fontaine (TB) November 2014 9 / 62

    Authenticity

    DefinitionAuthentication is the act of establishing or confirming something (orsomeone) as authentic, that is, that claims made by or about the subjectare true

    Attaques associesMan in the Middle, Masquerade, spoofing

    Authentication mechanisms :A difficult-to-reproduce physical artifact, such as a seal, signature,fingerprint.A shared secret such as a passphraseAn electronic signature ; public key infrastructure is often used tocryptographically guarantee that a message has been signed by theholder of a particular private key.

    S. Vaton & C.Fontaine (TB) November 2014 10 / 62

    11

  • Non-rpudiation

    DefinitionNon-repudiation is the concept of ensuring that a party in a dispute cannotrepudiate, or refute the validity of a statement or contract

    The most common method of asserting the origin of data is throughdigital certificates, that can be considered as "digital ID cards". Acertification authority is the trusted third party that ensures thecorrespondence between the physical identity and the digital identity. Acommon standard for digital certificates : X509.

    S. Vaton & C.Fontaine (TB) November 2014 11 / 62

    Security triangle

    "It is very important to understand that in security, one simply cannot say "whats thebest firewall ?" There are two extremes : absolute security and absolute access. Theclosest we can get to an absolutely secure machine is one unplugged from the network,power supply, locked in a safe, and thrown at the bottom of the ocean. Unfortunately, itisnt terribly useful in this state." Network Security and Networking Protocols,A.K.Sharma and C.S.Lamba

    S. Vaton & C.Fontaine (TB) November 2014 12 / 62

    12

  • Sommaire

    1 IntroductionRequirements in terms of securityWhy cryptography ?

    2 Confidentiality through Encryption

    3 Digital Signature

    4 Trusting Public Keys . . .

    5 Zero knowledge proofs

    6 In practiceAuthentication : KerberosAuthentification et cl de session : SSL/TLS et SSH

    7 Conclusion

    S. Vaton & C.Fontaine (TB) November 2014 13 / 62

    What is cryptography useful for ?

    to cipher messages (since Antiquity) :I to protect the confidentiality of messages (against eavesdropping)

    to digitally sign messages (since 1978) :I to authenticate the author of a message, i.e. to make sure that the

    author of the message is who he pretends to beI to guarantee non repudiation i.e. to make sure that the author of a

    message cannot pretend not having built this messageI to guarantee the integrity of a message i.e. to make sure that the

    message has not been altered, that its content has not been modifiedto authenticate oneself with a system (since 1978) :

    I to prove ones identity, by demonstrating that one holds a secret (suchas a passphrase) that no one knows (except the owner), without lettingthis secret circulate as plaintext on the network

    and many other applications (since 1978) :I key key exchange, Multi-Party Computation, electronic voting,

    oblivious transfer, anonymous digital money, ...

    S. Vaton & C.Fontaine (TB) November 2014 14 / 62

    13

  • Sommaire

    1 IntroductionRequirements in terms of securityWhy cryptography ?

    2 Confidentiality through Encryption

    3 Digital Signature

    4 Trusting Public Keys . . .

    5 Zero knowledge proofs

    6 In practiceAuthentication : KerberosAuthentification et cl de session : SSL/TLS et SSH

    7 Conclusion

    S. Vaton & C.Fontaine (TB) November 2014 15 / 62

    Basic concepts (1/2)

    Cryptography : conception of information protection systems. Differentapplication fields : encryption = ciphering, digital signature,authentication.Cipher : algorithm used to perform encryption or decryption ; series ofsteps that transform a plain text, in a cipher text (and vice versa)Cryptosystem : any computer system that involves cryptography ;usually includes methods for digital signatures, key managementtechniques, cryptographic hash functions

    S. Vaton & C.Fontaine (TB) November 2014 16 / 62

    14

  • Basic concepts (2/2)Encrypt = encipher = encode , decrypt = decode = decipher : thesender encrypts the plain text m (with the encryption key) to producethe cipher text c ; the receiver decrypts the cipher text c (with thedecryption key) and recovers the plain text m

    chiffrement

    Cl de chiffrement

    Alice Bobdchiffrement

    Eve

    Message en clair

    Canal jarretire

    Message chiffrMessage en clair

    Cl de dchiffrement

    (oreille indiscrte)

    Cryptanalysis : used to breach cryptographic security systems and gainaccess to the contents of encrypted messages even if the cryptographickey is unknown. How ? By analyzing the flow of information in orderto deduce hidden aspects (some bits of the key) ; in side channelattacks, by the analysis of physical parameters (such as powerconsumption for example).

    S. Vaton & C.Fontaine (TB) November 2014 17 / 62

    History (1/6)

    AntiquityScytale : tool to perform a transposition cipher (permutation of theletters of the message) ; easy to breach

    S. Vaton & C.Fontaine (TB) November 2014 18 / 62

    15

  • History (2/6)Caesar cipher : it is a particular mono-alphabetic substitution cipher :each letter is replaced by a letter some fixed number of positions downthe alphabet, the value of the shift is fixed by the key k :

    ci = mi + k mod [26]

    plain alphabet ABCDEFGHIJKLMNOPQRSTUVWXYZcipher alphabet CDEFGHIJKLMNOPQRSTUVWXYZAB

    plain text LETRO ISJAN VIERA TREIZ EHEUR ESETDcipher text NGVTQ KULCP XKGTC VTGKB GJGWT GUGVF

    Easily breachable by analysis of the frequency of letters in the alphabet

    0

    50

    100

    150

    200

    250

    A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

    Clair (franais)

    0

    50

    100

    150

    200

    250

    A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

    Csar (franais)

    S. Vaton & C.Fontaine (TB) November 2014 19 / 62

    History (3/6)

    16th century : Vigenre cipherpoly-alphabetic substitution cipher with periodicityci = (mi + ki mod |k|) mod [26] ex : with key k=LEROI

    plain alphabet ABCDEFGHIJKLMNOPQRSTUVWXYZcipher alphabet L LMNOPQRSTUVWXYZABCDEFGHIJKcipher alphabet E EFGHIJKLMNOPQRSTUVWXYZABCDcipher alphabet R RSTUVWXYZABCDEFGHIJKLMNOPQcipher alphabet O OPQRSTUVWXYZABCDEFGHIJKLMNcipher alphabet I IJKLMNOPQRSTUVWXYZABCDEFGH

    plain LETRO ISJAN VIERA TREIZ EHEUR ESETDkey LEROI LEROI LEROI LEROI LEROI LEROIciphered WIKFW TWAOV GMVFI EVVWH PLVIZ PWVHL

    19th centurycryptanalysis of the Vigenre cipher (Babbage, Kasiski and thencoincidence index in 1920)

    S. Vaton & C.Fontaine (TB) November 2014 20 / 62

    16

  • History (4/6)20th century

    1st world war : Vernam cipher (1917, published in 1926) or"one-time pad" : ci = mi + ki mod [2], where the plain text m andthe cipher text c are represented as a series of bits, and where the keyk is a random bit stream, of the same length as the message, and usedone and only one time. It can be seen as an extension of the Vigenrecipher with randomness and no period in the key.

    ?

    6

    - cipher textkey

    stream

    plain text

    (encoding)

    ?

    -

    -keystream

    plain text

    (decoding)

    Rem : it is the only cipher that has been proved to be unconditionnallysecure but it requires a key as long as the message itself (proven by C.Shannon in 1949).

    S. Vaton & C.Fontaine (TB) November 2014 21 / 62

    History (5/6)

    2nd world war : Enigma machineGerman electro-mechanical rotor ciphermachine.German military texts enciphered onthe Enigma machine were first bro-ken by Polish cryptanalysts. Poles theninitiated French and British cryptana-lysts into their Enigma decryption tech-niques. During the war, British crypto-logists decrypted a vast number of mes-sages enciphered on Enigma.

    1948 : development by Claude Shannon of information theory.Theoretical framework to coding and information security.

    S. Vaton & C.Fontaine (TB) November 2014 22 / 62

    17

  • History (6/6)

    1977 : standardization of DES (Data Encryption Standard) by NIST(National Institute of Standards, USA), after a call for proposals

    1987 : RC4 (Ronald Rivest) ; very popular cipher because of its speedand simplicity ; supported in SSL/TLS (for https) and WEP (for WiFinetworks)

    1999 : E0 (Bluetooth)

    1999 : A5 (GSM)

    2000 : standardization of the AES (Advanced Encryption Standard)by NIST in the US, after a call for proposals

    regular call for proposals for new algorithms and benchmarks(NIST, NoE ECRYPT)

    S. Vaton & C.Fontaine (TB) November 2014 23 / 62

    Cipher Keys

    Kerckhoffs principle (1883) : the cipher (i.e. the algorithm used forencryption/decryption) is known by the cryptanalyst ; the security isbased on the secret of the (decryption) key,

    standardization of the cipher

    in most cases the security cannot be perfect, the security is based onthe tremendous computational burden of an attack that wouldattempt to retrieve decipher the cipher text without decryption keyit must be "impossible" to do so, except for entities with an extremelylarge computational power

    the number of possible keys must be large enough to prevent bruteforce attacks constraints on minimum key lengths.

    S. Vaton & C.Fontaine (TB) November 2014 24 / 62

    18

  • Notion of Key : Symetric Cryptographyvs. Public Key Cryptography

    Taxonomy of CiphersSymetric Cryptography :

    I the ssame (secret) key is used for encryption and decryption 1,I Exemples : Caesar, Vigenre, Vernam, DES, RC4, RC6, Idea, Blowfish,

    AES, A5, E0, etcI Remark : all the ciphers that we have mentioned up to now belong to

    this categoryPublic Key Cryptography :

    I each user in the system has a pair of keys (public key, private key), thepublic key is used for encryption and the private key is used fordecryption

    I in a context of signature, the private key is used for signing and thepublic key is used for verifying the signature

    I Exemples : RSA, El Gamal, elliptic curve cryptographyI Remark : those ciphers have been developed after 1977

    1. more precisely the decryption key can be deduced very easily from the encryptionkey ; ex : k et -k.S. Vaton & C.Fontaine (TB) November 2014 25 / 62

    History (7)

    Public key cryptography

    1977 : W. Diffie and M. Hellmann, key exchange protocol, first steptowards public key cryptography

    1978 : R. Rivest, A. Shamir et L. Adleman, RSA cipher (based onnumber theory, prime numbers)

    1978 : Mc Eliece cipher Niederreiter cipher (both of them are basedon error correcting codes theory)

    1985 : El Gamal cipher (probabilistic)

    1987 : first cipher based on elliptic curves

    1994 : OAEP (Optimal Asymetric Encryption Padding), a way to useRSA in real life (probabilistic)

    S. Vaton & C.Fontaine (TB) November 2014 26 / 62

    19

  • Keystone of public key cryptography : one way functions

    One way functions : functions which are easy to compute (polynomialtime) but very difficult to reverse, except for the person who knows aparticular secret ;-).In order to find out the secret key from the public key it is necessaryto reverse a one way function, which is "impossible" except for theowner of the key who knows the secret

    Examples :I factorisation in a product of two very large prime numbers : N = p q.

    The security of the RSA cryptosystem is based on the difficulty of thisproblem.

    I discret logarithm : x is the discrete logarithm of a in base g , denotedas logg (a), if a = g x mod [N] (where g is the generator of (Z/NZ)).The security of cryptographic schemes such as Diffie Hellman or ElGamal is based on the difficulty of this problem.

    S. Vaton & C.Fontaine (TB) November 2014 27 / 62

    Keystone of public key cryptography : one way functions

    One way functions : functions which are easy to compute (polynomialtime) but very difficult to reverse, except for the person who knows aparticular secret ;-).In order to find out the secret key from the public key it is necessaryto reverse a one way function, which is "impossible" except for theowner of the key who knows the secret

    Examples :I factorisation in a product of two very large prime numbers : N = p q.

    The security of the RSA cryptosystem is based on the difficulty of thisproblem.

    I discret logarithm : x is the discrete logarithm of a in base g , denotedas logg (a), if a = g x mod [N] (where g is the generator of (Z/NZ)).The security of cryptographic schemes such as Diffie Hellman or ElGamal is based on the difficulty of this problem.

    S. Vaton & C.Fontaine (TB) November 2014 27 / 62

    20

  • RSA Cryptosystem (1/2)

    RSA : Rivest, Shamir, Adleman, 1977 ; one of the first public keycryptosystem and still the most important one

    RSA KeysI 2 large prime numbers p and q and their product N = p q,I e, integer coprime to (N) = (p 1)(q 1) (and consequently e is

    invertible modulo (N)),I The public key is the couple (e,N) (e : encryption exponent ; N : RSA

    modulus).I let d be the inverse of e modulo (N)I The private key is d (decryption exponent). The prime factors p and q

    of N have to remain private.RSA encryption and decryption

    I the plain text is identified to an integer M such that 2 M N 1I encryption : C = Me mod [N] (modular exponentiation)I decryption : Cd mod [N]I it can be proven, thanks to the Euler theorem, that Cd mod [N] = M

    S. Vaton & C.Fontaine (TB) November 2014 28 / 62

    RSA Cryptosystem (1/2)

    RSA : Rivest, Shamir, Adleman, 1977 ; one of the first public keycryptosystem and still the most important oneRSA Keys

    I 2 large prime numbers p and q and their product N = p q,I e, integer coprime to (N) = (p 1)(q 1) (and consequently e is

    invertible modulo (N)),I The public key is the couple (e,N) (e : encryption exponent ; N : RSA

    modulus).I let d be the inverse of e modulo (N)I The private key is d (decryption exponent). The prime factors p and q

    of N have to remain private.

    RSA encryption and decryptionI the plain text is identified to an integer M such that 2 M N 1I encryption : C = Me mod [N] (modular exponentiation)I decryption : Cd mod [N]I it can be proven, thanks to the Euler theorem, that Cd mod [N] = M

    S. Vaton & C.Fontaine (TB) November 2014 28 / 62

    21

  • RSA Cryptosystem (1/2)

    RSA : Rivest, Shamir, Adleman, 1977 ; one of the first public keycryptosystem and still the most important oneRSA Keys

    I 2 large prime numbers p and q and their product N = p q,I e, integer coprime to (N) = (p 1)(q 1) (and consequently e is

    invertible modulo (N)),I The public key is the couple (e,N) (e : encryption exponent ; N : RSA

    modulus).I let d be the inverse of e modulo (N)I The private key is d (decryption exponent). The prime factors p and q

    of N have to remain private.RSA encryption and decryption

    I the plain text is identified to an integer M such that 2 M N 1I encryption : C = Me mod [N] (modular exponentiation)I decryption : Cd mod [N]I it can be proven, thanks to the Euler theorem, that Cd mod [N] = M

    S. Vaton & C.Fontaine (TB) November 2014 28 / 62

    RSA Cryptosystem (2/2)

    RSA SecurityI 2 equivalent problems :

    F factorize N = pqF knowing e and N (public key) find out d (private key)

    I RSA security is based on the difficulty ot the problem of large integersfactorization

    Exercice1 prove that Cd mod [N] = M2 prove that the 2 above mentioned problems are equivalent

    S. Vaton & C.Fontaine (TB) November 2014 29 / 62

    22

  • Pros and Cons (1/4)Symmetric Cryptography

    fast encryption and decryptionEncryption and decryption are based on simple basic operations(permutations, substitutions, XOR, shifts, etc...) which are adapted tofast data processing and hardware acceleration.Perfect security for Vernam cryptosystem (One-Time Pad),computational security for other cryptosystemsbut requires a shared secret key ; how is it possible to share a secretkey on an unsecure channel ?

    Public key cryptographyencryption and decryption are much slower (non trivial mathematicalcomputations, such as modular exponentiation)computational security only, even if there are"arguments of proofs" ofsecuritydoesnt require a shared secretnecessary to certify public keys (PKI, Public Key Infrastructures)

    S. Vaton & C.Fontaine (TB) November 2014 30 / 62

    Pros and Cons (1/4)Symmetric Cryptography

    fast encryption and decryptionEncryption and decryption are based on simple basic operations(permutations, substitutions, XOR, shifts, etc...) which are adapted tofast data processing and hardware acceleration.Perfect security for Vernam cryptosystem (One-Time Pad),computational security for other cryptosystemsbut requires a shared secret key ; how is it possible to share a secretkey on an unsecure channel ?

    Public key cryptographyencryption and decryption are much slower (non trivial mathematicalcomputations, such as modular exponentiation)computational security only, even if there are"arguments of proofs" ofsecuritydoesnt require a shared secretnecessary to certify public keys (PKI, Public Key Infrastructures)

    S. Vaton & C.Fontaine (TB) November 2014 30 / 62

    23

  • Pros and Cons (2/4)In practice : combination of public key and symmetric cryptography

    key exchange protocol (such as Diffie-Hellmann) to build a sharedsecret. This shared secret is then used as the key in a symmetriccryptosystem.

    OR : hybrid cryptosystemI key encapsulation scheme : public key cryptography is used to cipher

    the key and share it between sender and receiverI data encapsulation scheme : the shared secret key is used to encrypt

    and decrypt the data

    Alice Bob

    m

    K

    -AES? AES(m)

    - AES1

    6

    -RSA RSA1?

    Pub(Bob)RSA(K ) ?

    Priv(Bob)

    K?

    -?

    m

    S. Vaton & C.Fontaine (TB) November 2014 31 / 62

    Pros and cons (3/4)

    Key lengths For an equivalent security level :

    Symmetric CryptographyI smaller keysI at least 128 bits for a good security level

    Public Key CryptographyI in general, longer keysI example : RSA modulus, at least 1024 bitsI other example : elliptic curve cryptography, smaller keys than RSA

    http://www.keylength.com/fr/5/ sums up recommandations about keylengths for different cryptosystems, different time horizons, and different securitylevels

    S. Vaton & C.Fontaine (TB) November 2014 32 / 62

    24

  • Pros and Cons (4/4)

    Example : recommandations of ECRYPT II (2012).

    S. Vaton & C.Fontaine (TB) November 2014 33 / 62

    Sommaire

    1 IntroductionRequirements in terms of securityWhy cryptography ?

    2 Confidentiality through Encryption

    3 Digital Signature

    4 Trusting Public Keys . . .

    5 Zero knowledge proofs

    6 In practiceAuthentication : KerberosAuthentification et cl de session : SSL/TLS et SSH

    7 Conclusion

    S. Vaton & C.Fontaine (TB) November 2014 34 / 62

    25

  • Digital Signature (1/2)Digital Signature goals : authentification of the sender, integrity of thedata, non repudiation (the sender cannot pretend not having signed thedata because it is impossible to coin a valid signature without the secretkey)

    Legal value : (France) law of march 2000, decree of march 2001

    Digital signature is enabled by public key cryptographyThe private key is used to sign,the validity of the signature is checked with the public key.

    Examples :RSA (factorisation),El Gamal (discrete logarithm),DSA, Digital Signature Algorithm : variation of El Gamal ; developpedby NIST and NSA (1994) ; governmental origin, doubts on theexistence of backdoors

    S. Vaton & C.Fontaine (TB) November 2014 35 / 62

    Naive implementation

    -

    Alice Bob

    ?Priv(Alice)

    6 6

    Pub(Alice)

    ?=?

    Problem : computation workload(public key cryptography on a big file).

    S. Vaton & C.Fontaine (TB) November 2014 36 / 62

    26

  • Implementation with a hash function

    -

    Alice Bob

    Hash

    Hash Function

    ?

    Priv(Alice)

    ?

    66

    Hash

    Pub(Alice)

    Hash Function

    ?Hash

    ?6=?

    h : {0, 1} {0, 1}m fixed size hash value, easy to compute, difficult to reverseExamples : MD5 (128), SHA-1 (160), RIPE-MD 160, SHA-256, . . .The problem of computational burden has been solved.

    But possible collision problems ! Cryptographic has functions must be used,sufficiently secure (not MD5 !).

    S. Vaton & C.Fontaine (TB) November 2014 37 / 62

    Sommaire

    1 IntroductionRequirements in terms of securityWhy cryptography ?

    2 Confidentiality through Encryption

    3 Digital Signature

    4 Trusting Public Keys . . .

    5 Zero knowledge proofs

    6 In practiceAuthentication : KerberosAuthentification et cl de session : SSL/TLS et SSH

    7 Conclusion

    S. Vaton & C.Fontaine (TB) November 2014 38 / 62

    27

  • Public Key Infrastructures (PKI)

    Public Key Infrastructures (PKI) : in charge of the management anddistribution of keys for public key cryptography

    terminology : certification authoritymissions :

    I generation for any entity that requires it of a pair of keys (public key,private key) after verification of the identity of this entity

    I creation and management of digital certificatesdigital certificate : includes

    I identity of the entity (institution, DNS server, email adress...)I value of the public keyI validity date and utilizations of the keyI identity of the authority that has delivered the certificateI signature of the certificate

    NB : Only the certification authority is able to sign the public key (the private keyof the certification authority is necessary to sign the certificate). The validity ofthe signature can be checked with the public key of the certification authority.

    S. Vaton & C.Fontaine (TB) November 2014 39 / 62

    Digital Certificates

    X.509 CertificatesX.509 : recommandation of the UIT (Int. Tlcom. Union)X.509 certificates are used in many solutions such as S/MIME (digitalsignature of emails), IPSec or SSL (secure tunnels)format des certificats X.509Certificate VersionSerial NumberAlgo. used to sign the certificateName of the certification authorityValidity PeriodCertificates OwnerOwners Public KeyAdditional Information (on the owner or on the ciphers)Signature of the Certificate (algotithms used for signature, and signature)

    S. Vaton & C.Fontaine (TB) November 2014 40 / 62

    28

  • Example of X.509 certificate : emitted by "Direction des Impts" during2004 tax declaration

    S. Vaton & C.Fontaine (TB) November 2014 41 / 62

    Digital certificates

    Example usage of a digital certificate : setting up a secure connection to anenterprise server

    1 the client browser connects to the enterprise server to pick up thename of the PKI and the reference of the enterprise certificate (serialnumber)

    2 the client connects to the PKI site and downloads the certificate3 it checks the validity period4 it checks the certificate authenticity ; for example :

    I if the signature has been produced with MD5 hash followed by RSAencryption

    I it decodes the RSA signature with the public key of the certificationauthority

    I it hashes the public key of the enterprise server with MD5I if both quantities are equal then the certificate is authenticated

    S. Vaton & C.Fontaine (TB) November 2014 42 / 62

    29

  • Certification authorities

    Hierarchy of certification authorities

    AC

    AC

    ACAC

    Panoramix

    ALICE BOB

    Limits of PKI infrastructuresmany certification autorithies : inter-operability problemslack of trust of users in the reliability of certification authorities ;example : fake Microsoft certificates emitted by Diginotar

    S. Vaton & C.Fontaine (TB) November 2014 43 / 62

    Certification authorities : who are you trusting ?Consciously or not . . .

    S. Vaton & C.Fontaine (TB) November 2014 44 / 62

    30

  • The PGP model

    PGP (Pretty Good Privacy ; Phil Zimmermann, 1991)I used to sign data, to encode/decode emails, folders, drive partitions, to

    ensure the security of emailsI uses symmetric cryptography and public key cryptography (hybrid

    cryptography)F encryption/decryption with a secret key IDEAF the IDEA secret key is encrypted with the RSA public key of the

    receiverI standard OpenPGP (IETF, RFC 4880) : initially, encryption and

    authentication of emails ; extended to OpenSSH and to secure web(TLS)

    Key certification in PGPI digital seal that guarantees the authenticity of public keysI trust is based on the notion of social proximity rather than on a central

    certification authorityI each user releases his own public key ; each user can sign the public key

    of another user ; trust in a public key signed by someone who is trusted

    S. Vaton & C.Fontaine (TB) November 2014 45 / 62

    The PGP model

    PGP (Pretty Good Privacy ; Phil Zimmermann, 1991)I used to sign data, to encode/decode emails, folders, drive partitions, to

    ensure the security of emailsI uses symmetric cryptography and public key cryptography (hybrid

    cryptography)F encryption/decryption with a secret key IDEAF the IDEA secret key is encrypted with the RSA public key of the

    receiverI standard OpenPGP (IETF, RFC 4880) : initially, encryption and

    authentication of emails ; extended to OpenSSH and to secure web(TLS)

    Key certification in PGPI digital seal that guarantees the authenticity of public keysI trust is based on the notion of social proximity rather than on a central

    certification authorityI each user releases his own public key ; each user can sign the public key

    of another user ; trust in a public key signed by someone who is trusted

    S. Vaton & C.Fontaine (TB) November 2014 45 / 62

    31

  • Sommaire

    1 IntroductionRequirements in terms of securityWhy cryptography ?

    2 Confidentiality through Encryption

    3 Digital Signature

    4 Trusting Public Keys . . .

    5 Zero knowledge proofs

    6 In practiceAuthentication : KerberosAuthentification et cl de session : SSL/TLS et SSH

    7 Conclusion

    S. Vaton & C.Fontaine (TB) November 2014 46 / 62

    Zero knowledge proofs (1/3)

    Zero-knowledge proofused for authenticationprinciple : prove that one knows a secret without making possible foran eavesdropper to catch any information about this secret on theunsecure channelhow ? prove that one is capable to answer successfully to a particular"challenge"public key cryptography :

    I uses one way functions ; examples : discrete logarithm, quadraticresidues (Fiat-Shamir), ...

    I uses random masks

    S. Vaton & C.Fontaine (TB) November 2014 47 / 62

    32

  • Zero knowledge proofs (2/3)Proofs of knowledge of discrete logarithmsPublic values : p, prime integer and , primitive root modulo p.

    The prover P needs to convince the verifier V that he knows the discretelogarithm s of I = s mod [p] (without transmitting s as plain text on thechannel) ; the prover P is identified by I in the eyes of V .

    3 Steps Protocol1 Commitment : P chooses r modulo p 1 randomly and transmits

    t = r mod [p] to V .2 Challenge : V chooses randomly in {0, 1} and communicates his

    choice to P .3 Answer : P must provide to V :

    I x = r mod [p 1] if = 0I x = r + s mod [p 1] if = 1

    V then computes x mod [p] which must be equal to t if = 0 andto It if = 1.

    S. Vaton & C.Fontaine (TB) November 2014 48 / 62

    Zero knowledge proofs (3/3)

    Proof of knowledge of discrete logarithmsExercice

    1 Is it possible for an intruder to authenticate oneself in the eyes of Vwithout knowing the secret s ? What is the probability that he iscaught ? And what if the same protocol is applied n times ?

    2 What is the quantity r useful for ?3 What happens if is taken off from the protocol ? Is it possible for the

    intruder to authenticate himself ? And what if the random numbergenerator used to produce is not good ?

    S. Vaton & C.Fontaine (TB) November 2014 49 / 62

    33

  • Sommaire

    1 IntroductionRequirements in terms of securityWhy cryptography ?

    2 Confidentiality through Encryption

    3 Digital Signature

    4 Trusting Public Keys . . .

    5 Zero knowledge proofs

    6 In practiceAuthentication : KerberosAuthentification et cl de session : SSL/TLS et SSH

    7 Conclusion

    S. Vaton & C.Fontaine (TB) November 2014 50 / 62

    Sommaire

    1 IntroductionRequirements in terms of securityWhy cryptography ?

    2 Confidentiality through Encryption

    3 Digital Signature

    4 Trusting Public Keys . . .

    5 Zero knowledge proofs

    6 In practiceAuthentication : KerberosAuthentification et cl de session : SSL/TLS et SSH

    7 Conclusion

    S. Vaton & C.Fontaine (TB) November 2014 51 / 62

    34

  • Authentication : particular case of Kerberos (1/2)

    Kerberosnetwork authentication service, developped by MIT ; standardKerberos v5 (RFC 1510 )key distribution center : authentication server to identify distantclients, ticket delivery server to authorize them to use the networkservicesbased on symmetric cryptography (DES), and the usage of tickets(with limited validity)The Kerberos server knows some servers and clients who are in hisdomain. It shares a secret key with each client or server in his domain.Possibility of inter-domain authentification thanks to a dialog betweenKerberos servers.

    S. Vaton & C.Fontaine (TB) November 2014 52 / 62

    Authentication : particular case of Kerberos (2/2)Usage : a user wants to proceed to a transaction with a server

    the user sends its identifier to the authentication serverthe authentication checks the access rights of the user and sends himan initial ticket. The initial ticket is encrypted with a key derived fromthe clients password. It contains : a ticket for access to the ticketdelivery service, a session key (used to cipher the nextcommunications)the user decrypts the initial ticket with his passwordwith this access ticket and his session key he sends an encryptedrequest to the ticket delivery service to ask for an access to a servicethere exists a mutual authentication system that enables the clientand the server to identify each other

    Kerberos Securitytemporary validity of tickets, which limits the possibility of replayattackssensitive to password cracking attacksvulnerability of Kerberos servers which must be very well secured

    S. Vaton & C.Fontaine (TB) November 2014 53 / 62

    35

  • Sommaire

    1 IntroductionRequirements in terms of securityWhy cryptography ?

    2 Confidentiality through Encryption

    3 Digital Signature

    4 Trusting Public Keys . . .

    5 Zero knowledge proofs

    6 In practiceAuthentication : KerberosAuthentification et cl de session : SSL/TLS et SSH

    7 Conclusion

    S. Vaton & C.Fontaine (TB) November 2014 54 / 62

    SSL/TLS Protocol

    SSL/TLSSSL : Secure Socket Layer (originally developped by Netscape)then TLS = Transport Layer Security [TLS v1.1 = SSL v3.1].(developped at IETF Internet Engineering Task Force)

    Goals of SSL/TLSauthentication of both parties thanks to certificatesconfidentiality of exchanged data ; symmetric encryption : DES,3-DES, RC4, AESintegrity of data ; hash functions : MD5, SHA-1

    OpenSSLopen implementation of SSL/TLS http://www.openssl.orgencryption/decryption, signature, certificates management

    S. Vaton & C.Fontaine (TB) November 2014 55 / 62

    36

  • Operation of SSL/TLS (1/2)

    establishment of a secure tunnel (encrypted) between client and serverafter an authentication stepindependant from the used protocol (HTTP, FTP, POP, IMAP...)acts as an additional security layer between transport layer andapplication layer

    TCP/IP

    APPLICATIONS

    HTTP IMAP etc ...

    TCP/IP

    SSL, TLS

    APPLICATIONS

    HTTPS IMAPS etcs ...

    S. Vaton & C.Fontaine (TB) November 2014 56 / 62

    Operation of SSL/TLS (2/2)

    Initial handshake

    -Hello, can we talk ?

    Hello, here is my certificate, and here are the ciphers that I support

    -OK, (here is my certificate), we are going to talk in XXX, with key YYY

    secure tunnel

    S. Vaton & C.Fontaine (TB) November 2014 57 / 62

    37

  • Operation of SSL/TLS

    HTTPS : secure WebURL starting by https :// and padlockNote : some servers use weak cryptography (40 bits) ; configure yourbrowser to accept only what you consider as sufficient in terms ofsecurity !

    IMAPSsame functionalities as IMAPwith moreover encrypted identification

    S. Vaton & C.Fontaine (TB) November 2014 58 / 62

    SSH Secure SHellSSH

    secure connection to a machine on an unsecure network (securetunnel)

    I handled functionalities : secure data communication (downloading),remote command-line login, remote command execution

    I secure channel over an insecure network between two computers, aserver and a client running SSH server and SSH client programs

    I designed as a replacement for Telnet (and other insecure remoteprotocols) which send information, notably passwords, as plaintext

    Puts in operation :I authentication (password, key, Kerberos token)I encryption (symmetric cryptography, public key cryptography)I signature, integrity (hashing)

    two versions of the protocol :I SSH-1 : unsecure ; possible to gain root privilegesI SSH-2 : more secure (several session keys, client-server and server-client

    transactions are independent, certification, tokens to avoid replay...)

    S. Vaton & C.Fontaine (TB) November 2014 59 / 62

    38

  • Network Security Course - November 2014 1

    Crypto Lab Secure mail, Public-Key Cryptography and PKI

    1 Overview

    The learning objective of this lab is for students to get familiar with the concepts in the Public-Key encryp-tion and Public-Key Infrastructure (PKI). Furthermore, this lab is going to be illustrated with the help ofsecure mail exchange. After finishing the lab, students should be able to gain a first-hand experience onsecure mail exchange, public-key encryption, digital signature, public-key certificate, certificate authority,authentication based on PKI.

    2 Lab Environment and organization

    2.1 Work organization

    1. Work in a group of THREE people.

    2. This Lab will be evaluated based on the reports you are going to submit. Please, see the last sectionregarding the submission and the format of the report.

    2.2 Installing OpenSSL.

    In this lab, we will use openssl commands and libraries. They should be present on the computers of theuniversity. If you wish to perform this lab on your own computer, you have to install it in addition. Note,that OpenSSL also exists under Windows, but some of the exercises may not function in the same way asunder Linux, so if you chose to do it on your own computer under Windows, be prepared to spend somemore time resolving the issues.

    2.3 Some links you might find helpful

    This Lab requires a significant amount of autonomous work. Read the tasks and the provided supportingmaterial very carefully.

    Do not hesitate to do your own research and to seek solutions to the problems you encounter on the web.Here is an example resource related to OpenSSL:

    http://www.madboa.com/geek/openssl/

    3 Lab Tasks

    A Certificate Authority (CA) is a trusted entity that issues digital certificates. The digital certificate certi-fies the ownership of a public key by the named subject of the certificate. A number of commercial CAsare treated as root CAs; VeriSign is the largest CA at the time of writing. Users who want to get digitalcertificates issued by the commercial CAs need to pay those CAs.

    For the first task we will be using a free, but not widely accepted CA. For the rest of the tasks we willbe creating our own CA (which will be even less widely accepted).

    41

    Crypto Lab

  • Network Security Course - November 2014 2

    3.1 Task 1: Obtain a personal certificate and send signed mails

    This task can be performed under Windows or Linux with no restrictions or differences.In this task we will see how to obtain free personal certificates and use them to sign our outgoing emails.

    This task requires the configuration of a full email client (or more formally a mail user agent (MUA)).There exist multiple MUAs for Linux, Windows and Mac OS X. We will be using the open-source, multi-platform email client Mozilla Thunderbird, which is already installed on the universitys computers.

    3.1.1 E-mail client configuration

    We will be using our university e-mail accounts for this task. Configure Thunderbird to access your e-mailaccount by specifying the appropriate parameters:

    E-mail address: your email at FINGIncoming mail server (IMAPS): the FING IMAPS serverOutgoing mail server (SMTPS): the FING SMTPS serverAccount name: user login

    Verify that youve correctly configured your MUA by sending an email to yourself and then receiving it.What is the difference between the protocols IMAP and IMAPS, and SMTP and SMTPS?

    3.1.2 Client certificate generation

    Obtain a free client certificate from the following provider http://www.cacert.org/ for your schoole-mail address. Please note, that the procedure may vary depending on your browser and OS. Use theinformation provided on the web site of CACert to generate the certificate.

    Thanks to a special code contained in the html page, the web site instructs the browser to generate akey pair. The private key of the user remains on the local disk. The public key is then sent to the authoritythat generates the certificate. Finally, the CA will send you an e-mail informing you when your certificate isready.

    Describe the procedure youve followed to generate your certificate and answer the following questions:

    1. Why do we have to download and install the certificate of the Certificate Authority (CA) beforeinstalling our own certificate?

    2. Which is the precise identity of the CA?

    3. The certificate is valid from which date to which date?

    4. In which field of the certificate you find your e-mail? Your public key? The CA?

    When downloading the root certificate you are provided with several possible download formats and thechecksum (also known as thumbprint in this context) with two algorithms (SHA1 and MD5).

    Answer the following questions:

    1. What is the use of this information?

    2. How can these checksums be verified? Try looking at the openssl package and related resources forhelp.

    3. Is it possible for a dedicated attacker with unlimited resources to circumvent this protection mecha-nism?

    42

  • Network Security Course - November 2014 3

    4. If it is possible, why is this mechanism still in place?

    5. Propose a way of distributing the root certificate that does not suffer the problems youve pointed out

    Thunderbird has its own certificate store and does not share it with other applications. In order to beable to send signed and/or encrypted e-mails, you have to import it to Thunderbird (and potentially export itfirst from the browser) by using a file in the format pkcs12.

    Import certificate to Thunderbird:

    Tools / Options / Privacy / Security /Show certificates / Authorities / Import

    Why do we need to install the certificates in the MUA and the web browser separately? Is there asystem repository of certificates? Is it used by all browsers and all MUAs?

    3.1.3 Exchange of encrypted and/or signed e-mails

    Exchange e-mails with your teammate. Make a table containing the sizes of the different e-mails:

    1. raw content exchanged whenever you have a signed mail

    2. signed and encrypted mail

    3. an encrypted mail

    4. a non-signed and non-encrypted mail

    You can access the raw content exchange via the menu View/Message Source. Describe your observationand analysis.

    3.2 Task 2: Become a Certificate Authority (CA)

    In this lab, we need to create digital certificates, but we are not going to pay any commercial CA. We willbecome a root CA ourselves, and then use this CA to issue certificate for others (e.g. servers). In thistask, we will make ourselves a root CA, and generate a certificate for this CA. Unlike other certificates,which are usually signed by another CA, the root CAs certificates are self-signed. Root CAs certificates areusually pre-loaded into most operating systems, web browsers, and other software that rely on PKI. RootCAs certificates are unconditionally trusted.

    Include all generated files (certificates, etc.) in your submission.

    The Configuration File openssl.conf. In order to use OpenSSL to create certificates, you have tohave a configuration file. The configuration file usually has an extension .cnf. It is used by three OpenSSLcommands: ca, req and x509. The manual page of it can be found at http://wwwneu.secit.at/web/documentation/openssl/openssl_cnf.html. You can also get a copy of the configurationfile from /usr/lib/ssl/openssl.cnf. After copying this file into your current directly, you need tocreate several sub-directories as specified in the configuration file (look at the [CA default] section):

    dir = ./demoCA # Where everything is keptcerts = $dir/certs # Where the issued certs are keptcrl_dir = $dir/crl # Where the issued crl are keptnew_certs_dir = $dir/newcerts # default place for new certs.

    43

  • Network Security Course - November 2014 4

    database = $dir/index.txt # database index file.serial = $dir/serial # The current serial number

    For the index.txt file, simply create an empty file. For the serial file, put a single number instring format (e.g. 1000) in the file. Once you have set up the configuration file openssl.cnf, you cancreate and issue certificates.

    Certificate Authority (CA). As we described before, we need to generate a self-signed certificate for ourCA. This means that this CA is totally trusted, and its certificate will serve as the root certificate. You canrun the following command to generate the self-signed certificate for the CA:

    $ openssl req -new -x509 -keyout ca.key -out ca.crt -config openssl.cnf

    You will be prompted for information and a password. Do not lose this password, because you willhave to type the passphrase each time you want to use this CA to sign certificates for others. You will alsobe asked to fill in some information, such as the Country Name, Common Name, etc. The output of thecommand are stored in two files: ca.key and ca.crt. The file ca.key contains the CAs private key,while ca.crt contains the public-key certificate.

    3.3 Task 3: Create a Certificate for PKILabServer.com

    If you do this part on a university computer, please use the name of the computer you are currently workingon (of the form pc-df-XXX.priv.enst-bretagne.fr) instead of PKILabServer.com.

    Now, we become a root CA, we are ready to sign digital certificates for our customers. Our first customeris a company called PKILabServer.com. For this company to get a digital certificate from a CA, it needsto go through three steps.

    Step 1: Generate public/private key pair. The company needs to first create its own public/private keypair. We can run the following command to generate an RSA key pair (both private and public keys).You will also be required to provide a password to protect the keys. The keys will be stored in the fileserver.key:

    $ openssl genrsa -des3 -out server.key 1024

    Step 2: Generate a Certificate Signing Request (CSR). Once the company has the key file, it shouldgenerates a Certificate Signing Request (CSR). The CSR will be sent to the CA, who will generate a certifi-cate for the key (usually after ensuring that identity information in the CSR matches with the servers trueidentity). Please use PKILabServer.com as the common name of the certificate request.

    $ openssl req -new -key server.key -out server.csr -config openssl.cnf

    Step 3: Generating Certificates. The CSR file needs to have the CAs signature to form a certificate. Inthe real world, the CSR files are usually sent to a trusted CA for their signature. In this lab, we will use ourown trusted CA to generate certificates:

    44

  • Network Security Course - November 2014 5

    $ openssl ca -in server.csr -out server.crt -cert ca.crt -keyfile ca.key \-config openssl.cnf

    If OpenSSL refuses to generate certificates, it is very likely that the names in your requests do not matchwith those of CA. The matching rules are specified in the configuration file (look at the [policy match]section). You can change the names of your requests to comply with the policy, or you can change the policy.The configuration file also includes another policy (called policy anything), which is less restrictive.You can choose that policy by changing the following line:

    "policy = policy_match" change to "policy = policy_anything".

    Include all generated files (certificates, etc.) in your submission.

    3.4 Task 4: Use PKI for Web Sites

    If you do this part on a university computer, you will be unable to modify the hosts file. In this case, pleasetake a look at it, but continue on without changing it.

    In this lab, we will explore how public-key certificates are used by web sites to secure web browsing.First, we need to get our domain name. Let us use PKILabServer.com as our domain name. To get ourcomputers recognize this domain name, the following entry should be added to /etc/hosts; this entrybasically maps the domain name PKILabServer.com to our localhost (i.e., 127.0.0.1):

    127.0.0.1 PKILabServer.com

    In Windows, this file can be found under

    C:\Windows\System32\Drivers\etc\hosts

    Please, after adding this line to the file, make sure that it works:

    $ ping pkilabserver.comPING PKILabServer.com (127.0.0.1): 56 data bytes64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.058 ms64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.103 ms64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.081 ms

    Next, let us launch a simple web server with the certificate generated in the previous task. OpenSSLallows us to start a simple web server using the s server command:

    # Combine the secret key and certificate into one file% cp server.key server.pem% cat server.crt >> server.pem

    # Launch the web server using server.pem% openssl s_server -cert server.pem -www

    By default, the server will listen on port 4433. You can alter that using the -accept option. If youare doing the lab on the university computers, please choose a port number between 30000 and 39999,and use it throughout the rest of the exercise instead of 4433. Now, you can access the server using thefollowing URL: https://PKILabServer.com:4433/. Most likely, you will get an error message

    45

  • Network Security Course - November 2014 6

    from the browser. In your browser, you will see a message like the following: pkilabserver.com:4433 usesan invalid security certificate. The certificate is not trusted because the issuer certificate is unknown.

    Had this certificate been assigned by VeriSign, we will not have such an error message, because VeriSignscertificate is very likely preloaded into your browsers certificate repository already. Unfortunately, thecertificate of PKILabServer.com is signed by our own CA (i.e., using ca.crt), and this CA is notrecognized by the browser. There are two ways to get Firefox to accept our CAs self-signed certificate.

    1. We can request Mozilla to include our CAs certificate in its Firefox software, so everybody usingFirefox can recognize our CA. This is how the real CAs, such as VeriSign, get their certificates intoFirefox. Unfortunately, our own CA does not have a large enough market for Mozilla to include ourcertificate, so we will not pursue this direction.

    2. Load ca.crt into Firefox: We can manually add our CAs certificate to the Firefox browser byclicking the following menu sequence:

    Edit -> Preference -> Advanced -> View Certificates.

    You will see a list of certificates that are already accepted by Firefox. From here, we can import ourown certifcate. Please import ca.crt, and select the following option: Trust this CA to identifyweb sites. You will see that our CAs certificate is now in Firefoxs list of the accepted certificates.

    Now, point the browser to https://PKILabServer.com:4433. Please describe and explain yourobservations. Please also do the following tasks:

    1. Modify a single byte of server.pem, and reload the URL. What do you observe? Make sure yourestore the original server.pem afterward.

    2. Since PKILabServer.com points to the localhost, if we use https://localhost:4433 in-stead, we will be connecting to the same web server. Please do so, describe and explain your obser-vations.

    Include screenshots of your navigator showing the stages through which you have passed duringthis task.

    3.5 Task 5: Performance Comparison: RSA versus AES

    In this task, we will study the performance of public-key algorithms. Please prepare a file (message.txt)that contains a 16-byte message. Please also generate an 1024-bit RSA public/private key pair. Then, do thefollowing:

    1. Encrypt message.txt using the public key; save the the output in message enc.txt.

    2. Decrypt message enc.txt using the private key.

    3. Encrypt message.txt using a 128-bit AES key.

    4. Compare the time spent on each of the above operations, and describe your observations. If an opera-tion is too fast, you may want to repeat it for many times, and then take an average. You might wantto look at the Linux command time which measures the duration of the execution of a command.

    5. Try running the tests over a significant number of repetitions, e.g. 1000 or more executions of thecommand. Hint: use a script that runs the command the required number of times, and then use thecommand time to calculate the overall time of execution.

    46

  • Network Security Course - November 2014 7

    4 Submission

    You need to submit a detailed lab report to describe what you have done and what you have observed; youalso need to provide explanation to the observations that are interesting or surprising. In your report, youneed to answer all the questions listed in this lab.

    The rules for the submission are:

    1. Submit an archive containing all generated files, along with your report. (except the certificates yougenerated from CACert, which you may wish to continue using afterwards).

    2. Provide your report in PDF format.

    3. Name the file of the archive youre submitting in the following way : NAME1 NAME2 NAME3-TP Crypto

    4. Limit the size of your report to no more than 11 pages.

    Please, send your report by email to [email protected]

    0

    This Lab is based on the Labs developed by Sylvain Gombault, TELECOM Bretagne and Wenliang Du,Syracuse University.

    The development of this document is funded by three grants from the US National Science Foundation:Awards No. 0231122 and 0618680 from TUES/CCLI and Award No. 1017771 from Trustworthy Computing.Permission is granted to copy, distribute and/or modify this document under the terms of the GNU FreeDocumentation License, Version 1.2 or any later version published by the Free Software Foundation. A copyof the license can be found at http://www.gnu.org/licenses/fdl.html.

    47

  • Tutorial sur lalgorithme RSA

    Sandrine Vaton

    Tlcom Bretagne, Dpartement Informatique

    Juin 2013

    S. Vaton (TB/INFO) RES201 Juin 2013 1 / 36

    Sommaire

    1 Description

    2 BasesArithmtique modulairePreuve du RSAInversion ModulaireExponentiation Modulaire

    3 Scurit du RSAFactorisation dun grand entierCls RSA

    4 Tests de primalit

    S. Vaton (TB/INFO) RES201 Juin 2013 2 / 36

    49

    RSA Tutorial

  • Algorithme RSA

    RSA : Rivest, Shamir, Adleman ; premier algorithme de chiffrement cl publique et toujours le plus rpandutrs utilis dans le commerce lectronique, et plus gnralement pourchanger des donnes confidentielles sur Internet.invent en 1977, brevet par le MIT en 1983, brevet tomb dans ledomaine public en 2000scurit base sur la difficult du problme de factorisation de grandsentiers (en un produit de deux nombres premiers) :

    N = p q, avec p et q premiers

    I le calcul de N partir de p et q a une complexit polynmiale(multiplication) ;

    I par contre, retrouver p et q premiers partir de leur produit N est unproblme NP-complet

    S. Vaton (TB/INFO) RES201 Juin 2013 3 / 36

    Le RSA en bref (1/2)

    Gnration de Cls1 choisir 2 grands entiers premiers p et q et calculer leur produit

    N = p q.2 calculer (N) = (p 1)(q 1) et choisir un entier e premier avec(N),

    3 calculer laide de lalgorithme dEuclide tendu linverse d de emodulo (N) : d = e1 mod (N).

    La cl publique est le couple (e,N) et la cl prive est d . Les facteurspremiers p et q de N doivent tre maintenus privs.Exemple :

    p = 11 q = 23 N = p q = 253(N) = (p 1)(q 1) = 10 22 = 220

    e = 3 d = 147

    S. Vaton (TB/INFO) RES201 Juin 2013 4 / 36

    50

  • Chiffrement et dchiffrement avec RSA

    Chiffrement avec RSALe message en clair est identifi un entier M dfini modulo N etpremier avec N : 2 M N 1, M 6= p, M 6= q.Pour envoyer un message Bob, Alice cherche la cl publique (e,N)de Bob (dans un annuaire appropri), et elle calcule le message chiffrC = Me mod [N] quelle envoie Bob.

    Dchiffrement avec RSAPour dchiffrer le message C , Bob prend sa cl prive d et calculeCdmod [N].On peut montrer que la valeur obtenue Cd mod [N] = (Me)d

    mod [N] est gale M.N est le module RSA ; e est lexposant de chiffrement (cl publique) ; d estlexposant de dchiffrement (cl secrte) ; les facteurs p et q de N sontmaintenus privs.

    S. Vaton (TB/INFO) RES201 Juin 2013 5 / 36

    Sommaire

    1 Description

    2 BasesArithmtique modulairePreuve du RSAInversion ModulaireExponentiation Modulaire

    3 Scurit du RSAFactorisation dun grand entierCls RSA

    4 Tests de primalit

    S. Vaton (TB/INFO) RES201 Juin 2013 6 / 36

    51

  • Bases pour le RSA

    Nous avons besoin de quelques bases pour prsenter lalgorithmeRSA :

    I bases sur larithmtique modulaireI tests de primalit (Fermat, Miller-Rabin) gnration de la cl secrteI algorithme dEuclide tendu gnration de lexposant de

    dchiffrement partir de lexposant de chiffrementI algorithme dexponentiation rapide fonctions de chiffrement et

    dchiffrementI fonction indicatrice dEuler, thorme dEuler preuve du RSA

    sance de Travaux Pratiques :I implmentation de lalgorithme RSA en langage C

    S. Vaton (TB/INFO) RES201 Juin 2013 7 / 36

    Sommaire

    1 Description

    2 BasesArithmtique modulairePreuve du RSAInversion ModulaireExponentiation Modulaire

    3 Scurit du RSAFactorisation dun grand entierCls RSA

    4 Tests de primalit

    S. Vaton (TB/INFO) RES201 Juin 2013 8 / 36

    52

  • Arithmtique Modulaire

    Elments de ZN :un entier a est dit quivalent un autre entier b si la diffrence entrea et b est un multiple de Nceci dfinit une relation dquivalence entre nombres entiersla classe dquivalence de a est identifie au reste de la division entirede a par N

    Oprations lmentaires dans ZN :somme : amod [N] + bmod [N] = (a + b)mod [N],diffrence : amod [N] bmod [N] = (a b)mod [N],produit : (amod [N]).(bmod [N]) = (a.b)mod [N].

    A partir du produit modulaire on dfinit lexponentiation modulaire :a0mod [N] = 1, a1mod [N] = a, a2mod [N] = a.amod [N] et par rcurrenceanmod [N] = an1mod [N].amod [N].

    S. Vaton (TB/INFO) RES201 Juin 2013 9 / 36

    Inversion Modulaire

    Soit N un entier. Un entier a est inversible modulo N si et seulement si ilexiste un entier b tel que a b = 1 mod [N]. Lentier b est appel linversede a modulo N et est not a1 dans larithmtique modulo[N] note ZN .a est inversible modulo N si et seulement si a et N sont premiers entre eux.Exemples :

    N = 30, a = 17, a est inversible modulo N et son inverse est b = 23car 23 17 = 391 = 1 mod[N].a = 18 nest pas inversible modulo N = 30 car 18 et 30 ne sont paspremiers entre eux.

    S. Vaton (TB/INFO) RES201 Juin 2013 10 / 36

    53

  • Sommaire

    1 Description

    2 BasesArithmtique modulairePreuve du RSAInversion ModulaireExponentiation Modulaire

    3 Scurit du RSAFactorisation dun grand entierCls RSA

    4 Tests de primalit

    S. Vaton (TB/INFO) RES201 Juin 2013 11 / 36

    Thorme dEuler

    Thorme dEuler : si N est un entier naturel et si a est premier avec Nalors

    a(N) = 1 mod [N]

    o (N) est la fonction indicatrice dEuler.Rem1 : le thorme dEuler gnralise le petit thorme de Fermat.Rem2 : ce thorme fonde le test de primalit dit test de Fermat.Rem3 : la preuve du RSA repose sur le thorme dEuler.

    S. Vaton (TB/INFO) RES201 Juin 2013 12 / 36

    54

  • Preuve du RSA

    La preuve repose sur le fait que Z N (ensemble des entiers plus petitsque N, diffrents de p et q, pris modulo N et muni de lamultiplication) est un groupe cyclique dordre (N).Nous devons montrer que Cd mod [N] = M quand C = Me

    mod [N] avec M diffrent de 1, p et q.

    Cd mod [N] = (Me)d mod [N] = Me d mod [N]e d = 1 mod [(N)] = 1+ k (N)Me d mod [N] = M1+k (N) mod [N]= M (M(N))k mod [N]

    et daprs le th. dEuler M(N) = 1 mod [N] donc

    Cd mod [N] = M

    S. Vaton (TB/INFO) RES201 Juin 2013 13 / 36

    Sommaire

    1 Description

    2 BasesArithmtique modulairePreuve du RSAInversion ModulaireExponentiation Modulaire

    3 Scurit du RSAFactorisation dun grand entierCls RSA

    4 Tests de primalit

    S. Vaton (TB/INFO) RES201 Juin 2013 14 / 36

    55

  • Algorithme dEuclide (1/2)

    Entres : deux nombres entiers N et K (N > K )Sortie : PGCD(N,K), le plus grand commun diviseur de N et K .

    N = K q0 + r0K = r0 q1 + r1r0 = r1 q2 + r2

    ...rm2 = rm1 qm + rmrm1 = rm qm+1

    Lalgorithme se termine quand le reste est nul. Le PGCD de N et de K estle dernier reste non nul rm.

    S. Vaton (TB/INFO) RES201 Juin 2013 15 / 36

    Algorithme dEuclide (2/2)

    Exemple 1 : N = 72, K=54

    72 = 54 1+ 1854 = 3 18 PGCD(N,K ) = 18

    Exemple 2 : N=1848, K=945, PGCD(N,K)= ?Exemple 3 : N=4862, K=1320, PGCD(N,K)= ?

    S. Vaton (TB/INFO) RES201 Juin 2013 16 / 36

    56

  • Algorithme dEuclide tendu (1/3)

    Entres : deux entiers N et K (N > K )Sorties : PGCD(N,K) ainsi que les coefficients u et v de lidentit de Bezout

    u N + v K = PGCD(N,K )

    Principe :construire rcursivement des coefficients ai et bi tels queaiN + biK = ri en combinant les galits euclidiennes ; terme on obtient u = am et v = bm puisque pgcd(N,K ) = rm(dernier reste non nul).

    S. Vaton (TB/INFO) RES201 Juin 2013 17 / 36

    Algorithme dEuclide tendu (2/3)Egalits euclidiennes :

    ri2 = ri1qi + rien posant N = r2, et K = r1

    Initialisation :

    r2 = N donc a2 = 1, b2 = 0r1 = K donc a1 = 0, b1 = 1

    Rcursion :

    ri = ri2 ri1qi= (ai2N + bi2K ) (ai1N + bi1K )qi= (ai2 ai1qi )N + (bi2 bi1qi )K

    ai = ai2 ai1qibi = bi2 bi1qi

    S. Vaton (TB/INFO) RES201 Juin 2013 18 / 36

    57

  • Algorithme dEuclide tendu (3/3)

    Complexit chaque itration la valeur du reste est au minimum divise par 2 ;par consquent le nombre ditrations est born par 2 log2(N) ;chaque itration requiert une division, un reste, deux multiplications etdeux soustractions sur des nombres de longueur au plus log2(N) bits ;par consquent la complexit de chaque itration est borne parC1(log2 N)2

    au total la complexit de lAEE est borne par C2(log2 N)3, donccomplexit polynmiale.

    S. Vaton (TB/INFO) RES201 Juin 2013 19 / 36

    Inversion Modulaire

    Soit un entier N et a, un entier premier avec N. Lalgorithme dEuclidetendu donne un moyen de calculer linverse de a modulo N.En effet PGCD(a,N) = 1 et lidentit de Bezout scrit :

    u N + v a = 1 et donc v a = 1mod [N]

    Par consquent le coefficient v de lidentit de Bezout est linverse de amodulo N :

    v = a1mod [N]

    Utilis pour calculer lexposant de dchiffrement d qui doit vrifier d = e1

    mod (N).

    S. Vaton (TB/INFO) RES201 Juin 2013 20 / 36

    58

  • Sommaire

    1 Description

    2 BasesArithmtique modulairePreuve du RSAInversion ModulaireExponentiation Modulaire

    3 Scurit du RSAFactorisation dun grand entierCls RSA

    4 Tests de primalit

    S. Vaton (TB/INFO) RES201 Juin 2013 21 / 36

    Algorithme dexponentiation rapide (1/2)

    Objectif : calculer rapidement me mod [N] un calcul direct ncessiterait e multiplications modulairesRemarque : e peut aussi scrire (reprsentation binaire pure)

    e =

    i ei 2i ei {0, 1}

    et doncme mod [n] =

    i/ei=1 m

    2i mod [n]

    Il suffit donc de calculer les facteurs m2imod [n]

    m()2 m2 ()

    2

    m22 ()2

    m23 ()2

    log2(e) + 1 carrs modulaires au lieu de e multiplications modulaires

    S. Vaton (TB/INFO) RES201 Juin 2013 22 / 36

    59

  • Algorithme dexponentiation rapide (2/2)

    Complexit

    log2(e) + 1 multiplications,chaque multiplication se fait sur des nombres de longueur au pluslog2(N) + 1 bit donc la complexit de chaque multiplication estC1(log2(N))2 [si multiplication scolaire],par consquent la complexit de lalgorithme dexponentiation rapideest C2(log2(N))2 log2(e).

    S. Vaton (TB/INFO) RES201 Juin 2013 23 / 36

    Sommaire

    1 Description

    2 BasesArithmtique modulairePreuve du RSAInversion ModulaireExponentiation Modulaire

    3 Scurit du RSAFactorisation dun grand entierCls RSA

    4 Tests de primalit

    S. Vaton (TB/INFO) RES201 Juin 2013 24 / 36

    60

  • Sommaire

    1 Description

    2 BasesArithmtique modulairePreuve du RSAInversion ModulaireExponentiation Modulaire

    3 Scurit du RSAFactorisation dun grand entierCls RSA

    4 Tests de primalit

    S. Vaton (TB/INFO) RES201 Juin 2013 25 / 36

    Scurit du RSA (1/3)

    La scurit du RSA repose sur la difficult du problme defactorisation dun entier en produit de deux grands facteurs premiers.On peut montrer que les deux problmes suivants sont quivalents :

    1 connaissant e et N (cl publique) retrouver la valeur de d (cl prive) ;2 trouver les facteurs p et q de N.

    S. Vaton (TB/INFO) RES201 Juin 2013 26 / 36

    61

  • Scurit du RSA (2/3)

    Si on connat p et q alors on peut calculer (N) = (p 1).(q 1) et, partir de e (cl publique), retrouver la valeur de d par inversionmodulaire.Si on connat (e,N) (cl publique) et d (cl prive) on peut retrouverraisonnablement facilement p et q.En effet si on connaissait non seulement N mais aussi (N) ontrouverait p et q comme les racines de lquation du second degr :

    () x2 (N + 1 (N))x + N = 0

    En effet le produit des racines de (*) est N = p.q et la somme desracines est p + q == N + 1 (N) puisque(N) = (p 1)(q 1) = p.q (p + q) + 1 = N (p + q) + 1.

    S. Vaton (TB/INFO) RES201 Juin 2013 27 / 36

    Scurit du RSA (3/3)

    Supposons connatre e et d . On sait que (N) divise e d 1 puisquee d = 1 mod (N) = 1+ k (N).

    e est gnralement petit (rapidit du chiffrement), par ailleurs d < (N)par consquent k est petit (de lordre de quelques milliers) et (N) estgrand.

    On explore les diffrentes valeurs possibles de k (en commenant par lesplus petites), et pour chaque valeur (N) correspondante, on dtermine silquation (*) a des racines entires. Si (*) a des racines entires alors cesracines sont p et q.

    S. Vaton (TB/INFO) RES201 Juin 2013 28 / 36

    62

  • Sommaire

    1 Description

    2 BasesArithmtique modulairePreuve du RSAInversion ModulaireExponentiation Modulaire

    3 Scurit du RSAFactorisation dun grand entierCls RSA

    4 Tests de primalit

    S. Vaton (TB/INFO) RES201 Juin 2013 29 / 36

    Construction de Cls en RSA (1/2)

    aujourdhui on considre que pour que lalgorithme soit sr il faut queN soit de longueur minimale 1024 bits ; les longueurs de cl sonthabituellement comprises entre 1024 et 2048 bits.par ailleurs, pour viter que lon puisse factoriser N il faut que chacundes facteurs p et q soit grand (longueur de lordre de 512 bits auminimum) ;il faut que la diffrence entre p et q soit elle-mme grande (longueurminimale de 500 bits cest--dire que p et q doivent prsenter aumoins une diffrence sur les 12 premiers bits).

    S. Vaton (TB/INFO) RES201 Juin 2013 30 / 36

    63

  • Construction de Cls en RSA (2/2)

    Mthode de factorisation de Fermat :Supposons par exemple que p > q et notons p = s + t et q = s t. AlorsN = p.q = (s + t).(s t) = s2 t2.

    Si la diffrence 2t entre p et q est petite on retrouve facilement p et q.

    En effet on remarque que N + t2 = s2 et on retrouve s et t en testant unepar une les valeurs de t de longueur faible (disons quelques millions devaleurs) et on cherche la valeur t pour laquelle lquation N + t2 = s2

    possde une solution s entire.

    S. Vaton (TB/INFO) RES201 Juin 2013 31 / 36

    Sommaire

    1 Description

    2 BasesArithmtique modulairePreuve du RSAInversion ModulaireExponentiation Modulaire

    3 Scurit du RSAFactorisation dun grand entierCls RSA

    4 Tests de primalit

    S. Vaton (TB/INFO) RES201 Juin 2013 32 / 36

    64

  • Tests de Primalit

    Pour pouvoir gnrer les facteurs p et q il faut tre capablede gnrer un nombre au hasard : gnrateurs pseudo-alatoires,de tester si ce nombre est un nombre premier : tests de primalit

    Les tests de primalit sont donc un sujet particulirement important encryptographie cl publique.Dans le cadre de ce cours nous allons tudier deux tests de primalit (ditsprobabilistes) :

    le test de Fermat,le test de Miller-Rabin.

    S. Vaton (TB/INFO) RES201 Juin 2013 33 / 36

    Test de Fermat (1/2)

    Thorme de Fermat :Soit p un entier premier. Alors pour tout nombre a 6= 0 mod [p] on a lersultat suivant :

    ap1 = 1 mod [p]

    Rem : Le thorme de Fermat est un cas particulier du thorme dEuler.Test de Fermat :Cest un des tests de primalit les plus simples. Le test repose sur leprincipe suivant :

    choisir une base a au hasard (2 a p 1) et calculer ap1 mod [p] ;si le rsultat est diffrent de 1 alors p est composite ;

    si le rsultat est 1 alors p est peut-tre premier ;

    rpter la procdure un grand nombre de fois tant quon na pas trouv debase a pour laquelle p ne passe pas le test.

    S. Vaton (TB/INFO) RES201 Juin 2013 34 / 36

    65

  • Test de Fermat (2/2)

    Le test de Fermat est un test probabiliste :sil existe une base a0 pour laquelle p ne passe pas le test alors p nepasse pas le test pour au moins la moiti des bases ;il est alors trs peu probable que, quand on augmente le nombre debases a, on nen trouve pas au moins une pour laquelle p ne passe pasle test ;par contre on ne peut jamais tre sr que p nest pas un nombrecomposite car il existe de (trs rares) nombres composites p quipassent le test pour toute valeur de a ;ces nombres sont appels nombres pseudo-premiers ou nombres deCarmichael ; le plus petit dentre eux est 561 = 3 11 17.

    Malgr lexistence de nombres de Carmichael, le standard RSA a utilis letest de Fermat comme test de primalit jusquen 1997.

    S. Vaton (TB/INFO) RES201 Juin 2013 35 / 36

    Tests probabilistes de primalit

    Il existe diffrents tests probabilistes de primalit.Les plus connus dentre eux sont :

    test de Fermattest de Miller-Rabintest de Solovay-Strassen

    Voir la description de ces tests sur Wikipedia par exemple.

    S. Vaton (TB/INFO) RES201 Juin 2013 36 / 36

    66

  • Travaux Pratiques RSA

    Module F2B401B, Introduction a la Cryptographie

    janvier 2007

    1. Algorithme dEuclide : cet algorithme fournit le plus grand commun diviseur de deux nombres (PGCD).

    Questions :

    Completer la procedure PGCD dans le programme euclide.c Compiler et tester pour differents couples dentiers (A,B).

    Voir la description de lalgorithme dEuclide en annexe.

    2. Algorithme dEuclide etendu : cet algorithme fournit les coefficients (u, v, d) de lidentite de Bezout ou

    d = PGCD(A,B) et ou u et v sont deux entiers tels que u A+ v B = d.

    Utilisation : cet algorithme sert a determiner lexposant de dechiffrement RSA d tel que e d = (n) ou d,

    lexposant de chiffrement RSA, est premier avec (n) = (p 1)(q 1) (n = pq etant le module RSA).Principe : construire recursivement des coefficients ui et vi tels que uiA + viB = ri ou ri est le reste de la

    division euclidienne dans lalgorithme dEuclide.

    Voir la description de lalgorithme dEuclide etendu et de son implementation en annexe.

    Dans le programme euclidee.c,

    La fonction Update realise h = hh et hh = h hh k. A quoi va servir la fonction Update ?

    Remarquer lutilisation des pointeurs dans la fonction Update. Quel est linteret de lutilisation de

    pointeurs ?

    La procedure EuclideExtended calcule les coefficients (u, v, d) de lidentite de Bezout. Cette procedurefait appel a la procedure Update.

    Completer la procedure EuclideExtended.

    Completer le main par un appel a la procedure EuclideExtended.Le main permet de calculer les coefficients de lidentite de Bezout pour 2 entiers saisis au clavier.

    Compiler et tester avec differentes valeurs de A et B.

    1

    69

    RSA Lab

  • 3. Inversion Modulaire.

    Lorsque A et N sont premiers entre eux lidentite de Bezout secrit u A+ v N = 1 et donc u est linverse de

    A modulo N puisque u A = 1 + v N = 1 mod [N ].

    Le programme invmod.c fournit linverse modulo N de A si A et N sont premiers entre eux.

    Dans le programme invmod.c,

    completer la procedure EuclideExtended completer le main :

    appel a la procedure EuclideExtended,

    faire afficher linverse de A modulo N .

    compiler et tester.

    4. Exponentiation modulaire.

    Lalgorithme dexponentation rapide permet de calculer lexponentielle modulaire ax mod [n] avec une com-

    plexite numerique de lordre de log2(x) au lieu de x pour la methode directe.

    Le programme expmod.c permet de comparer la methode directe et la methode rapide.

    La methode directe est donnee (fonction ModExp2). On vous demande :

    dimplemeter la methode rapide (completer la fonction ModExp1), comparer les resultats donnes par ModExp1 et ModExp2.

    5. Tests de primalite.

    De nombreux algorithmes cryptographiques necessitent de generer des tres grands nombres premiers. En

    particulier, le module RSA n est le produit de deux facteurs premiers p et q. Il est donc vital de savoir

    generer des nombres premiers avec un cout de calcul aussi faible que possible.

    Dans ce TP on propose de generer des nombres entiers aleatoires et de tester leur primalite par le test de

    Fermat. Le test de Fermat est expose en Annexe.

    Dans primal.c :

    completer la procedure Premier completer et tester pour differentes valeurs de N

    6. Chiffrement et Dechiffrement RSA.

    Ecrire votre propre programme qui :

    genere aleatoirement les facteurs p et q premiers genere aleatoirement lexposant de chiffrement e, premier avec (n) = (p 1)(q 1) calcule lexposant de dechiffrement correspondant d

    2

    70

  • produit aleatoirement un message (entier compris dans [1...N-1]), le chiffre, puis oublie ce messageet le retrouve en dechiffrant le cryptogramme ; afficher les valeurs du message en clair, du chiffre et du

    message obtenu apres dechiffrement a lecran.

    Question subsidiaire : densite des nombres premiers.

    On rappelle le theoreme de Tchebichev : le nombre dentiers premiers plus petits que N est approximativement

    egal a N/ log(N). Verifier par simulation le theoreme de Tchebichev sur la densite des nombres premiers.

    3

    71

  • Chiffrement RSA

    n est un entier produit de deux nombres premiers p et q :

    n = p q

    n est appele module RSA.

    Lexposant de chiffrement e est un entier premier avec (n) = (p 1)(q 1) ((n) est lindicateur dEuler den).

    Lexposant de dechiffrement d est linverse de e modulo (n) :

    d e = 1 mod (n)

    Le message m est un entier compris entre 1 et n1, le chiffre c est egalement un entier compris entre 1 et n1.Chiffrement

    Le chiffre c est obtenu par :

    c = me mod [n]

    Dechiffrement

    Le message est obtenu par :

    m = cd mod [n]

    4

    72

  • Algorithme dEuclide

    Lalgorithme dEuclide permet de determiner le p.g.c.d. de 2 entiers A et B (B < A) sans faire appel a leur

    factorisation.A = B q0 + r0B = r0 q1 + r1r0 = r1 q2 + r2

    ...

    rm2 = rm1 qm + rmrm1 = rm qm+1

    Lalgorithme se termine quand le reste est nul. Le pgcd de A et de B est le dernier reste non nul rm.

    5

    73

  • Algorithme dEuclide etendu

    Cet algorithme determine, en plus de PGCD(A,B), 2 entiers u et v tels que

    u A+ v B = PGCD(A,B).

    Comment ? On construit recursivement, en combinant les egalites euclidiennes, des coefficients ui et vi tels que uiA +

    viB = ri.

    A terme on obtient u = um et v = vm puisque PGCD(A,B) = rm (dernier reste non nul).

    Egalites euclidiennes :ri2 = ri1qi + ri

    avec A = r2, et B = r1

    Initialisation :r2 = A donc u2 = 1, v2 = 0

    r1 = B donc u1 = 0, v1 = 1

    Puis, par recurrence :ri = ri2 ri1qi

    = (ui2A+ vi2B) (ui1A+ vi1B)qi= (ui2 ui1qi)

    | {z }A+ (vi2 vi1qi)

    | {z }B

    ui = ui2 ui1qivi = vi2 vi1qi

    Implementation de lalgorithme dEuclide etendu

    Initialisation :dividende = A diviseur = B

    u = 1 v = 0

    uu = 0 vv = 1

    Tant que (diviseur 0) faire

    quotient = dividende / diviseur (division entiere)

    reste = dividende-diviseur*quotient

    dividende diviseurdiviseur reste

    unew = = u-uu*quotient

    u uuuu unew

    vnew = v-vv*quotient

    v vvvv vnew

    6

    74

  • Exponentiation modulaire

    Objectif : calculer me mod [n].

    Remarque : e peut aussi secrire (representation binaire pure)

    e =P

    i ei 2i ei {0, 1}

    et donc

    me mod [n] =Q

    i/ei=1m2

    i

    mod [n]

    Il suffit donc de calculer les facteurs m2i

    mod [n]

    m()2 m2 ()

    2

    m22 ()2

    m23 ()2

    log2(e) carres modulaires au lieu de e multiplications modulaires

    7

    75

  • Rappels sur le test de Fermat

    Ce test repose sur le petit theoreme de Fermat qui dit que :

    si N est premier, et si a 6= 0 mod [N ] alors aN1 = 1 mod [N ].On sait aussi que :

    si N est premier on a toujours cette egalite (quelque soit la base a) si N nest pas premier il se peut que, pour certaines valeurs de la base a, cette egalite soit quand meme verifiee : maisrassurez-vous, cest quand meme rare...

    Soit N un entier (impair). On cherche a determiner, avec une probabilite derreur aussi petite que possible, si N est

    premier.

    Test de Fermat :

    generer un nombre aleatoire a dans 2, 3, . . . , N 1 calculer a(N1)/2 mod [n]

    si a(N1)/2 mod [n] est different de 1 et 1 alors N nest pas premier (et cest sr) si a(N1)/2 mod [n] est egal a 1 ou 1 alors N a de grandes chances detre premier

    Bien sr, les grincheux vous diront que cela ne marche pas a tous les coups :

    il existe des nombres N non premiers pour lesquels legalite a(N1)/2 mod [N ] {1,1} est verifiee pour certainesvaleurs de la base a : ce sont les nombres pseudo premiers (qui portent aussi le joli nom de nombres de Poulet).

    Exemple : 341 est pseudo-premier pour la base 2.

    Il y en a meme (les coquins) pour lesquels legalite a(N1)/2 mod [N ] {1,1} est toujours vraie, quelque soit labase a choisie ! Ces nombres sont appeles nombres de Carmichael, ou encore nombres pseudo premiers absolus.

    Exemple : le plus petit dentre eux est 561 (561 = 11 3 17).Si on a lidee de se dire que le test de Fermat ne marche pas mais quen essayant differentes valeurs de la base a, par

    recoupement on devrait y arriver, on a perdu puisque N peut tres bien etre un nombre de Carcmichael.

    Cependant, les nombres de Carmichael sont tres rares. Ainsi la proportion de nombres pseudo premiers pour la base 2

    est inferieure a 1 sur 1 million pour les entiers jusqua 25 milliards, et cette proportion est encore plus petite pour N grand.

    Donc on peut appliquer le test de Fermat avec une fiabilite relativement grande.

    8

    76

  • FORMULAIRE DEXERCICES DE CRYPTOGRAPHIE

    TELECOM Bretagne

    Novembre 2014

    Question1Chiffrement de CsarLe chiffrement de Csar est le schma de chiffrement par substitution mono-alphabtique le plussimple. Il sagit dun chiffrement par dcalage qui consiste simplement dcaler les lettres de lal-phabet dun nombre de crans constant vers la droite.Dcrypter le texte suivant qui a t obtenu en appliquant le chiffre de Csar sur un texte en languefranaise dans lequel les espaces ont t supprims :

    Indice : lhistogramme suivant vous donne la frquence dapparition des lettres en franais

    Question2Algorithme dEuclide tenduCalculer linverse de 7 modulo 40.

    1

    79

    Public Key Cryptography Exercices

  • Question3Exponentiation modulaireCalculer 27 mod 55, puis 1823 mod 55.

    Question4Echange de cl de Diffie Hellman

    1. Vrifier que g = 2 est un gnrateur du groupe multiplicatif Z11.2. Quel est le secret commun qutablissent Alice et Bob en utilisant le protocole de Diffie-Hellman

    avec p = 11 et g = 2 si les nombres alatoires quils ont choisi sont xA = 7 et xB = 8.

    Question5RSASoit p = 3, q = 13, n = pq = 39 et e = 29.1. Calculer d tel que ed = 1mod(n).2. Chiffrer le message m = 2 et vrifi

    er le rsultat en le dchiffrant.

    Question6RSAVous interceptez le cryptogramme c = 10 qui a t