prof.ssa sophia danesino

49
Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18 1/49 Esame di Stato a.s. 2018/19 Classe 5A Informatica Classe 5B Informatica TECNOLOGIE E PROGETTAZIONE DI SISTEMI INFORMATICI E DI TELECOMUNICAZIONI DISPENSE INTEGRATIVE prof.ssa Sophia Danesino

Upload: others

Post on 17-Nov-2021

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

1/49

Esame di Stato a.s. 2018/19

Classe 5A InformaticaClasse 5B Informatica

TECNOLOGIE E PROGETTAZIONE DI

SISTEMI INFORMATICI E DI TELECOMUNICAZIONI

DISPENSE INTEGRATIVE

prof.ssa Sophia Danesino

Page 2: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

IndiceCLIL - Cryptography...............................................................................................................3

1. Introduction..................................................................................................................................3[SCAFFOLDING] Overhear/Evesdrop......................................................................................3Security concerns........................................................................................................................4

Secrecy...............................................................................................................................4Authentication....................................................................................................................5Message Integrity...............................................................................................................5Non repudiation.................................................................................................................7

Cryptography vs cryptology vs cryptanalysis.............................................................................8Check point.................................................................................................................................9

2. Confidentiality/Secrecy..............................................................................................................11[SCAFFOLDING] The words of cryptography........................................................................11Symmetric Encryption..............................................................................................................12Check your understanding........................................................................................................13Kerckhoffs's principle...............................................................................................................15

Basic Properties: correctness and security.....................................................................................16Substitution ciphers........................................................................................................................19

The Caesar cipher......................................................................................................................19The cypher wheel......................................................................................................................19Breaking the cipher...................................................................................................................20Monoalphabetic substitution.....................................................................................................21Vigenere cipher.........................................................................................................................22

Transposition ciphers.....................................................................................................................27A transposition cipher: the spartan scytale................................................................................28

Frequency analysis.........................................................................................................................29XOR cipher....................................................................................................................................30

One Time Pad encryption method.............................................................................................31CRITTOGRAFIA ASIMMETRICA.........................................................................................32

Scambio di chiavi Diffie-Hellman.................................................................................................32RSA................................................................................................................................................35

FIRMA DIGITALE.................................................................................................................38Generazione e verifica della firma digitale....................................................................................38Certificati elettronici......................................................................................................................39

Lo standard X.509 per i certificati............................................................................................40Infrastruttura a chiave pubblica (PKI).......................................................................................41

Funzioni di hash.............................................................................................................................45Funzione unidirezionale (one way function).............................................................................47Sicurezza debole........................................................................................................................47Sicurezza forte...........................................................................................................................47

Message Authentication Code (MAC)...........................................................................................48BIBLIOGRAFIA E SITOGRAFIA..........................................................................................49

2/49

Page 3: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

CLIL - Cryptography

1. Introduction

[SCAFFOLDING] Overhear/Evesdrop

Read the following sentences and guess the difference between overhear and eavesdrop:• We overheard the teacher say there would be a test today.• There was Trudy eavesdropping outside the door.

To overhear means to accidentally hear what other people are saying, when they do not know thatyou have heard.

To eavesdrop refers to a situation in which you deliberately listen secretly to other people'sconversations.

3/49

Page 4: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Security concerns

Alice and Bob want to communicate "securely", but what precisely does this mean?

http://www.science.smith.edu/~jcardell/Courses/EGR328/Readings/KR%20Security.pdf

Let us introduce Alice and Bob, two people who want to communicate "securely." Alice and Bobare well-known fixtures in the security community, perhaps because their names are more funthan a generic entity named "A" that wants to securely communicate with a generic entity named"B." Illicit love affairs, wartime communication, and business transactions are the commonly citedhuman needs for secure communications; preferring the first to the latter two, we're happy to useAlice and Bob as our sender and receiver, and imagine them in this first scenario. We said thatAlice and Bob want to communicate "securely," but what precisely does this mean? Certainly, Alicewants only Bob to be able to understand a message that she has sent, even though they arecommunicating over an "insecure" medium where an intruder (Trudy, the intruder) may intercept,read, and perform computations on whatever is transmitted from Alice to Bob. Bob also wants tobe sure that the message that he receives from Alice was indeed sent by Alice, and Alice wants tomake sure that the person with whom she is communicating is indeed Bob. Alice and Bob alsowant to make sure that the contents of Alice's message have not been altered in transit. Giventhese considerations, we can identify the following desirable properties of secure communication.

SecrecyOnly the sender and intended receiver should be able to understand the contents of thetransmitted message. Because eavesdroppers may intercept the message, this necessarilyrequires that the message be somehow encrypted (disguise data) so that an intercepted messagecan not be decrypted (understood) by an interceptor. This aspect of secrecy is probably the mostcommonly perceived meaning of the term "secure communication." Note, however, that , forexample, Alice might also want the mere fact that she is communicating with Bob (or the timing orfrequency of her communications) to be a secret!

AuthenticationBoth the sender and receiver need to confirm the identity of other party involved in thecommunication - to confirm that the other party is indeed who or what they claim to be. Face-to-face human communication solves this problem easily by visual recognition. When communicating

4/49

Page 5: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

entities exchange messages over a medium where they can not "see" the other party,authentication is not so simple. Why, for instance, should you believe that a received emailcontaining a text string saying that the email came from a friend of yours indeed came from thatfriend? If someone calls on the phone claiming to be your bank and asking for your accountnumber, secret PIN, and account balances for verification purposes, would you give thatinformation out over the phone? Hopefully not.

Message IntegrityEven if the sender and receiver are able to authenticate each other, they also want to insure thatthe content of their communication is not altered, either malicously or by accident, intransmission.

Having established what we mean by secure communication, let us next consider exactly what ismeant by an "insecure channel." What information does an intruder have access to, and whatactions can be taken on the transmitted data? Alice, the sender, wants to send data to Bob, thereceiver. In order to securely exchange data, while meeting the requirements of secrecy,authentication, and message integrity, Alice and Bob will exchange both control message and datamessages. All, or some of these message will typically be encrypted. A passive intruder canlisten to and record the control and data messages on the channel; an active intruder can removemessages from the channel and/or itself add messages into the channel.

5/49

Page 6: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Quiz

SUMMARY - The Story of Alice and Bob

• Alice and Bob: generally, Alice wants to send a message to Bob.

6/49

Page 7: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Non repudiation

Information security is about constructing and analyzing protocols that overcome the influence ofadversaries and that are related to various aspects in information security such as dataconfidentiality, data integrity, authentication, and non-repudiation.

• Confidentiality is a set of rules that limits access to information• Data integrity prevents changes to information during transmission• Authentication is the process of confirming the identity of a person

Authentication verifee who you are (Ueer-ID) while Non-Repudiation verifee what you did (e.geending a meeeage).

• Authentication allows to determine whether a person is really who it claims to be.• Non repudiation meane to eneure that a traneferred meeeage hae been eent and received

by the partiee claiming to have eent and received the meeeage. Non repudiation ie a way toguarantee that the sender of a message cannot later deny having sent the messageand that the recipient cannot deny having received the meeeage.A malicioue ueer can capture a eigned meeeage and poet it multiple timee. Therefore a partycan repudiate having eent the eame meeeage multiple timee. Making each meeeage uniqueueing timeetampe ie therefore ueed for non-repudiation in combination with eigning andencryption.

7/49

Page 8: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Cryptography vs cryptology vs cryptanalysis

• Cryptography: from Greek κρυπτός kryptós, "hidden, secret" and γράφειν graphein,"writing", writing secretes

• Cryptology: from Greek κρυπτός kryptós, "hidden, secret" and -λογία -logia, "study", thescience of secrets

• Cryptanalysis: (from the Greek kryptós, "hidden", and analýein, "to loosen" or "to untie") isthe study of analyzing information systems.

8/49

Page 9: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Check point

A. Match the terms and the cartoons1.

CONFIDENTIALITY – AUTHENTICATION – NON REPUDIATION – DATA INTEGRITY

A. B.

C. D.

1 A: DATA INTEGRITY B: CONFIDENTIALITY C: NON REPUDIATION D: AUTHENTICATION

9/49

Page 10: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

B. What are we talking about?

“Data passes between a client and a Web service, sometimes through one ormore intermediaries. Messages may also be kept in repositories, such asmessage queues or databases. Some of the data within the messages isconsidered to be sensitive in nature. There is a risk that an attacker can gainaccess to sensitive data, either by eavesdropping on the network or accessinga repository.”2

C. Fill the gaps3

Data integrity is the opposite of data ………….., which is a form of ……… loss. The overall

intent of any data integrity technique is the same: ensure data is transmitted/recorded

……... as intended and upon receing/later retrieval, ensure the data is the …...... as it was

originally. In short, data integrity aims to prevent …….. to information. Data integrity is not

to be confused with data……., the discipline of protecting data from unauthorized parties.

exactly - data - same - corruption - security – changes

D. Match the following terms and their definition4:

Cryptology Analyzing (breaking) secretsCryptography Science of hidingCryptanalysis Secret writing

2 SECURITY3 Data integrity is the opposite of data corruption, which is a form of data loss. The overall intentof any data integrity technique is the same: ensure data is transmitted/recorded exactly asintended and upon receing/later retrieval, ensure the data is the same as it was originally. In short,data integrity aims to prevent changes to information. Data integrity is not to be confused with datasecurity, the discipline of protecting data from unauthorized parties.4 Cryptology Science of hiding Cryptography Secret writing Cryptanalysis Analyzing (breaking) secrets

10/49

Page 11: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

2. Confidentiality/Secrecy

[SCAFFOLDING] The words of cryptography

• Data that can be read and understood is called plaintext or cleartext.

• The method of disguising (disguise: mascherare, read disgais) plaintext in such a way asto hide its substance is called encryption.

Encrypting plaintext results in unreadable text called cyphertext.

• The process of reverting cyphertext to its original plaintext is called decryption.

• Theencryption function takes a plaintext and produces a cyphertext.

• A message is PUT OVER an insecure channel. A message COMES OUT from a channel.

Noun: The message doesn't make sense; I think it's written in a cipher. Verb: Cipher the message so that no one but us can understand it.

11/49

By the end of this module you’ll be able to describe the block schema of ENCRYPTION and DECRYPTION

US: CIPHER UK: CYPHER

Page 12: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Symmetric Encryption

http://youtu.be/dk40W6ULb0I?list=PLAA92F9967A520440[0.00-2.25]

Encryption is the process of encoding messages in such a way that only authorized parties canread it. In an encryption scheme, the message, referred to as plaintext, is encrypted using anencryption algorithm, generating ciphertext that can only be read if decrypted. Communicatingparties must have the same key before they can achieve secure communication.

Example

Let's imagine a substitution cipher in which each letter in the plaintext is 'shifted' a certain numberof places down the alphabet. For example, with a shift of 1, A would be replaced by B, B wouldbecome C, and so on. With a shift of 2, A would be replaced by C, B would become D, and so on.The method is named after Julius Caesar, who apparently used it to communicate with hisgenerals.

Function: if we translate all of our characters to numbers, 'a'=0, 'b'=1, 'c'=2, ... , 'z'=25 we canrepresent the encryption function, e(x), where x is the character we are encrypting, as:

and the decryption function as:

Key k: the number of characters to shift the cipher alphabet

12/49

Page 13: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Check your understanding

[Eavesdropper] [False]

[True]

[Plaintext, Cleartext]

13/49

Page 14: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

[True] [True]

[Goes from an element of C to an element of M] [Both decryption and decryption are done with the same key]

[True]

14/49

Page 15: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Kerckhoffs's principle

• Kerckhoffs's principle5: a cryptographic system should be secure even ifeverything about the system, except the key, is public knowledge.

• Shannon's maxim6: the enemy knows the system.

http://youtu.be/dFTxdaXosrw?list=PLAA92F9967A520440

5 19 January 1835 – 9 August 19036 April 30, 1916 – February 24, 2001

15/49

Page 16: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Basic Properties: correctness and security

For all messages the result of decrypting the encryption of the message is the same as the message we started with.

QUIZ: Do the following functions satisfy the correctness/security property for asymmetric cypher7?

• Ek(m)=m+k Dk(c)=c-k

• Ek(m)=m Dk(c)=c

• Ek(m)=m%k Dk(c)=c*K

Answer:

http://youtu.be/B7KqXFpyEEE?list=PLAA92F9967A520440

7 From: "Applied cryptography" (Udacity) by Dave Evans

16/49

By the end of this module you’ll be able to verify if a cryptosystemis CORRECT and SECURE

m M messages, c C ciphertexts, k K keys∈ ∈ ∈

Correctness property: m,k: D∀ k(Ek(m))=m

The result of decrypting the encryption of the message is the same as the message we started with.

Security property: A ciphertext reveals nothing about key or message.

Page 17: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Task

Now you’re going to work in pairs to complete a task about the correctness and security properties.The aim is to deeply understand when a cipher is correct and secure.

In each pair I’d you to talk together and find a function that satisfies the correctness property andthe security one.

I’ll give you 5 minutes to complete the task, then I’ll ask you to demonstrate the function youchoose satisfies the properties.

Test1. What does SYMMETRIC cryptography mean?

2. Read the following principles and answer the quiz

Kerckhoffs's principle (1835-1903): acryptographic system should be secureeven if everything about the system,except the key, is public knowledge.

Shannon's maxim (1916-2001): theenemy knows the system.

QUIZ: What parts of a cryptosystem must be kept secret?□ Alice □ Encryption Algorithm □ Decryption Algorithm □ Keys □ Ciphertext

3. With the addition of the key, you are now working with three main elements m, c, k. You want yourencryption function to take the message m and a key k and map that to a ciphertext c. Your decryptionfunction will take a ciphertext and a key and map that to a message.

Correctness property: to be correct you need to obtain the same message after decryption. For allmessages and keys, you have the property that the result of decrypting the ciphertext8, using that key9, is theoriginal message. This can be written as:

Security property: the ciphertext reveals nothing about the key or the message.

8The ciphertext is the result of encrypting using the key and the message.

9 The subscript indicates that there are two inputs for the decryption function: one is the key and one is theinput ciphertext.

17/49

Page 18: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

QUIZ: Which of these functions satisfy the correctness property for a symmetric cipher? Each choice is a pairof functions and the message and the keys are natural numbers:

• M = {1, 2, 3, ...} • K = {1, 2, 3, ...}

QUIZ: Do the following functions satisfy the correctness/security property for a symmetric cipher?

• Ek(m)=m+k Dk(c)=c-k

• Ek(m)=m Dk(c)=c

• Ek(m)=m%k Dk(c)=c*K

18/49

Page 19: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Substitution ciphers

The Caesar cipher

The action of a Caesar cipher is to replace each plaintext letter with a different one a fixed numberof places down the alphabet. The cipher illustrated here uses a left shift of three, so that (forexample) each occurrence of E in the plaintext becomes B in the ciphertext10.

The cypher wheel

A cipher wheel is an encrypting device that consists of two concentric circles inner circle and outercircle.The inner circle is fixed and outer circle is rotated randomly,so that it stops at somepoint.Then ‘A’ of outer circle is tallied with the position of ‘A’ of inner circle.That position isconsidered as key and the mapping of all the positions of outer and inner circles is used asencrypting logic11.

In the picture key = 3 ,since ‘A’ of outer circle is on ‘D’ of inner circle.

10 http://en.wikipedia.org/wiki/Caesar_cipher11 https://impythonist.wordpress.com/2014/09/11/alas-julius-caesar-doesnt-have-python-in-50-bc/

19/49

By the end of this module you’ll know how a SUBSTITUTION cipher works

Page 20: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Breaking the cipher

Breaking the scheme is straightforward. Since there are only a limited number of possible shifts (25in English12: if you shift by 26 you are back to where you started), they can each be tested in turn ina brute force attack. One way to do this is to write out a snippet of the ciphertext in a table of allpossible shifts. The example given is for the ciphertext "EXXEGOEXSRGI":

Caesar cipher coding

Watch the following video from Khan Academy and code an algorithm that encrypts and decrypts aplaintext using the Caesar cipher.

http://youtu.be/sMOZf4GN3oc

Flaw= difetto, Narrow down= restringere/limitare, Consistent= coerente, Blow= colpo.

12 The modern English alphabet consists of 26 letters.

20/49

Page 21: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Monoalphabetic substitution

A monoalphabetic substitution cipher relies on a fixed replacement structure. That is, thesubstitution is fixed for each letter of the alphabet. Thus, if "A" is encrypted to "C", then everytime we see the letter "A" in the plaintext, we replace it with the letter "C" in the ciphertext.

How many checks does a brute-force attack in the worst case?

Solution: there are 26!-1 possible keys.

21/49

Page 22: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Vigenere cipher

Scaffolding: vocabulary

Let's start looking at the following vocabulary:

have a crush on = avere una cotta per (Eve has a crush on Bob)to bud = sbocciare (a budding romance) at all cost = a tutti i costito shift the alphabet BY a certain numbers of lettersto shift a letter BY one/two/.. place/s TO another letterto crack the code = decifrare il codiceit occurs almost 13% of the time = compare quasi il 13% del tempoto thwart = impedireto rip = strappareto rip through sth = to move very powerfully through a place or building, destroying it quickly (diffondersi velocemente)to plague = affliggereas a brief aside = means that the author was discussing one subject, but for a short time, he wishes to give the reader a different point of view or to offer a different way of thinking about the subjectto match up = accoppiareto end up with = finire per (it was obvious throughout the whole romantic comedy that the two characters would end up with each other.)to meet up = incontrarsiit's worth it to ... = vale la pena di ...interwoven = connesso (to weave, wove, woven: intrecciare, tessere)to crop up = saltare fuoriweird = strano, misteriosoprying = impiccione, ficcanaso

Now watch this video from Nate Hardison (Harvard University) and write a summary about thesubstitution ciphers you learnt (try to use the previous vocabulary as much as you can):

http://youtu.be/9zASwVoshiM

22/49

Page 23: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Vigenère cipherVideo transcript

https://www.youtube.com/watch?v=9zASwVoshiM

Meet Alice. Alice has a crush on Bob. Fortunately for Alice, Bobalso has eyes for her. Unfortunately for their budding romance, not only do Alice'sparents disapprove of Bob, but Alice's best friend, Evelyn, has asecret crush on Bob and selfishly wants to keep them apart at allcosts. To send secret messages to each other that Alice's parents can'tunderstand, Alice and Bob have been using a Caesar cipher, whichworks by shifting the alphabet by a certain number of letters as away to generate a new alphabet. Each letter in the originalalphabet is then substituted by its corresponding letter in thenew shifted alphabet. Alice's favorite number is 3, which Bob knows, so she uses 3 asher key. When she shifts the English alphabet by 3 letters, Abecomes D, B becomes E, C becomes F, and so forth. When she gets to the end of the alphabet, to the letters X, Y, andZ, she just wraps around back to the beginning of the alphabet andsubstitutes X with A, Y with B, and Z with C. So when Alice goes to encrypt her secret message to Bob, namely"Meet me at the park at eleven a.m.," she just makes theappropriate substitutions. M becomes P, E becomes H, and so onuntil her unencrypted plain text message is turned into encryptedcipher text: "Phhw ph dw wkh sdun dw hohyhq dp" is definitely notthe most romantic sounding, but Alice believe that it'll do. Alice gives the message to Evelyn to deliver to Bob's house. ButEvelyn instead takes it back to her room and tries to crack thecode. One of the first things Evelyn notices is that the letter Hoccurs 7 times in the message, many more times than any otherletter. Knowing that the letter E is the most common in the Englishlanguage, occurring almost 13% of the time, Evelyn guesses that Hhas been substituted for E in order to make the secret message andtries using a key of 3 to decrypt it. Within minutes, Evelyn figures out Alice's plans and evilly callsAlice's parents. Had Alice and Bob taken CS50, they would haveknown of this frequency analysis attack on the Caesar cipher,which allows it to be broken quite quickly. They would also have known that the cipher is easily subject to abrute-force attack, whereby Evelyn could have tried all of thepossible 25 keys, or shifts of the English alphabet, in order todecipher the message. Why 25 keys and not 26? Well, try shifting any letter by 26positions, and you'll see why. Anyway, a brute-force attack would have taken Evelyn a bit longerbut not long enough to keep her from thwarting Alice and Bob'splans, especially if Evelyn has the aid of a computer which couldrip through all 25 cases in an instant.

23/49

Page 24: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

So, this problem also plagued others who used the Caesar cipher,and therefore people began experimenting with more complexsubstitution ciphers that use multiple shift values instead ofjust one. One of the most well-known of these is called Vigenèrecipher. How do we get multiple shift values? Well, instead of using anumber as the key, we use a word for the key. We'll use eachletter in the key to generate a number, and the effect is thatwe'll have multiple Caesar cipher-style keys for shifting letters.Let's see how this works by encrypting Alice's message to Bob:“Meet me at the park at eleven a.m. ” I, personally, think baconis delicious, so let's use that as the key. If we take the messagein its unencrypted, plain-text format, we see that it's 25 letterslong. Bacon has only 5 letters, so we need to repeat it 5 times tomake it match the length of the plain text: Bacon bacon bacon bacon bacon. As a brief aside, if the number of letters in the plain textdidn't divide cleanly by the number of letters in the key, we justend the final repetition of our key early, using only the letterswe needed to make everything match up. Now we go about finding the shift values. We're going to do thisby using the position of each letter of our key, bacon, in the Ato Z alphabet. Since we're computer scientists, we like to start counting at zeroinstead of 1, so we're going to say that the position of the firstletter of bacon, B, is in position 1 in the zero-indexed A to Zalphabet, not 2, and the position of A is zero, not 1. Using thisalgorithm, we can find the shift values for each letter. To encrypt the plain text and generate cipher text, we just shifteach letter in the plain text by the specified amount, just likewe do with the Caesar cipher, wrapping from Z back to A ifnecessary. M gets shifted by 1 place to become N. The first Edoesn't shift at all, but we shift the second E by 2 places to Gand T by 14 places to H. If we work through the plain text, we end up with, "Negh zf av hufpcfx bt gzrwep oz." Again, not very romantic-sounding but definitely cryptic. If Aliceand Bob had known about Vigenère cipher, would they have been safefrom Evelyn's prying eyes? What do you think? Would you want tolog into your bank account if your bank decided to use Vigenèrecipher to encrypt your communication using your password as yourkey? If I were you, I wouldn't. And while Evelyn might be kept busy long enough for Alice and Bobto have their meet-up, it's not worth it for Alice and Bob tochance it. Vigenère cipher is relatively easy to break if you know the lengthof the key because then you can treat the encrypted cipher text asthe product of a few interwoven Caesar ciphers. Finding the length of the key isn't terribly hard, either. If theoriginal plain-text message is long enough that some words occurmultiple times, eventually you'll see repetition cropping up inthe encrypted cipher text, as in this example, where you see MONCYappear twice.

24/49

Page 25: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Additionally, you can perform a brute-force attack on the cipher.This does take significantly longer than a brute-force attack onthe Caesar cipher, which can be done almost instantaneously with acomputer since instead of 25 cases to check you've got 26ⁿ-1possibilities, where n is the length of the unknown key. This is because each letter in the key could be any of the 26letters, A through Z, and a smart person would try to use a keythat can't be found in a dictionary, which means that you'd haveto test all of the weird letter combinations, like ZXXXFF, and notjust a couple hundred thousand words in the dictionary. The minus 1 comes into the math because you wouldn't want to use akey with only A's, since with our zero-indexed alphabet that wouldgive you the same effect as using a Caesar cipher with a key ofzero. Anyway, 26ⁿ-1 does get large rather quickly, but while youdefinitely wouldn't want to try breaking a cipher by hand thisway, this is definitely doable with a computer. Fortunately for Alice and Bob, and for online banking,cryptographers have developed more secure ways to encrypt secretmessages from prying eyes. However, that's a topic for another time. My name is Nate Hardison. This is CS50.

25/49

Page 26: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Let's play a game!

Encrypt and decrypt the following message "HELLO FROM ITALY" using a polialphabetic cipher (use the key "CLIL")

Vigenère cipher

26/49

Page 27: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Transposition ciphers

Transposition (or anagram) ciphers are where the letters are jumbled up together: instead ofreplacing characters with other characters, this cipher just changes the order of the characters.

This means that the giveaway for a transposition cipher is that frequency analysis shows that theconstituent letters are what would be expected in a standard text (eg. e is the most commonEnglish letter). What typically happens is that the text to be encrypted is arranged in a number ofcolumns. These columns are then reordered resulting in encrypted text eg. (1, 2, 3, 4, 5) -> (4, 5, 3,2, 1). To decrypt you need to workout the number of columns and then rearrange the columns13.

From Encrypting using a keyword-based transposition cipher

https://youtu.be/Y_E0M5vfw3g

h

13 http://www.richkni.co.uk/php/crypta/trans0.php

27/49

Page 28: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

A transposition cipher: the spartan scytale

A scytale14 is a tool used to perform a transposition cipher, consisting of a cylinder with a strip ofparchment wound around it on which is written a message. The ancient Greeks, and the Spartansin particular, are said to have used this cipher to communicate during military campaigns.

A description of how it operated is not known from before Plutarch (50-120 AD):

When the ephors send out an admiral or a general, they make two roundpieces of wood exactly alike in length and thickness, so that each correspondsto the other in its dimensions, and keep one themselves, while they give theother to their envoy. These pieces of wood they call scytalae. Whenever, then,they wish to send some secret and important message, they make a scroll ofparchment15 long and narrow and wind it round their scytale, leaving no vacantspace thereon, but covering its surface all round with the parchment. Afterdoing this, they write what they wish on the parchment, just as it lies wrappedabout the scytale; and when they have written their message, they take theparchment of and send it, without the piece of wood, to the commander. He,when he has received it, cannot get any meaning out of it, since the lettershave no connection, but are disarranged, unless he takes his own scytale andwinds the strip of parchment about it, so that, when its spiral course is restoredperfectly, and that which follows is joined to that which precedes, he readsaround the staf, and so discovers the continuity of the message. And theparchment, like the staf, is called scytale, as the thing measured bears thename of the measure.

Plutarch, Lives (Lysander 19), ed. Bernadotte Perr

Make your own scytale:

http://www.classic-play.com/spies-like-us-secret-codes-pt-2/

14 Read schitali15 Rotolo di papiro

28/49

Page 29: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Frequency analysis

Frequency analysis16 is the study of letters or groups of letters contained in a ciphertext in anattempt to partially reveal the message. The English language (as well as most other languages)have certain letters and groups of letters appear in varying frequencies.

0

0.02

0.04

0.06

0.08

0.1

0.12

0.14

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

This is a chart of the frequency distribution of letters in the English alphabet. As you can see, theletter ‘e’ is the most common, followed by ‘t’ and ‘a’, with ‘j’, ‘q’, ‘x’, and ‘z’ being very uncommon.

Knowing the usual frequencies of letters in English communication, if the encryption method doesnot effectively mask these frequencies it is possible to statistically determine parts of the plaintextfrom looking at the ciphertext alone. Let’s look at an example based on a plaintext encrypted withthe Caesar Cipher – a cipher that provides no protection from frequency analysis.

wkh sdvvzrug lv vhyhq grqw whoo dqbrqh

Let’s get the letter frequencies (how often each letter appears) of this ciphertext.

h = 5v = 4q = 3r = 3g = 3d = 2b = 1k = 1l = 1s = 1y = 1

Okay, so we’ve found our frequencies. The first reaction here is to try h = e and since we know thecipher used is the Caesar cipher we can try a shift of -3 and the message is revealed!

16 http://learncryptography.com/frequency-analysis/

29/49

Page 30: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

XOR cipher

In cryptography, the simple XOR cipher is an encryption algorithm that operates according to theprinciples:

where ⊕ denotes the exclusive disjunction (XOR) operation. With this logic, a string of text canbe encrypted by applying the bitwise XOR operator to every character using a given key. Todecrypt the output, merely reapplying the XOR function with the key will remove the cipher.

For example, the string "Wiki" (01010111 01101001 01101011 01101001 in 8-bit ASCII) can beencrypted with the repeating key 11110011 as follows:

Its primary merit is that it is simple to implement, and that the XOR operation is computationallyinexpensive.

30/49

Page 31: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

One Time Pad encryption method

If the key is random and is at least as long as the message, the XORcipher is much more secure than when there is key repetition within amessage.

With a key that is truly random, the result is a one-time pad (alsoknown as the Vernam17 cipher) which is unbreakable even in theory.

One Time Pad keys are used in pairs. The keys are distributed securely prior to encryption. Onecopy of the key is kept by the sender and one by the recipient.

1. To encrypt plain text data, the sender uses a key string equally long as the plain text. Thekey is used by mixing (XOR-ing) bit by bit, always adding one bit of the key with one bit ofthe plain text to create one bit of cipher text.

2. This cipher text is then sent to the recipient.3. At the recipient’s end, the encoded message is mixed (XOR-ed) with the duplicate copy of

the One Time Key and the plain text is restored.4. Both sender’s and recipient’s keys are automatically destroyed after use, so that erroneous

re-application of the same key is impossible.

The mostcritical aspect of the Vernam cipher is therandomness of the pad sequence. An event sequence can besaid to be truly random if it is impossible to predict the nextevent in the sequence even if the entire state of thegenerating process up to that point is known. Anydeterministic process, such as running software on a computer,can never produce truly random numbers.

17 Gilbert Vernam invented and patented his cipher in 1917 while working at AT&T.

31/49

It is possible to prove that a stream cipher encryption scheme is unbreakable if the following preconditions are met:

1. the key must be as long as the plain text.2. the key must be truly random.3. the key must only be used once

Page 32: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

CRITTOGRAFIA ASIMMETRICA

Il punto debole della crittografia simmetrica è lo scambio della chiave: se questa vieneintercettata la crittografia diventa inutile. Una svolta nella storia della crittografia venne con lacrittografia asimmetrica, conosciuta anche come crittografia a coppia di chiavi, crittografia a chiavepubblica/privata o anche solo crittografia a chiave pubblica: un tipo di crittografia dove ad ogniutente è associata una coppia di chiavi:

• la chiave pubblica, che viene distribuita, con cui si cifra• la chiave privata, con cui si cifra, che deve rimanere segreta.

In questo modo si evitano i problemi relativi allo scambio dell'unica chiave utile allacifratura/decifratura presente invece nella crittografia simmetrica.

La crittografia a chiave pubblica fu una vera rivoluzione nella storia della crittografia, preceduta daun meccanismo per lo scambio sicuro della chiave.

Scambio di chiavi Diffie-Hellman

Lo scambio di chiavi Diffie-Hellman (Diffie-Hellman key exchange) è un protocollo crittografico checonsente a due entità di stabilire una chiave condivisa e segreta utilizzando un canale dicomunicazione insicuro (pubblico) senza la necessità che le due parti si siano scambiateinformazioni o si siano incontrate in precedenza. La chiave ottenuta mediante questo protocollopuò essere successivamente impiegata per cifrare le comunicazioni successive tramite unoschema di crittografia simmetrica.

Il protocollo per lo scambio di chiave Diffie-Hellman fu sviluppato da Diffie ed Hellman nel 1976.

Possiamo intuire il funzionamento tramite l’uso di colori: l’idea è che è facile mischiare due o piùcolori, ma è praticamente impossibile ricavare i colori di partenza a partire dal colore condiviso.

32/49

Page 33: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Questo meccanismo si ritrova nella fattorizzazione dei numeri primi.

Il protocollo ha due parametri di sistema p e g, sono entrambi pubblici. Il parametro p è un numeroprimo e il parametro g (generalmente chiamato generatore) è un intero minore di p.

Supponiamo che Bob e Alice si vogliano accordare su una chiave segreta condivisa usando ilprotocollo di Diffie-Hellman, procederanno come segue:

• Alice genera un valore casuale a che solo lei conosce e Bob fa altrettanto generando b.

• Quindi ricaveranno i loro numeri pubblici usando i parametri p e g e i loro numeri privati. Il

valore pubblico di Alice è A=ga mod p, mentre quello di Bob sarà B=gb mod p.

• A questo punto si scambiano i loro valori pubblici.

• Alice calcola Bamod p = (gb)a mod p = k

• Bob calcola A bod p = (ga)b mod p. = k

Alice e Bob hanno una chiave segreta condivisa k.

33/49

Page 34: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

In questo modo si risolve il problema della distribuzione delle chiavi: Bob infatti deve generare unasola coppia di chiavi e può distribuire a chi vuole la propria chiave pubblica.

Le due chiavi, pubblica e privata, sono fra loro correlate ma è estremamente difficile risalire allaseconda conoscendo la prima. Questa difficoltà è di natura matematica, o meglio, è legataad un problema matematico18 particolarmente difficile da risolvere.

18 Il problema del logaritmo discreto

34/49

Page 35: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

RSA

In crittografia la sigla RSA indica un algoritmo di crittografia asimmetrica, inventato nel 1977 daRonald Rivest, Adi Shamir e Leonard Adleman utilizzabile per cifrare o firmare informazioni.

Il sistema di crittografia si basa sull'esistenza di due chiavi distinte, che vengono usate per cifrare edecifrare. Se la prima chiave viene usata per la cifratura, la seconda deve necessariamente essereutilizzata per la decifratura e viceversa. La questione fondamentale è che nonostante le duechiavi siano fra loro dipendenti, non è possibile risalire dall'una all'altra, in modo che seanche si è a conoscenza di una delle due chiavi, non si possa risalire all'altra, garantendo inquesto modo l'integrità della crittografia.

RSA è basato sull'elevata complessità computazionale della fattorizzazione in numeri primi19.In breve dati due numeri primi molto grandi è facile calcolare n=p*q, ma è computazionalmentetroppo lungo trovare i due fattori p e q, noto n.

19 Il teorema fondamentale dell'aritmetica afferma che: ogni numero naturale maggiore di 1 o èun numero primo o si può esprimere come prodotto di numeri primi. Tale rappresentazione èunica, se si prescinde dall'ordine in cui compaiono i fattori.

35/49

Page 36: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Concetto base

Per semplificare il funzionamento immaginiamo che A debba spedire un messaggio segreto a B.

A B

(di B) (di B)

1. B sceglie due chiavi: una privata e una pubblica. Le chiavi sono delle coppie di numeri.2. B invia la propria chiave pubblica ad A. Chiunque può vedere questa chiave.3. A usa questa chiave per cifrare il messaggio. 4. A manda il messaggio cifrato a B, chiunque può vederlo, ma non decifrarlo. 5. B riceve il messaggio e utilizzando la chiave privata che solo lui conosce lo decifra.

Immaginiamo che la chiave pubblica sia la coppia (n,e) e che quella privata sia (n,d)

Cifratura: c = memod nUn messaggio m viene cifrato attraverso l'operazione memod n trasformandolo nel messaggiocifrato c.

Decifrazione: m =cd mod nUna volta trasmesso c viene decifrato con cd mod n=m riottenendo il messaggio in chiaro.

Esempio

Il messaggio viene rappresentato come un valore intero. Un messaggio è una sequenza di bit dicui si può trovare l'equivalente decimale.

Se messaggio='m'=100100012=145

quindi crittografare un messaggio equivale a cifrare il suo corrispondente intero decimale.

Supponiamo messaggio=7

Messaggio in chiaro cifrato con (n,e)=(55,3): 73mod 55 =13

Messaggio cifrato decifrato con (n,d)=(55,27): 1327mod 55 =7

36/49

Page 37: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

La generazione delle chiavi

[SOLO LETTURA]

1. Si scelgono a caso due numeri primi p e q abbastanza grandi da garantire la sicurezzadell'algoritmo (sono consigliati almeno 4096 bit): p e q devono rimanere privati!

2. si calcola il loro prodotto n=p*q20, chiamato modulo (dato che tutta l'aritmetica seguente èmodulo n), e il prodotto z=(p-1)(q-1)

3. si calcola la chiave per cifrare: si sceglie un numero 1<e<n, coprimo con z21, la chiavepubblica è (n,e)

4. si calcola la chiave per decifrare: si calcola il numero d tale che e*d mod z=1, la chiaveprivata è (n,d).

La chiave pubblica è (n,e), mentre la chiave privata è (n,d). I due numeri primi p e p possonoessere distrutti, anche se spesso vengono mantenuti insieme alla chiave privata.La forza dell'algoritmo sta nel fatto che per calcolare d da e o viceversa, non basta la conoscenzadi n, ma serve il numero z=(p-1)(q-1) e che il suo calcolo richiede tempi molto elevati; infattifattorizzare in numeri primi (cioè scomporre un numero nei suoi divisori primi) è un'operazionemolto lenta. Solo conoscendo la fattorizzazione di n è possibile trovare il valore delle chiavi. Infatticonoscendo la fattorizzazione di n è possibile calcolare z=(p-1)(q-1) e calcolare d = e-1mod zusando l'algoritmo esteso di Euclide. Da ciò si deduce che la sicurezza dell'RSA dipende dalproblema di fattorizzare grandi numeri. La sicurezza dell'RSA si basa sul fatto che la funzione dicifratura xe mod n è una funzione "one-way" che è computazionalmente difficile da invertire per unnemico che volesse decifrare un messaggio.

Esempio

1. p=5 q=112. n=p*q=5*11=55

z=(p-1)*(q-1)=4*10=403. trovare 1<e<55 tale che MCD(e,40)=1

40=5*23

e=2 MCD(2,40)=2 NOe=3 MCD(3,40)=1 SI

4. trovare d / 3*d mod 40=1d=2 2*3 mod 40=6 NOd=3 3*3 mod 40=9 NO….d=27 27*3 mod 40= 81 mod 40=1 SI

Chiave pubblica = (55,3)

Chiave privata = (55,27)

20 La fattorizzazione di n è segreta e solo chi sceglie i due numeri primi, p e q, la conosce 21 e non ha fattori in comune con z: MCD(e,z)=1

37/49

Page 38: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

FIRMA DIGITALE

Generazione e verifica della firma digitale

I metodi crittografici a chiave pubblica possono essere utilizzati per la generazione della firmadigitale. Mentre nella crittografia la chiave pubblica viene usata per la cifratura, ed il destinatario usa quellaprivata per leggere in chiaro il messaggio, nel sistema della firma digitale:

• il mittente utilizza la sua chiave privata per generare la firma• la firma ed il messaggio vengono inviati al destinatario• il destinatario verifica la provenienza del messaggio, grazie alla chiave pubblica del

mittente. Chiunque può accertare la provenienza del messaggio adoperando la chiave pubblica. L’algoritmo RSA, usato per generare firme elettroniche, si basa semplicemente sull’inversione delruolo delle chiavi rispetto a quello utilizzato per assicurare la riservatezza. Le differenze fra le dueapplicazioni risiedono essenzialmente nel fatto che per la firma digitale si evita di dover applicarel’operazione di cifratura all’intero testo (con notevole risparmio di tempo). Il testo da firmare viene compresso in una sorta di riassunto (detto impronta digitale), tramiteun’apposita funzione di Hash, costruita in modo da rendere minima la probabilità che da testidiversi si possa ottenere il medesimo valore dell’impronta. La dimensione del riassunto è fissa, emolto più piccola di quella del messaggio originale; sicché la generazione della firma risultaestremamente rapida. Poichè la firma è calcolata a partire dall’hash del messaggio, la firma non solo autentica laprovenienza dello stesso, ma ne garantisce l’integrità. Il mittente, infine, non può negare di averinviato il messaggio poiché è l’unico in possesso della chiave privata (non ripudio).

38/49

Page 39: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Certificati elettronici

Nella tecnologia di crittografia a chiave pubblica sia in fase di cifratura sia in fase di verifica diuna firma digitale occorre ritrovare la chiave pubblica o del destinatario di un messaggio o delfirmatario del messaggio firmato. In entrambi i casi la chiave pubblica non è confidenziale; lacriticità sta nel garantire l’autenticità delle chiave pubbliche, ossia sta nell’assicurare che unacerta chiave pubblica appartenga effettivamente all’interlocutore per cui si vuole cifrare o dicui si deve verificare la firma. Se, infatti, una terza parte prelevasse la chiave pubblica deldestinatario sostituendola con la propria, il contenuto dei messaggi cifrati sarebbe disvelatoe le firme digitali potrebbero essere falsificate.

La distribuzione delle chiavi pubbliche è, pertanto, il problema cruciale della tecnologiaa chiave pubblica. Il problema della distribuzione delle chiavi pubbliche è risolto tramitel’impiego dei certificati elettronici. Un certificato è un documento elettronico che associa unachiave pubblica ad una persona fisica/ente. L’utilizzo dei certificati elettronici presuppone,l’esistenza di una Autorità di Certificazione (Certification Authority o CA) che li emetta eli gestisca. La CA firma il certificato.

I compiti di una CA sono:• rilascio e pubblicazione del certificato (firmato con la propria chiave privata)• manutenzione del registro delle chiavi pubbliche• revoca o sospensione dei certificati in caso di istanza dell'interessato o in caso di abusi,

falsificazioni, ecc. e nel contempo aggiornamento della lista pubblica dei certificatisospesi o revocati (certificate revocation list)

39/49

Page 40: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Lo standard X.509 per i certificati

Lo standard ormai diffusamente riconosciuto di definizione del formato dei certificati èquello descritto nello standard X.509 ISO/IEC/ITU [RFC2459] (Visa e MasterCard hanno adesempio adottato le specifiche X.509 come base per la definizione dello standard per ilcommercio elettronico SET, Secure Electronic Transaction).

Ogni certificato è una struttura dati costituita da una parte dati contenente:• versione: indica la versione del formato del certificato (1, 2 o 3) • serial number: è un codice numerico che identifica il certificato tra tutti i certificati emessi

dall’Autorità di Certificazione • signature algorithm: specifica l’algoritmo utilizzato dalla CA per firmare il certificato; è data

dalla coppia funzione hash – algoritmo a chiave pubblica • issuer name: è il nome della CA• subject name: informazioni che identificano univocamente il possessore di una chiave

pubblica• il valore della chiave pubblica• il periodo di validità temporale del certificato (da … a)• la firma digitale della autorità di certificazione con cui si assicura autenticità della

chiave ed integrità delle informazioni contenute nel certificato• Subject Unique Identifier: è una stringa di bit aggiuntivi, opzionale, usata nel caso di

omonimia di due membri in una stessa CA • Issuer Unique Identifier: è una stringa di bit aggiuntivi, opzionale, usata nel caso in cui

nella struttura ad albero ci siano due CA

40/49

Page 41: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Se un intruso tentasse, durante la pubblicazione del certificato, di alterarne il contenuto, lamanomissione sarebbe immediatamente rilevata in fase di verifica della firma sulcertificato; il processo di verifica fallirebbe e l’utente finale sarebbe avvertito della non integritàdella chiave pubblica contenuta nel certificato.

Infrastruttura a chiave pubblica (PKI)

Le infrastrutture a chiave pubblica (Public Key Infrastructure) forniscono ilsupporto necessario affinché la tecnologia di crittografia a chiave pubblica sia utilizzabile sularga scala. Una infrastruttura a chiave pubblica introduce il concetto di third-party trust, ossia di quellasituazione che si verifica quando due generiche entità si fidano implicitamente l’una dell’altrasenza che abbiano precedentemente stabilito una personale relazione di fiducia. Questo èpossibile perché entrambe le entità condiviono una relazione di fiducia con una terza partecomune.

41/49

Page 42: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Third-party trust è un requisito fondamentale per qualsiasi implementazione su larga scalache utilizzi crittografia a chiave pubblica e in una PKI viene realizzata attraverso l’Autoritàdi Certificazione. In Italia sono, ad esempio, Infocamere, Poste italiane, Actalis S.p.A. (elencoaggiornato e completo dei certificatori qualificati nel sito del cnipa www.cnipa.gov.it).

42/49

Page 43: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Il modello di una PKI in realtà prevede due enti: l’autorità di registrazione e quella di certificazione

RA: Autorità di RegistrazioneL’accertamento dell’identità dell’utente richiedente un certificato elettronico, deveprecedere l’effettiva emissione del certificato; è indispensabile procedere a tale verificadato che con l’emissione di un certificato elettronico si rende pubblicamente validal’associazione tra una certa chiave pubblica e una certa entità. Una volta attestata lavalidità dell’identità dell’utente attraverso una serie di procedure definite nell’ambito di unaprecisa politica di sicurezza (ad esempio, il controllo della carta di identità), l’autoritàdi registrazione ha il compito di abilitare l’utente come appartenente ad uno specifico dominiodi fiducia ; la funzionalità di autorità di registrazione può essere espletata dall’autorità dicertificazione stessa oppure delegata ad altre entità.

CA: Autorità di CertificazioneCostituisce il cuore di una PKI; la sua principale funzione consiste nel creare icertificati elettronici per quegli utenti precedentemente abilitati nella fase di registrazioneal dominio di fiducia di cui la CA è garante; un’Autorità di Certificazione non si deve limitareesclusivamente alla generazione dei certificati, ma deve poterne gestire l’intero ciclo di vita. Ilciclo di vita comprende le fasi di generazione, aggiornamento (nel caso in cui il certificato stia perperdere validità temporale), sostituzione (nel caso di scadenza della validità temporale) erevoca nel caso in cui le condizioni di emissione del certificato non siano più valide. Unulteriore compito della CA è stabilire relazioni di fiducia con altre CA.

La CA pubblica su un specifico server pubblico detto “Certificate Server” liberamente accessibile,la lista dei certificati in corso di validità o con l’indicazione se questi certificati sono revocati osospesi.

43/49

Page 44: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Una CA può emettere un certificato anche per un’altra CA, in modo da creare catene gerarchichedi certificati. Controllare la validità di un certificato, quindi, significa risalire la sua catena diautorizzazioni, fino a raggiungere quella di una CA “fidata”. In cima alla catena gerarchica c’è unaRootCA, che possiede un certificato “auto-firmato” (root certificate).I browser in circolazione sono configurati per dare fiducia ad un certo numero (modificabile,ovviamente) di CA ben note, contenendo quindi i relativi root certificate. I certificati di CA credutedall’utente, quindi, sono memorizzate nel browser.

44/49

Page 45: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Funzioni di hash

Una funzione hash trasforma un messaggio di lunghezza arbitraria in output di lunghezza fissachiamato hash o digest del messaggio originale.

Una funzione di hash è una funzione H che, dato un input m di dimensione qualsiasi, produce unoutput h (l’hash) di dimensione fissa:

h= H(m)

Una funzione di hash deve:• poter essere impiegata con blocchi di lunghezza variabile• produrre un output di lunghezza fissa

Messaggi diversi, anche per un solo bit, devono generare hash non correlati.

45/49

Page 46: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

La lunghezza dei valori di hash varia a seconda degli algoritmi utilizzati. Il valore più comunementeadottato è di 128 bit, che offre una buona affidabilità in uno spazio relativamente ridotto. Tuttaviava registrata la possibilità d'uso di hash di dimensione maggiore (SHA, ad esempio, può anchefornire stringhe di 224, 256, 384 e 512 bit) e minore (che però è fortemente sconsigliato).

Lo scopo di una funzione di hash è di creare un’impronta (fingerprint) del messaggio:• un hash non è una firma: non garantisce autenticazione. Nel calcolo di un hash non si

inserisce nessuna informazione segreta, per cui chiunque può generare l’hash corretto diqualunque messaggio.

• Una funzione di hash non è un algoritmo di cifratura. Calcolare l’hash di un messaggionon equivale a cifrarlo: il calcolo di un hash non include nessuna chiave, e soprattutto èun’operazione non invertibile.

Gli algoritmi di hash sono largamente utilizzati nei seguenti ambiti:i. Controllo degli errori: in questo caso la funzione di hash viene utilizzata come un

checksum, per identificare eventuali errori di trasmissione dei dati. Le proprietà aggiuntivedegli hash non vengono in questo caso sfruttate

ii. Integrità dei dati: la funzione di hash viene utilizzata per garantire che un messaggio nonsia stato modificato da un eventuale attaccante. Utilizzato ad esempio negli IDS (IntrusionDetection System) per controllare l’integrità dei file critici di un sistema operativo(tripwire/fastsum).

iii. Memorizzazione di password e autenticazione: nella maggior parte dei casi, quando unsistema informatico deve memorizzare una password, questa non viene salvata in chiaroper motivi di sicurezza, né viene cifrata per evitare che sia possibile risalire alla passwordoriginale. Si memorizza in questi casi l’hash della password. Ad esempio, sotto Windows,Linux e MacOS le password degli utenti sono salvate sotto forma di hash. Quando unutente scrive la propria password per accedere al sistema, ne viene calcolato l’hash econfrontato con quello memorizzato nel sistema.

iv. Firme digitali: si è già detto che la crittografia a chiave pubblica è computazionalmentemolto onerosa, per cui solitamente viene usata solo per trasmettere la chiave di unacrittografia simmetrica Per le firme digitali esiste un problema di prestazioni analogo:firmare l’intero documento è computazionalmente pesante. Soluzione: firmare solo un hashdel documento (ha anche il vantaggio di lasciare il documento in chiaro, leggibile anche dachi non dispone degli strumenti per verificare la firma digitale)

v. Nell'ambito dell'informatica forense per validare digitalmente i dati acquisiti, tipicamente lecopie forensi. La recente legislazione impone infatti una catena di custodia che permetta dipreservare i reperti informatici da eventuali modifiche successive all'acquisizione: tramite icodici hash è possibile in ogni momento verificare che quanto repertato sia rimastoimmutato nel tempo. Se i codici hash corrispondono, entrambe le parti in un procedimentogiudiziario hanno la certezza di poter lavorare sulla stessa versione dei reperti, garantendoquindi una uniformità di analisi.

Dato che l’output ha lunghezza fissa (in genere dell’ordine di una o poche centinaia di bit),esisteranno necessariamente diversi messaggi che generano lo stesso hash. Quando due testiproducono lo stesso hash, si parla di collisione, e la qualità di una funzione di hash è misuratadirettamente in base alla difficoltà nell'individuare due testi che generino una collisione. Persconsigliare l'utilizzo di algoritmi di hashing in passato considerati sicuri è stato infatti sufficienteche un singolo gruppo di ricercatori riuscisse a generare una collisione. Questo è quello che èavvenuto ad esempio per l'algoritmo MD4.

Nel contesto delle funzioni hash, ci si riferisce a diversi concetti di sicurezza:

46/49

Page 47: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Funzione unidirezionale (one way function)

E' facile calcolare l'hash di un messaggio, ma è difficile trovare il messaggio che ha generato undato hash. L'algoritmo hash non deve essere invertibile, ossia deve essere difficile ricostruire il documentooriginale a partire dalla stringa che viene restituita in output:• dato m deve essere facile calcolare h=H(m)• dato h deve essere computazionalmente impraticabile calcolare m=H-1(h).Computazionalmente impraticabile significa che non dovrebbe permettere di risalire, in un tempoconfrontabile con l'utilizzo dell'hash stesso, ad un testo che possa generarlo.

Sicurezza debole

Dato un messaggio è difficile trovarne un altro che generi lo stesso hash. Una funzione hash H è debolmente priva di collisioni se dato un messaggio m ècomputazionalmente inammissibile trovare un messaggio m’ tale che m≠m' e H(m)=H(m').

Sicurezza forte

E' difficile trovare due messaggi che abbiano lo stesso hash. Una funzione hash H è fortemente libera da collisioni se è computazionalmente difficile trovare unacoppia di messaggi m,m' tali che H(m)=h(m').L’idea è che, anche se necessariamente esistono messaggi diversi che producono lo stesso hash,non è praticabile trovarli.

Si può fornire una motivazione per ognuna delle tre proprietà delle funzioni hash. Consideriamo ilmeccanismo di generazione della firma digitale in cui la firma è apposta al valore hash H(m).

• H dovrebbe essere una funzione hash con la proprietà di sicurezza debole altrimenti, unnemico C potrebbe ricavare dalla firma l'impronta H(m), cercare un messaggio m' tale cheH(m)=H(m'), e quindi dimostrare che il mittente ha firmato m'. Ad esempio Alice ha firmatom, ma l'avversario può sostenere che ha firmato m'.

• Se poi C può scegliere il messaggio che il mittente deve firmare, allora C ha solamentebisogno di cercare una coppia (m,m') che è una collisione, lavoro piuttosto arduo se lafunzione hash gode della proprietà di sicurezza forte. Immaginiamo, ad esempio, chePippo prepari due versioni del contratto m e m' rispettivamente favorevole e sfavorevoleper Pluto. Pippo fa firmare H(m) a Pluto e poi sostituisce m con m'.

• Esaminiamo ora la necessità della proprietà di one-way per una funzione hash in unoschema di firma digitale a chiave pubblica. Si consideri l'RSA, dove l'utente A possiede unachiave pubblica (e,n)22. C può scegliere un valore casuale f, calcolare h=femod n. Se C puòcercare una preimmagine m tale che H(m)=h può dimostrare che f è una firma del mittentesu m.

22 Per generare la frma di un messaggio m A ne calcolerà l'hash h=H(m) e lo cifrerà con laprivata (n,d): f=H(m)dmod n. Invierà m insieme a f. Per verifcare la frma B dovrà verifcareH(m)=femod n.

47/49

Page 48: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

Message Authentication Code (MAC)

Un Message Authentication Code (MAC) è un piccolo blocco di dati utilizzato per l'autenticazionedi un messaggio digitale e per verificarne l'integrità da parte del destinatario, generato secondo unmeccanismo di crittografia simmetrica: un algoritmo MAC accetta in ingresso una chiave segretaed un messaggio da autenticare di lunghezza arbitraria, e restituisce un MAC. In ricezione ildestinatario opererà in maniera identica sul messaggio pervenuto in chiaro ricalcolando il MAC conlo stesso algoritmo e la stessa chiave: se i due MAC coincidono si ha autenticazione e integrità delmessaggio inviato.

Il valore MAC protegge dunque sia l'integrità dei dati del messaggio sia la sua autenticitàpermettendo al destinatario dello stesso (che deve anch'egli possedere la chiave segreta) dirilevare qualsiasi modifica al messaggio. L'algoritmo MAC protegge solo da integrità dei dati,autenticità del mittente del messaggio, ma non dalla confidenzialità delle informazioni contenutenello stesso.

• Una funzione di MAC è diversa da una di hash perché verifica anche l’autenticità delmessagggio.

• I MAC sono diversi dalla firma digitale poiché sono sia generati che verificati utilizzando lastessa chiave segreta. Questo implica che il mittente ed il destinatario del messaggiodevono scambiarsi la chiave prima di iniziare le comunicazioni, come nel caso dellacrittografia simmetrica. Per questa ragione i MAC non forniscono la proprietà del "nonripudio" offerta dalle firme digitali: qualunque utente che può verificare un MAC è anchecapace di generare MAC per altri messaggi. Invece una firma digitale è generatautilizzando la chiave privata di una coppia di chiavi (crittografia asimmetrica). Dato che lachiave privata è nota solo al suo possessore, una firma digitale prova che un documento èstato firmato esattamente dal suo proprietario e da nessun altro. Ecco che le firme digitalioffrono la proprietà del "non ripudio".

48/49

Page 49: prof.ssa Sophia Danesino

Sophia Danesino – Dispense integrative “TPSIT” a.s. 2017/18

BIBLIOGRAFIA E SITOGRAFIA

• M.A.Dye, R.McDonald, A.W.Rudi, “Network Fundamentals. Cisco Exploration CompanionGuide”, Cisco Networking Academy

• Kurose, Ross, “Computer networking a top down approach”, Pearson• Lo Russo, Bianchi, Sistemi e reti vol.3, Hoepli• Anelli, Macchi, Angiani, Zicchieri, Gateway Sistemi e reti, Petrini• Applied Cryptography Udacity

https://www.udacity.com/course/applied-cryptography--cs387• eForHum (Cisco Academy Support Center e Cisco Academy Instructor Training Center),

"Mappatura tra i nuovi programmi ministeriali degli Istituti Tecnici Superiori e i curriculaCisco Academy”

49/49