scieee AI-readable full text Open interactive document viewer

Kyber: analysis of a Nist´s post-quantum cryptographic standard

Rojas Rodríguez, Diego

Abstract

Quantum computing represents a threat to security over the internet due to its capacity to factorize composite numbers under polynomial time. This is done using Shor's algorithm and when a big enough quantum computer is built RSA will become obsolete. The cryptographic community started to look for alternatives that could work as public key cryptosystems. One of these alternatives is CRYSTALS-Kyber, considered by NIST as a possible new standard in the post-quantum era. Kyber's security depends on a computationally hard problem over Lattices, Learning With Errors. The version used in Kyber is Module LWE and relies on the polynomial ring structure to speed up matrix multiplication. This is something special in Kyber that uses the Number Theoretic Transform to map polynomials to a domain where multiplication can be done more eficiently. This carries some drawbacks as the NTT is known to be vulnerable against some attacks that target the implementation on physical devices. These are the side-channel attacks which, as for today, have become Kyber's biggest enemy. We will try to find protection against these attacks in interpreted languages that allow us to make implementations that are closer to the mathematical problem than compiled languages. We will answer how RSA works, how does Shor's algorithm break it, how big the impact in performance of the NTT is and how eficient an implementation in interpreted languages can be.

Full text

KYBER: Análisis de un estándar de criptografía postcuántica KYBER: Analysis of a NIST's post-quantum cryptographic standard Trabajo de Fin de Grado Curso 20232024 Autor Diego Rojas Rodríguez Director María Emilia Alonso García David de Frutos Escrig Colaborador Luis Hernández Encinas Grado en Ingeniería Informática Facultad de Informática Universidad Complutense de Madrid KYBER: Análisis de un estándar de criptografía postcuántica KYBER: Analysis of a NIST's post-quantum cryptographic standard Trabajo de Fin de Grado en Ingeniería Informática Autor Diego Rojas Rodríguez Director María Emilia Alonso García David de Frutos Escrig Colaborador Luis Hernández Encinas Convocatoria: Junio 2024 Grado en Ingeniería Informática Facultad de Informática Universidad Complutense de Madrid 27 de mayo de 2024 Dedicatoria A Luis.H Encinas, por ser mi vía de acceso y guía en el mundo de la postcuántica v Agradecimientos En primer lugar quería agradecer a María Emilia y David por haber aceptado dirigir un trabajo como este. A María Emilia por haber revisado el álgebra de esta memoria, que encontrareis abundante, invitarme a seminarios donde poder ampliar conocimientos en campos de nicho como este y haberme animado a seguir adelante con la investigación en criptografía. Tambien a David por la paciencia que ha necesitado para escucharme hablar de un tema con el que no estaba familiarizado y haberme ayudado a plantear hipotesis en otro del que si entendía mucho. Quiero agradecer también a la fundación Max Mazin por concederme la beca con la que pude dar mis primeros pasos en el mundo de la investigación dentro del CSIC. Especialmente agradecer a Luis H.Encinas por haber sido mi tutor en el CSIC y haber accedido a enseñar a un informático todos los detalles que a menudo pasamos por alto cuando nos centramos en la implementación. Ha sido él quien ha invertido su tiempo, que no siempre sobraba, en enseñarme y ha conado en mí lo suciente como para darme la oportunidad de presentarme a mi primer congreso. vii Resumen KYBER: Análisis de un estándar de criptografía postcuántica La compputación cuántica esta cerca de convertirse en una amenaza para la seguridad en internet gracias a su capacidad de factorizar números ecientemente. El algoritmo de Shor dejará RSA obsoleto una vez que exista un computador sucientemente grande. En la comunidad criptográca se están buscando alternativas que sirvan como estándar de criptografía de clave pública. Una de estas alternativas es CRYSTALS-Kyber, considerado por el NIST como posible nuevo estándar en la era post-cuántica. La seguridad de Kyber depende de un problema computacionalemnte dicil de retículos, Learning With Errors. La versión presente en Kyber es Module LWE que utiliza la estructura de anillo de polinomios para acelerar la multiplicacion de matrices. Esto es algo característico de Kyber, que usa la Number Theoretic Transform para representar los polinomios en un dominio donde la multiplicación se puede hacer de forma eciente. Esta decisión trae algunas desventajas ya que la NTT es vulnerable frente a ciertos ataques que aprovechan su implementación en dispositivos físicos, los ataques por canal lateral. A día de hoy estos son el mayor enemigo de Kyber. Se pretende proteger Kyber de estos ataques implementándolo en lenguajes de alto nivel que permitan mantener el código más el al planteamiento matemático, algo dicil en lenguajes compilados. Queremos responder cómo funciona RSA, cómo el algoritmo de Shor puede vulnerarlo, cuánto se nota el impacto en rendimiento de la NTT y cómo de eciente puede ser una implementación en un lenguaje interpretado. Palabras clave Criptografía, Post-cuántica, Cuántica, Ciberseguridad, Cifrado, Retículo, Shor, RSA, NIST, Kyber ix List of tables 3.1. Average performance of interpreted Kyber . . . . . . . . . . . . . . . 40 xvii List of Algorithms 1. G : Key generation in Kyber-CPA . . . . . . . . . . . . . . . . . . . . 23 2. E(pk, m) : Encryption in Kyber-CPA . . . . . . . . . . . . . . . . . . . 24 3. D(sk, c) : Decryption in Kyber-CPA . . . . . . . . . . . . . . . . . . . 24 4. G⊥ FO : Key generation in Kyber-CCA . . . . . . . . . . . . . . . . . . . 26 5. EC ⊥ FO : Encapsulation in Kyber-CCA . . . . . . . . . . . . . . . . . . . 26 6. DC ⊥ FO : Decapsulation in Kyber-CCA . . . . . . . . . . . . . . . . . . 26 7. Denition of parameters for Kyber512 . . . . . . . . . . . . . . . . . 34 8. Denition of red_ring function . . . . . . . . . . . . . . . . . . . . . 34 9. Denition of red_ring_mat function . . . . . . . . . . . . . . . . . . 35 10. keyGen algorithm in CPA interpreted Kyber . . . . . . . . . . . . . . 37 11. encryption algorithm in CPA interpreted Kyber . . . . . . . . . . . . 37 12. decryption algorithm in CPA interpreted Kyber . . . . . . . . . . . . 38 13. keyGen algorithm in CCA interpreted Kyber . . . . . . . . . . . . . . 38 14. decapsulation algorithm in CCA interpreted Kyber . . . . . . . . . . 38 15. decapsulation algorithm in CCA interpreted Kyber . . . . . . . . . . 39 xix Chapter 1 Introduction vcjaezd xplyd dpncpe Caesar cipher, key 37, alphabet={abcdefghijklmnopqrstuvwxyz} Since RSA cryptosystem was published in 1977 no one could question the security of public key cryptography. Attacking public key exchanges based in RSA or elliptic curves wasn't feasible a couple decades ago. In 1994 Peter Shor published an algorithm capable of factorize numbers under polynomial time. The secret? This algorithm requires a quantum computer. Quantum computing oers solutions for several mathematical problems that until now couldn't be solved eciently. Not only cryptography, but also computational hardness was aected, including the famous P=NP problem. Asymmetric cryptography security depends on the hardness of certain mathematical problems. These problems must be easily solved if known the initial data and almost impossible without such information. In the case of RSA the problem chosen is integer factorization: known the factors of an integer is easy to calculate the composite number but hard to calculate the factors from the composite number. Shor's algorithm nds a solution to this problem taking advantage of quantum phenomena like superposition and interference. Far from assuming defeat, cryptography researchers accepted the challenge of nding a new algorithm based in some problem that not even a quantum computer is able to solve. This new paradigm is known as post-quantum cryptography. The National Institute of Standards and Technology (NIST) is a US institution that made a proposal looking for new post-quantum cryptographic standards. In this project we analyze one of the submissions accepted by the NIST and, at the moment of publication of this project, accepted as new standard by the name of ML-KEM. Nonetheless, even perfect mathematical solutions struggle to be implemented in code. There is a branch in cryptography that focuses on nding exploits of implementations that exploit weaknesses on physical devices. These are known as side-channel attacks and lots of NIST researchers have been analyzing the severity of these weaknesses, given that they constitute considerable threat. In this project 1 2 Chapter 1. Introduction we will also analyze known attacks to the KEM proposition made by the group CRYSTALS, Kyber, and understand why they constitute a threat. 1.1. Motivation Cryptography is usually associated to mathematics, however; it's also tightly related to computing and engineering. Originally cryptography was used by emperors and generals who hid critical messages with sensitive information. As of today, all of use cryptography in our phones, computers and specially the internet. It's responsibility of the developers to implement these algorithms correctly to maintain them secure. From the point of view of quantum computing, cryptography is one of the biggest sell points when starting in investigation. Quantum algorithms have existed for several years, but it's today that they have become a real menace. There only exist quantum computers big enough to factorize small integers but if we don't start to develop post-quantum solutions we could en up living in a world where condentiality disappears. I had the opportunity to explore these topics in subjects as APCC (Arquitectura y Programación de Computadores Cuánticos) and CTC (Criptografía y Teoría de Códigos), but was during my time at CSIC that I learn about how the post-quantum community is ghting back. Estimations say that companies like IBM will have by 2030 quantum computers big enough to break RSA, or at least the lower levels. This means we work against the clock to protect our security over the internet. This project aims to be my rst contribution in this competition and, if I'm lucky, the rst of many. 1.2. Goals It's essential to understand why RSA is a secure cryptosystems, why it is no longer secure and how to attack it. Understand why quantum computers have an advantage when compared to regular computers when factorizing integers and how to do it. We look to understand why CRYSTALS-Kyber is considered a secure algorithm by the NIST. This must also be proved analyzing side-channel attacks to determine if they represent a real threat. However, the main goal of this project is designing an alternative able to resist the known side-channel attacks for Kyber. Analyzing its pros and cons vs. the original proposition. To sum up, we aim to understand the following items: O1 Fundamentals of public key cryptography O1.1 Integer factorization problem O1.2 RSA cryptosystem O1.3 Weaknesses of RSA O2 Quantum attacks on public key cryptography 1.3. Work plan 3 O2.1 Quantum superposition, entanglement and interference O2.2 Quantum Fourier Transform O2.3 Shor's algorithm O3 Lattice based cryptography O3.1 Hard problems over Lattices O3.2 Learning With Errors O3.3 CRYSTALS-Kyber O3.4 IND-CPA and IND-CCA security O4 Side-Channel attacks O5 Implementation in an interpreted language for CRYSTALS-Kyber 1.3. Work plan Cryptographic standards approved by the NIST will be analyzed, specially RSA used for public key exchange. We will explain the Integer Factorization Problem, why is unapproachable today and why it will not be in the future. We will explore how quantum computers implement Shor's algorithm for integer factorization and break RSA. In NIST's call for proposals one of the most outstanding algorithms was Kyber, from CRYSTALS. We will explain Learning With Errors and Module Learning With Errors (MLWE) and why they are important in Kyber. We will review the MLWE cryptosystem and which functions implement the KEM. Most relevant side-channel attacks will be understood and we will analyze how they exploit physical weaknesses. There will have to be implemented a version for Kyber in an interpreted language able to resist these side-channel attacks. We will analyze the eciency of this implementation and will be compared with the ocial one. There must be a pros and cons study for both algorithms. Chapter 2 State of the art 2.1. Classic cryptography Classic cryptography aims to share a message safely through an insecure channel. Most of modern communications are based in public key cryptography following a Die-Hellman scheme. This scheme is used to securely share a secret that will be used to start a more ecient ow encryption. The security of this key exchange relies on the computational hardness of an specic mathematical problem, used to create the keys of the PKE (Public Key Encryption). It's a common practice to introduce two parties interested in sharing a message: Alice and Bob. Alice must be able to create a pair of keys, public and secret, relatively easily and then share the public key with Bob. Later, Bob will cipher a message with this public key and send it to Alice. Once received, Alice would use an ecient algorithm to recover the message under polynomial time using her private key. At the same time, it should be almost impossible to recover the message for any third party eavesdropping the conversation, lets call her Eve. This doesn't mean that it is impossible for Eve to decipher the message, but a process long enough she doesn't think is worth the eort. This satises the denition of a One-Way function, used to cipher a message under polynomial time and, if and only if someone knows the secret key, deciphering it under polynomial time. 2.1.1. Integer factorization problem As of today, there is no algorithm able to nd the factors of an integer under polynomial time using a regular computer. Integers with around 800 digits are unapproachable even today. Historically, integer factorization has been one of the most widely used problems for the establishment of cryptographic standards. This is due to the fact that there is only one possible answer for the factorization of a number, as stated in the Fundamental Theorem of Arithmetic. Theorem 2.1.1 (Fundamental Theorem of Arithmetic) . 1. Any integer is either a prime number or a composite number 2. Composite numbers can be factorized (prime numbers can not) 5 12 Chapter 2. State of the art A quantum computer uses qubits as its minimum unit of information. These qubits reassemble regular bits in that both have two measurable states, |0⟩ and |1⟩ . The main dierence resides in qubits being able to stay in an intermediate state, combination of the basic states, as long as they are not measured. The proportion of how close is one state to each fo the basic ones is represented by the coecients α and β . This concept can be visually represented by the Bloch sphere, see gure 2.1. Arguably, the most relevant step in Shor's algorithm is the Quantum Fourier Transform, often shortened as QFT. This transform is a quantum approximation to the Discrete Fourier Transform, shortened as DFT, that relies on the n th-roots of unity to perform an ecient transform in a discrete domain. Figure 2.2: 12th-Roots of unity visualized over C Denition 2.2.2 (Roots of unity) . Transforms are based in the nth-roots of unity, numbers that raised to n give 1 . These are the solutions of the equation xn= 1 or the polynomial xn−1 and can be calculated in any eld, even nite elds. When the domain of the equation are the complex numbers C one could calculate them like: e 2kπi n Notice that for k=n we start to repeat values so there only exist n n-th roots of unity. This DFT approximation allows us to calculate Fourier's transform like: Denition 2.2.3 (Discrete Fourier Transform) . ˆxk= n−1 X j=0 xkωjk n where ωn represent the nth-roots of unity required to perform the DFT. ˆxk= n−1 X j=0 xke 2πi njk 2.2. Quantum computing in cryptography 13 For an interpretation of the DFT in the quantum domain using the bra-ket notation the transform is dened as follows Denition 2.2.4 (Quantum Fourier Transform) . |ˆxk⟩=1 √n n−1 X j=0 ωjk n|xk⟩ and calculating the roots of unity as shown before |ˆxk⟩=1 √n n−1 X j=0 e 2πi njk |xk⟩ The physical interpretation of this transform is what gives the quantum advantage in solving the IFP. To explain why is necessary to introduce another quantum phenomenon. Denition 2.2.5 (Quantum interference) . As quantum objects in superposition can be both interpreted as a wave or a particle, they are susceptible to present wavelike interference. As a wave does, qubits can interact constructively or destructively with each other resulting in cancellation or reinforcement of the amplitude of some states. We refer to this phenomenon as quantum interference. Is due to quantum interference that Shor's algorithm computes multiple orders at a time. There still exists a problem at the moment of recovering the results of this calculation. As previously stated, quantum interference happens when multiple qubits stay in a quantum superposition, and in this state it's impossible to know the answer of a query without forcing the superposition to collapse to a basic state. Measuring at this point would return a random element present in the superposition, which would be as useful as randomly guessing it. It is precisely for this reason that Shor's algorithm needs the QFT. As the classic Fourier Transform, the QFT can separate in dierent frequencies the elements being measured, in our case the elements in superposition. 14 Chapter 2. State of the art Figure 2.3: Visual interpretation of how the Fourier Transform maps waves to their frequencies With a clever arrangement of the qubits one could make them to destructively interfere so that the frequency at which the element raised to a given power starts to have the same remainder. Measuring this frequency with the QFT would be equivalent to measuring the period at which the remainders repeat. As frequency and period are the inverse of each other T=f−1 , and precisely; the period of this repetition coincides with the order of the element in the group, and the order of the element divides the order of the group. This way one would be solving the IFP under polynomial time using Quantum mechanics. 2.2.2. Shor's Algorithm Once understood the quantum steps of the algorithm, it's time to introduce how exactly the Order Finding Problem is solved. Denition 2.2.6 (Shor's algorithm) . The goal of this algorithm is to guess the prime factors of a given composite integer N. 1. Find a number q, power of 2, such that N2< q < 2N2 (see Bertrand's postulate) 2. Initialize the rst log2q qubits as a superposition of every number r(mod q) (register 1) and the rest of the qubits with |0⟩ (register 2) |ψ1⟩=1 √q q−1 X r=0 |r⟩|0⟩ 3. Choose a random x∈[2, N −2] . If gcd(x, N)= 1 x is a factor of N, but this is quite unlikely. 2.3. Lattice based cryptography 15 4. Fill the register 2, previously equal to |0⟩ , with the powers xr(mod N) |ψ2⟩=1 √q q−1 X r=0 |r⟩|xr(mod N)⟩ 5. Apply the QFT to the rst log2q qubits (register 1) |ψ3⟩=1 q q−1 X r=0 q−1 X j=0 e 2πi qjr |r⟩|xr(mod N)⟩ 6. Measure the state |ψ3⟩ and keep the values of both registers 7. If |r⟩ is odd then go back to step 2. If r is even then compute {gcd(xr/2−1, N),gcd(xr/2+ 1, N)} a ) If (xr/2+ 1)(xr/2−1) ≡0 (mod N) these are both the factors of N. b ) Else, if (xr/2+ 1)(xr/2−1) ≡ 0 (mod N) repeat step 4 using {gcd(xr/2− 1, N),gcd(xr/2+ 1, N)} as the values for x instead of random ones. c ) If neither of this happens restart from step 2. Once Shor's algorithm successfully ends, one could proceed to break the RSA encryption as shown in 2.1.2. 2.3. Lattice based cryptography Once consensus was established in the cryptographic community that RSA has become obsolete, researchers had to come up with new mathematical problems resistant to quantum computing and Shor's algorithm. One of the most promising alternatives, as for today, are the lattice based problems that gave birth to the lattice based cryptography. Figure 2.4: Two possible basis for a Lattice Denition 2.3.1 (Lattice) . A lattice L in the Euclidean n-dimensional space Rn is a discrete subgroup of linearly independent elements forming the basis L=k X i=1 ciai:ck∈Z, ak∈Rn In practice, a lattice can be visualized as a grid with equally separated points where the intermediate space is not dened, see gure 2.4. 16 Chapter 2. State of the art Denition 2.3.2 (Distance in a lattice) . Let K be a closed convex 0-symmetric set of positive volume in Rn . The successive minima of the lattice L with respect to K is: λi(L, k) = min{t∈R>0| tK contains at least i linearly independent elements of L} Notice that: 0< λ1(L, K)< λ2(L, K)< ... < λn(L, K) In this context: λ1(L, K) = min{∥x∥:x∈ L, x = 0} represents the successive minimum and ∥x∥=λ1(L, K) is a shortest vector of L 2.3.1. Learning With Errors Considering the aforementioned denition of distance, some problems as the Shortest Vector Problem (SVP) are dened and considered computationally hard. Denition 2.3.3 (Shortest Vector Problem) . Given a lattice L nd a vector x∈ L, x = 0 such that x is the shortest vector in L . In other words, given any other vector y∈ L, y =x then ∥x∥≤∥y∥ . Notice that this also means ∥x∥=λ1(L, K) . However, for the most successful post-quantum proposals, whose problem are lattice based, Learning With Errors is usually chosen as the problem to base cryptographic security on. For instance: CRYSTALS-Kyber, CRYSTALS-Dilithium and Falcon are some of the most promising propositions according to the NIST [7]. All of them are lattice based and all of them implement a version of the Learning With Errors problem. In order to understand the fundamentals of LWE, it's necessary to comprehend where the hardness of the problem lies. Denition 2.3.4 (Parity problem) . Given a nite amount of samples (xi, yi) and knowing that yi=f(xi) guess the function f. With enough samples is possible to nd the solution to this problem by simply running a Gaussian reduction algorithm in a regular computer in O(n3) . However, this is used as the foundation of a computationally hard problem, even for quantum computers. As per usual, from the standpoint of computational hardness two denitions are considered. Denition 2.3.5 (Learning With Errors (LWE)) . For integers m, q ≥1 , an integer vector s∈Zm q over a Lattice L , and a discrete probability distribution ϕ on R over L . This probability of distribution must return values within a bound, usually of q 2 . Let Aq,s,ϕ be the distribution over Zm q×Zq described as follows: Choose an a∈Zm q uniformly at random and e, error, term sampled from ϕ . Consider the pair ((a, b)=(a, b =⟨a, s⟩+e)∈Zm q×Zq as output. Chosing 2.3. Lattice based cryptography 17 Denition 2.3.6 (Decision Learning With Errors) . Given access to arbitrarily many independent samples from Aq,s,ϕ , distinguish with non-negligible advantage between values of b sampled from Aq,s,ϕ and ψ where ψ is a random uniform distribution over the lattice L . Denition 2.3.7 (Search Learning With Errors) . Given access to arbitrarily many independent samples from Aq,s,ϕ recover the vector s. The scope of this project falls far short of verifying the hardness of these problems, although justication can be found in [8]. In any case, either solving the decision or search problem of LWE would grant the solution of the other. This means by today not only is unfeasible to recover the vector s , part of the secret key, but also is unattainable a signicant advantage when it comes to decide if the answer is from a LWE distribution or totally random over the lattice. Considering this problem is hard to solve, a new cryptosystem can be dened around it. Denition 2.3.8 (LWE Cryptosystem [9]) . Consider the LWE instance Aq,s,ϕ and let U be the uniform distribution in Zn q : Key generation: a1..am←UZn q s←ϕZn q e←ϕZn q output: (ai, bi=ais+ei)n i=1 as public key (pk) and keep s as secret key (sk). Cipher: Given a plaintext M∈ {0,1}m with m≤n cipher each Mi∈M as r←ϕZn q e1←ϕZn q e2←ϕZq output: (ui, vi) = (air+e1i, br +e2+q 2Mi(mod q)) Decipher: Given a pair (u,v) v−us =br +e2+q 2Mi−airs −e1s Taking into account the denition of b: v−us =aisr +er +e2+q 2Mi−airs −e1s Thus: v−us =q 2Mi+er +e2−e1s(mod q) 18 Chapter 2. State of the art With a probability close to 1 : er +e2−e1s≤q 4 , which ultimately means that for each bit of the ciphertext ci∈C, 0≤i<m : If Mi= 0 then: q 2Mi< er +e2−e1s≤q 4 If Mi= 1 then: er +e2−e1s≤q 4<q 2Mi Values higher than q 4 will be decrypted as 1 and values lower than q 4 will be decrypted as 0 . The opposite works for the other side with +q 2 , values lower than 3q 4 will be decrypted as 1 while the values greater than 3q 4 will be decrypted as 0 . This is because of modular arithmetic, values greater than 3q 4 are closer to q and thus also closer to q 4 being decrypted as 0 . Figure 2.5: Visualization of the decryption process in the LWE cryptosystem [1] For this cryptosystem to work one should be careful choosing the error distribution. For early versions of this problem Discrete Gaussian was considered but for the latest versions modications of the Binomial proved to be more ecient. The probability of decryption to fail purely depends on the error distribution chosen. For the latest NIST submissions the probability of failure is between 2−139 and 2−174 [10].Ecient implementations of the LWE cryptosystem don't calculate each bit separately, see [11]. 2.3.2. Ring LWE and Module LWE For the NIST, one of the most important metrics for an algorithm to excel in is its eciency. Some candidates, such as Frodo-KEM, were disregarded because of their low performance time wise. The LWE problem requires ecient implementations of vector and matrix multiplication, which for today still have an almost cubic computational cost. To solve this, some researchers proposed a dierent approach to the LWE problem [12]. 2.4. CRYSTALS-Kyber 19 Denition 2.3.9 (Ring-LWE) . Similar considerations to the plain LWE, except this time q must be a prime number or a power of a prime number. The ring R is dened as: R=Zq[x]/f(x) where f is an irreducible polynomial of degree n over Zq An instance of Ring-LWE shall be as follows: Choose s←[Rm , a←[Rm uniformly at random, e←[ϕR and output: ((a, b) = ⟨a, s⟩+e)∈Rm×R This version of LWE, based on the ring structure, has not been proved to be any easier to solve than the plain LWE, hence it is as secure as the plain version. As proven in [12], the hardness of solving Ring-LWE in Zq is equivalent to solving the random knapsack problem in Zq . This lower bound comes very handy, as nding an ecient algorithm to solve Ring LWE could lead to a proof that P = NP. In this structure other ecient mechanisms to perform matrix multiplication can be implemented, such as the Number Theoretic Transform (NTT). Among these research teams, who have opted for the more ecient implementation of LWE, is the CRYSTALS group with Kyber for encrypting and Dilithium for signatures. Although, the implementation relies on another mathematical structure that allowed them to dene dierent security levels. Denition 2.3.10 (Module-LWE) . Same considerations as in Ring-LWE, except this time the ring R will serve as foundation of a module structure under which dierent security levels can be dened. Let k be a positive integer parameter, then the module M is dened as: M=Rk= (Zq[x]/f(x))k An instance of Module-LWE would be in the form: s←[Rk , A←[Rm×k uniformly at random, e←[ϕRk and output: ((A, b) = ⟨A, s⟩+e)∈Rm×k×Rk In a nutshell, a module can be understood as the k -dimensional variant of the ring, taking k dierent vectors for an instance. This way, dierent values of k would lead to consequential levels of hardness, and multiple standards can be dened under these hardnesses. This is the case of CRYSTALS-Kyber. The cryptosystem based on Module-LWE will be dened in the next section for Kyber specically. 2.4. CRYSTALS-Kyber Since the third round of NIST's call for post-quantum cryptography standard proposals no submission for KEM other than Kyber made the cut [7]. This ultimately means that Kyber has the greatest potential among all lattice-based KEM algorithms to become a standard in the upcoming years. Given the signicance of this proposal, an in depth comprehension of its operational process is advisable. MLWE, the mathematical problem Kyber is based on, has been already described, therefore the only matter left to be claried is the implementation of this problem in the proposal. Two dierent resistances are presented, one relying on the other. To ensure the simplicity of the explanation, the simplied version of Kyber from [2] will be considered. 20 Chapter 2. State of the art Proposition 2.4.1 (Kyber MLWE) . Consider the ring Rq=Zq[x]/(xn+ 1) where n= 2n′−1 such that xn+ 1 is the 2n′ cyclotomic polynomial Φ2n′(x) . This allows the implementation of fast multiplication algorithms such as the NTT, see 2.4.1.2. It is possible to increase the dimension of the structure by increasing the parameter k. Now MLWE will be written as: t=A◦s+e Where t is the new challenge, oered as public key (t,A), and A is a matrix of size k×k and s is a vector with k polynomials sampled with the same distribution ϕ as the vector e. This random distribution is usually the discrete Gaussian, although latest versions use the centered binomial as an ecient approximation. To perform eciently the calculation of t, Kyber operates in the domain of the NTT. This means, given a set of values for A, s and e in Kyber, t is computed as ˆ t , where ˆ t=NTT(t) . NTT−1(ˆ t) = NTT−1(NTT(A)◦NTT(s) + NTT(e)) As the cost of performing the NTT is lower than computing multiplication in the original domain, this new proposal is way more ecient than the original. Not only that, but also instead of calculating ˆ A=NTT(A) , ˆ A is generated in the domain of the NTT. As a result, sharing the value of A will end up in just arranging a seed to generate the matrix in the NTT domain with a pseudo-random number generator. These few changes proposed by CRYSTALS for Kyber have proven to be of utmost importance. The eciency of the NTT and the idea of generating ˆ A instead of computing it have made Kyber to stand out in the cryptographic community. Proposition 2.4.2 (Kyber parameters) . 1. n = 256, degree of the polynomial used in the module construction (x256 + 1) . Notice n′= 9 . 2. q = 3329, prime number used as quotient of the group Z3329 . 3. k∈ {2,3,4} , where k is the dimension of the module M=Rk q . 4. η1, η2∈ {2,3} are the parameters under which Centered Binomial Distributions are built. 5. du∈ {10,11}, dv∈ {4,5} are the values used for the compression and decompression process. The security of Kyber greatly depends on the dimension of the module. Three levels of security are considered: Kyber512 with k= 2 , Kyber768 with k= 3 and Kyber1024 with k= 4 . All other parameters for each security level can be found in [10]. Some of the parameters make references to functions that have not been introduced yet. Among these are pseudo-random generators, compression and decompression but in Kyber also hash functions play an important role. 2.4. CRYSTALS-Kyber 21 Denition 2.4.1 (Hash functions) . Let h be a hash function that can eciently perform the transformation of a message M into a hash m, h(M) = m . Then h must meet the following requirements: 1. Bit dependent: the value of m must depend on each of the bits in M 2. Preimage resistant: it is considered computationally hard to get a value m for a given M 3. Second preimage resistant: Given a message M is considered computationally hard to nd another value M′ such that h(M) = h(M′) = m 4. Collision resistant: it is considered computationally hard to nd a pair M, M′ such that h(M) = h(M′) = m Notice that these last two conditions are dierent from each other, collision resistance is weaker. In collision resistance no relation on M and M′ is required. In the second preimage a given M is assumed and then it is assured to be computationally hard to nd the other M′ . These functions play many dierent roles, among which are: output extension, key derivation and pseudo-random number generation. Kyber uses with this purpose ve dierent hash functions dened in the FIPS-202 standard. XOF ← SHAKE-128: an extendable output function used to generate hashes as long as required. H← SHA3-256: used in the IND-CCA version to perform the FO-Transformation. Fixed length to 256 bits. G← SHA3-512: used in the IND-CCA version to perform the FO-Transformation. Fixed length to 512 bits. PRF(s, b)← SHAKE-256 (s||b) : used for generating pseudo-random number sequences. KDF ← SHAKE-256: a key derivation function to ensure IND-CCA security in the FO-Transformation. To generate the necessary seeds to feed these hash functions, random distributions are required. Two dierent distributions are considered: U : Uniform discrete distribution. Takes values 1 or 0 with equal probability: Bη : Centered binomial distribution. Given values (f1, .., f2η)← {0,1}2η , outputs: Bη(fi) = η−1 X k=0 f2iη+k− η−1 X k=0 f2iη+k+η Probability of recovering the message in Kyber's cryptosystem depends on Bη , see 2.3.1. 28 Chapter 2. State of the art execution of the NTT can reduce the entropy of the result to about 56 for Kyber768, low enough to perform brute force attacks [2]. The explanation behind this can be explained as follows: Proposition 2.5.1 (Exploit for the NTT [2]) . The implementation of the NTT follows a CT - butterfly operation similar to some implementations of the FFT (Fast Fourier Transform). This specically performs repeatedly (u0, y1) = ((x0+x1·ζ),(x0−x0·ζ)) Where the indices 0 and 1 of the variables change each repetition and values of ζ vary among all nth-roots of unity of the polynomial used for the NTT. Notice that ζ is a very sensitive value and corrupting its value may aect drastically in the result. For instance, zeroing the value of ζ results in yi=(xi for i < n/2 xi−n/2 otherwise The dierence of n/2 in the index is due to the fact that the FFT scheme divides several times the DFT into halves that can be computed independently. In Kyber specically, the last step of the NTT is skipped. This means that Kyber should perform 8 iterations (from 0 to 7 ) because 27= 128 , forming the 128 quadratic polynomials dened in the cyclotomic division. In the implementation Kyber performs the transforms for sizes from 21 to 27 . As harmless as this change may seem it leads to yi=(xi for i ={0,1} 0 otherwise In Kyber with just a fault on a specic pointer one could zeroize almost all the result of the NTT. This attack still requires physical access to the device executing the algorithm and the ability to perform fault injections. It is a very demanding approach, although if successful one could breach the security of an algorithm not even a quantum computer can surpass. To know when to perform these fault injection attackers usually take advantage of Dierential Power Analysis. Denition 2.5.2 (DPA or Dierential Power Analysis) . These are a type of side channel attacks that rely on interpreting the current values of a cryptographic device while performing operations related to a cryptographic scheme. By analyzing the consumption of the processor one could know which operations are being performed even if the attacked device works as a black-box. 2.5. NTT side channel attack vulnerabilities 29 Figure 2.6: Graphic of power consumption over time while executing the NTT [2] As shown in the gure 2.6 an attacker with physical access to the device executing CRYSTALS-Kyber can know when the NTT is performed in order to start a fault injection. 2.5.2. Key recovery attack The key recovery attack aims to inject a fault in the key generation process to force the public keys and secret keys to have very low entropy. Proposition 2.5.2 (Key recovery attack [2]) . Fault the NTT operation on the secret s∈Rn q resulting in the corrupted secret ˆs∗ . This corrupted secret will be used to generate a LWE instance with low entropy s∗ . The result of this transform has all coecients of every polynomial equal to 0 , except for the rst two coecients. Now a brute-force attack can be performed as follows: 1. Compute d=t−As∗ 2. The dierence d for the correct guess will be as low as the error of the LWE problem This method has a 100 % guarantee of recovering the keys under polynomial time if the fault injection is successful. As Kyber-CCA is an IND-CCA algorithm, ciphertexts cant be distinguished form random, making it very dicult for the victim to notice. Also notice that the generated key is a valid LWE key so the communication is neither interrupted nor disturbed. 2.5.3. Message decryption attack There is a dierent approach for breaching Kyber's security that aims to recover a message from a valid ciphertext exchanged between to unrelated individuals. Proposition 2.5.3 (Message recovery Attack [2]) . Fault the NTT operation to recover the message of a valid ciphertext. The target is the variable r during the encryption process, resulting in a low entropy r∗ that will be used to generate the ciphertext. The faulty ciphertext will be ct∗= (u∗, v∗) . The attack proceeds as follows: 30 Chapter 2. State of the art 1. Suppose m=Compress(v∗−NTT−1(ˆ t◦NTT(r)),1) 2. Guess r∗ , the erroneous polynomial like: m=v∗−NTT−1(tT◦r∗) 3. For the correct guess the coecients of m are clustered around 0 and q/2 with low variation while for all other guesses they are distributed around Zq . This approach has a 100% guarantee of recovering the secret. The implementation of this attack varies if the target is Kyber-CPA or Kyber-KEM (IND-CCA version). This kind of attacks are usually referred to as Man In The Middle (MITM). Usually two unrelated people, Alice and Bob, establish communication while a third person, Eve, tries to recover the secret without being noticed. Figure 2.7: Fault assisted MITM on Kyber-CCA [2] Chapter 3 Contributions Never ever, ever, ever, ever, ever implement your own crypto Dan Boneh, Cryptography I (2008) Most side channel attacks rely on the hardware implementation of the algorithms they try to breach. Almost every ocial implementation of cryptographic algorithms are programmed in C. This is because C is the most ecient are general purpose programming language, as it is eciently translated to assembly code. This is its biggest advantage but also its biggest aw. For an attacker is manageable to translate C code to assembly for an specic computer, look for exploits in the instructions and then perform an attack at hardware level. This is unavoidable for any implementation of any algorithm, because it ultimately doesn't depend entirely on the code itself but in its translation to hexadecimal. That being said, a programmer can try to hinder the attackers job by avoiding the use of easily exploitable functions. Some researchers try to mask the power consumption of some operations at the cost of delaying the execution time. These are unsatisfactory solutions for these problems and usually is not enough to protect against side-channel attacks. Given the severity of the threat these side channel attacks constitute to the security of Kyber the following proposition is made: Proposition 3.0.1 (Interpreted Kyber) . Compiled languages as C are the most e- cient options to implement cryptographic algorithms. However, some attacks target these implementations, as it is arguably easy to know exactly which processor instructions correspond to certain lines of code. For this reason, using interpreted languages, where the code is not translated into machine instructions but executed by another program or virtual machine, may result in more accurate versions of the LWE problem. The abstraction this type of languages provide might be an advantage against side channel attacks as instructions can be interpreted during program runtime. With this purpose, we recommend testing the performance dierence between an 31 32 Chapter 3. Contributions implementation made in an interpreted language to observe if the eciency dierence is low enough to justify using this version instead of the compiled one. 3.0.1. Maple The interpreted language chosen for the implementation is Maple 2023.2, a language designed by the University of Waterloo and published in 1988. This language is optimized for cryptography and among its libraries there are multiple implementations of mathematical functions required by Kyber, such as the SHA3 family. In the compiled version of Kyber, most polynomial operations are approximations that consider the twos compliment representation (C2). In Maple several types as the polynomials are dened natively and structures like rings or modules can be easily created with standard libraries. In this environment, there is no need to dene e- ciency focused functions such as the NTT or the Montgomery reduction used in the compiled version of Kyber. Denition 3.0.1 (Maple computational engine) . Maple consists of two main parts: 1 The kernel: written in C, supports all the basic arithmetic operations and is in charge of linking the headers to the libraries. 2 The math libraries: these are integrated in the Maple language and are usually loaded during runtime. The libraries Maple contains by default are implemented at high level, although the references point to compiled versions. Libraries will still be considered safe, meaning they shouldn't be vulnerable against side-channel attacks. To ensure that this interpreted version in Maple is harder for side channel attacks, libraries will not be compiled like in other interpreted languages such as Python. Maple can use dierent formats for its libraries. Among them there are .mla, a binary format, and .mw, interpreted as an script and run at the beginning of the program. The binary les, .mla, store data that should be unintelligible for humans granting more eciency without necessarily reducing security. This strictly depends on the behavior of the compiler LLVM, used by Maple to translate functions to C++. There will be for now on 3 dierent versions of Kyber considered: 1. Standard Kyber: coded in C by the authors of Kyber's cryptosystem. In the analysis, the implementation present in the Open Quantum Safe library (libOQS) will be used to test performance. 2. Maple interpreted Kyber: coded in Maple and linking the auxiliary functions dynamically using the Maple Workbook (.mw) format. 3. Maple compiled Kyber: coded in Maple and linking statically the auxiliary functions in format Maple Library Archive (.mla). For the implementation of the interpreted version of Kyber some libraries, apart from the standard ones, were required. These include a family of hash functions 3.1. Implementation 33 developed by NIST researchers to include the SHA3 family functions used in Kyber. The format of the library was .mw (Maple Workbook) and had to be adapted to make it compatible with Kyber. 3.0.1.1. Packages Library functions in Maple are referenced through packages. In the Maple implementation for Kyber, most of these were not imported wholly, but only the necessary functions. This reduces the size of the binary le in the Maple compiled version. The packages referenced in the implementation were: 1. NumberTheory: functions for number theory 2. PolynomialTools: operations that work with polynomials 3. Groebner: tools for skew algebra 4. LinearAlgebra: basic operations for linear algebra 5. FileTools: functions used to read or write les 6. StringTools: functions to convert and operate with strings 7. Bits: basic operations for the Bit type 8. ListTools: Operations for the List type 9. ArrayTools: Operations for the native type Array 3.1. Implementation Functions have been adapted from the original Kyber proposition [10]. To simplify the abstraction process, the types string, integer, polynom, Vector, Matrix and Array were used for this purpose. Each of these represent dierent objects depending on the context although most of the time they will be used as: 1. integer: coecients of polynomials 2. string: random seeds, hashes or serialized objects 3. polynom: polynomials over the ring R 4. Vector: vectors over the Modulus M 5. Matrix: matrix over the Modulus M 6. Array: arrays of bytes before serialization Now in order to understand how the implementation was made we will introduce each package dened in the project. 34 Chapter 3. Contributions 3.1.1. params There are a total of 3 les that start with params in their names. These are params512, params768 and params1024. Each one contains the parameters for a dierent NIST security level dened as global variables called by functions in the other packages. As an example one could use params512: Algorithm 7 Denition of parameters for Kyber512 Q := 3329: N := 256; k := 2; p := x256 + 1 ; η1 := 3; η2 := 2; du := 10; dv := 4; Z := GF(3329, 1); POLY_SIZE := 384; POLYVEC_SIZE := k*POLY_SIZE; HASH_SIZE := 64; 3.1.2. ring_operations In this le we dened the operations with polynomials in a Ring and Modulus. The rst denition is of the ring itself: R:= Groebner :−Basis([p], tdeg(x)); We used the Groebner package to dene a base of polynomials smaller than p ( x256 ) that uses x as unknown. This is still not enough to dene Kyber's ring as elements of the ring must have coecients smaller than Q (3329). That's why we dened red_ring: This function receives any element and returns its normal form in the Algorithm 8 Denition of red_ring function red_ring := proc(a) return modp(Groebner:-NormalForm(a,R,tdeg(x)),Q); end proc; base R with coecients mod Q . This function will be called every time we make an arithmetic operation over the ring to be sure that the result also belongs to the ring. Operations of two polynomials over the ring are simply dened as calling red_ring after performing Maple's default operations (a+b, a-b, a*b). Operations over the Modulus are a bit dierent. As all of the elements in the Vector or Matrix need to be reduced, calling red_ring would not work. That's the reason we dened red_ring_mat, which uses the functional programming operation map to 3.1. Implementation 35 Algorithm 9 Denition of red_ring_mat function red_ring_mat := proc(A)::Matrix return map(z → map(y → Groebner:-NormalForm(modp(y,Q),R,tdeg(x)),z),A); end proc; get the normal form over the basis of each element in the Vector or Matrix: Output is specied as a Matrix but it could be a Vector as it can be casted from a 1 by n Matrix. Then again operations of these elements just calls red_ring_mat after applying the addition of Maple or the LinearAlgebra:-Multiply in the case of the multiplication, as matrix multiplication can't be performed without the LinearAlgebra package. 3.1.3. SHA3 As we have previously mentioned, the SHA3 implementation was taken from NIST researchers that implemented the function in Maple []. We won't explain the whole package, but we will cite the functions used in the implementation of interpreted Kyber. 1. bytestohex: maps numbers from 0 to 15 to their respective hexadecimal character 2. SHA3: instance of the sponge function SHA3 3. SHAKE: instance of the extendable output hash SHAKE 3.1.4. hashes This le denes the hash functions required for Kyber. Some of the hashes needed to be adapted before being used in our implementation. This is the case for: 1. XOF: before redirecting to SHAKE-128 we check if the input is a list, and if so we convert it to a string concatenating its elements. 2. PRF: in Kyber PRF is called with two input variables that are concatenated and then used as a seed in SHAKE-256. We rst check if input are lists to concatenate its elements and then concatenate both variables and feed them to SHAKE-256. For H we just instantiate as SHA3-256, G as SHA-512 and KDF as SHAKE-256. 3.1.5. auxiliary In this le are dened all the supporting function needed for Kyber-CPA and Kyber-CCA. These include the Normal and Centered Binomial distributions as well as the functions used to generate the random vectors using the Binomial distribution. There are also dened functions to serialize the polynomials to facilitate sharing over the network. 36 Chapter 3. Contributions Proposition 3.1.1 (Serialization) . Data over the internet and other networks is transmitted as byte streams. To visualize these streams computers show their representation in hexadecimal to shorten an 8 bits number to a 2 hex character number. To serialize polynomials we followed the process used in Kyber's implementation in C. We represented polynomials as arrays with 256 slots and lled each with the coecient corresponding to the power of the index. S[i] = coeff(p, xi) Where coe is supposed to return the coecient of the i-th x-power of p. To save space, instead of using 2 whole bytes to represent each number from 0 to 3328 we used 12 bits for each coecient and packed them in pairs. This way 3 bytes represent a pair of coecients where the rst byte and the 4 most signicant bits of the second byte correspond to the rst coecient and the rest to the second. Using this serialization process our polynomials are 384 bytes long. To generate polynomial Kyber denes two processes. The rst one is what we called the CBD (Centered Binomial Distribution), that generates a polynomial in the ring R given a seed and the value of eta. Proposition 3.1.2 (CBD) . The process we followed is heavily inspired by the original approach specied in Kyber's documentation. The process changes the seed to a 64 ·η seed using SHAKE[256] and then converts it to bits. Each bit is then added in groups of 2·η where the rst η correspond to a number a and next η ones to b. Then calculate a-b and use it as index for the coecient xi . The other process is the one used for the polynomials in the public matrix A . We called this function parsetopol. Proposition 3.1.3 (parsetopol) . Takes a seed as an input and generates a polynomial using the seed for randomness. First, changes the seed to hex and later to bits. The bits of the seed are then used as randomness in a process equivalent to the one described in the original pseudocode of Kyber. 3.1.6. KyberCPA This le contains the implementation of Kyber's algorithm when ciphering a specic message. As previously explained, this consists of 3 functions: keyGen, encryptionCPA and decryptionCPA. We will discuss how these were adapted to Maple using functional programming. Key generation needs to generate the polynomials used in the ciphering and deciphering processes. The public matrix A is generated using the Matrix constructor of Maple with dimensions k by k and initialized with a lambda function. This lambda function takes as input the row and column of the element and feeds it to the XOF with a seed generating a dierent 32 byte seed for each element in the matrix. This unique seed is used in the auxiliary function parsetopol to generate the polynomial. 3.1. Implementation 37 Algorithm 10 keyGen algorithm in CPA interpreted Kyber Proposition 3.1.4 (keyGenCPA) . keyGenCPA := proc() local nonce := 0; local seedA := Uniform(); local seedB := Uniform(); local A := Matrix(k,k,(i,j) → parsetopol(XOF([ seedA ,i,j],32))); local s := convert([seq(CBD(PRF( seedB , nonce++), η1 ),1..k)],Vector[column]); local e := convert([seq(CBD(PRF( seedB , nonce++), η1 ),1..k)],Vector[column]); local t := ring_mat_add(ring_mat_mul(A,s),e); local pk := cat( seedA ,encodevec(t)); local sk := encodevec(s); return [pk,sk]; end proc; Vectors of polynomials s and e are generated with the function seq that receives a function and uses it to generate the elements of a list. The function used is the CBD using the result of the PRF with the nonce and original seed. As the nonce increases with each call each time the PRF returns a dierent hash. This is then converted to a column vector to use in the multiplication. Ultimately the challenge t is calculated using the operations dened in ring_operations and serialized with the function encodevec. Algorithm 11 encryption algorithm in CPA interpreted Kyber Proposition 3.1.5 (encryptionCPA) . encryptionCPA := proc(pk::string, m::string, seedR :=Uniform())::string; local nonce := 0; local seedA := susbtring(pk,1..HASH_SIZE,string); local t := decodevec(substring(pk,HASH_SIZE+1..length(pk),string)); local At := LinearAlgebra:-Transpose(Matrix(k,k,(i,j) → parsetopol(XOF( [ seedA ,i,j], HASH_SIZE)))); local r := convert([seq(CBD(PRF( seedR ,nonce++), η1 ),1..k)],Vector[column]); local e1 := convert([seq(CBD(PRF( seedR ,nonce++), η2 ),1..k)],Vector[column]); local e2 := CBD(PRF( seedR ,nonce++), η2 ); local u := ring_mat_add(ring_mat_mul( At ,r),e1); local v := ring_add(ring_add(ring_mat_mul(LinearAlgebra:-Transpose(t), r), e2 ),decode(m)); return cat(encodevec(u),encodevec(v)); end proc; The rst step to encrypt a given message is to decode the key, previously stored in hex notation. The public key contains the hash used to generate the matrix A and so the sender can regenerate it to encrypt. Vectors r, e1 and polynomial e2 are calculated as in keyGenCPA via the CBD function, and the seq function in the case of the vectors. Then simply calculate u and v using ring_operations and concatenate them in hex to send the ciphertext. 44 Chapter 4. Conclusions and Future Work very least for the sake of science. Our performance analysis still wasn't exhaustive enough for a serious conclusion. The lack of physical devices for the measurement of power peaks in the algorithm forced us to settle for an approximation based on number of operations and time spent. In the future, we propose to use devices as the ChipWhisperer to measure the power usage and peak voltage of interpreted Kyber and even try to perform side-channel attacks over the parsetopol and CBD functions. If these prove to be secure against side-channel attacks we could claim that interpreted Kyber is secure against all physical vulnerabilities known at the moment. Introducción Desde la aparición del criptosistema RSA en 1977 hasta hace unos años nadie había podido poner en tela de juicio la seguridad de la criptografía de clave pública. Descifrar un mensaje cifrado con RSA o curvas elípticas (ECC) era impensable hasta hace un par de décadas. En 1994 se presentó por primera vez un algoritmo capaz de factorizar números en tiempos aceptables ¾El secreto? El algoritmo necesita un computador cuántico para poder ejecutarse. La computación cuántica plantea soluciones a muchos problemas matemáticos que hasta el momento se creían imposibles de abordar. No solo la criptografía se ha visto afectada, sino todo el campo de la complejidad de algoritmos, incluido el famoso problema P = NP. La seguridad de la criptografía asimétrica depende de la complejidad de resolver un determinado problema matemático. Estos problemas deben ser fáciles de resolver conocidos los datos iniciales y totalmente inabordables sin esta información. En el caso de RSA se usa la factorización de números: conocidos los factores es muy facil multiplicarlos pero dicil calcular sus factores conocido el número compuesto. El algoritmo de Shor encuentra una solución a este problema, calcula estos factores aprovechando los fenómenos cuánticos de superposición e interferencia. Lejos de aceptar la derrota, los investigadores de criptografía han aceptado el reto de encontrar un nuevo algoritmo basado en algún problema que ni siquiera un computador cuántico pueda resolver. Este nuevo paradigma se conoce como la criptografía post-cuántica. El NIST (National Institute of Standards and Technology), el organismo que decide los estándares criptográcos en EEUU, abrió una convocatoria buscando popuestas que resistan ataques realizados por computadores cuánticos. En este proyecto analizamos una de las propuestas que fue aceptada por el NIST y, para el momento de publicación del trabajo, aceptada como estándar bajo el nombre de ML-KEM. No obstante, hasta las soluciones perfectas a nivel matemático se enfrentan al problema de ser implementadas en dispositivos físicos. Existe una rama de la criptografía que se centra en buscar ataques que expriman debilidades en la implementación de los algoritmos en dispositivos físicos. Estos son conocidos como ataques por canal lateral y muchos investigadores del NIST han estado analizando la severidad de estas vulnerabilidades, puesto que sin duda constituyen una amenaza. En este trabajo también analizaremos ataques conocidos para la proposición de KEM del grupo CRYSTALS, Kyber, y si verdaderamente constituyen un peligro. 45 46 Chapter 4. Conclusions and Future Work Motivación La criptografía es un campo de estudio que habitualmente se asocia más a las matemáticas, sin embargo; esta íntimamente relacionada con la computación y la informática. En los orígenes de la criptografía eran los emperadores y militares los que cifraban sus mensajes para ocultarlos a ojos indiscretos. A día de hoy todos nosotros usamos dispositivos criptográcos en nuestros terminales telefónicos, ordenadores y por supuesto en internet. Es responsabilidad informática implementar estos algoritmos elmente para mantenernos seguros. Desde el punto de vista de la computación cuántica, la criptografía es uno de los temás que más motiva a la gente a introducirse en la investigación. Los algoritmos cuánticos llevan mucho tiempo existiendo, pero es ahora cuando la amenaza empieza a estar verdaderamente cerca. Existen a día de hoy dispositivos con suciente capacidad de cómputo para poder factorizar números pequeños y si no empezamos a implementar soluciones post-cuánticas podríamos terminar viviendo en un mundo donde desaparezca la condencialidad. He podido indagar en estos temas en asginaturas como APCC (Arquitectura y Programación de Computadores Cuánticos) y CTC (Criptografía y Teoría de Códigos), pero ha sido sobre todo en mi tiempo en el CSIC que pude ver cómo especícamente el mundo de la post-cuántica está contraatacando. Las estimaciones de empresas como IBM son que para 2030 existirán computadores cuánticos con capacidad de descifrar RSA, al menos en sus primeros niveles, así que vivimos en una carrera contrareloj por nuestra seguridad online. Este proyecto busca ser mi pequeña aportación a esta competición y, con algo de suerte, la primera de muchas. Objetivos Es vital comprender por qué RSA es un criptosistema seguro, por qué ha dejado de serlo y como se ataca sus intercambios de clave. Entender por qué un computador cuántico tiene ventaja frente a uno clásico al factorizar números y cómo lo hace. Se busca comprender los motivos por los que CRYSTALS-Kyber es considerado un algoritmo seguro por el NIST. Esto también debe justicarse revisando los ataques por canal lateral y estimar si constituyen una amenaza para las implementaciones físicas. De todos modos, el objetivo principal de este proyecto es diseñar una alternativa capaz de resistir los ataques por canal lateral conocidos para Kyber. Sintetizando, se pretende entender los siguientes puntos: O1 Fundamentos de la criptografía de clave pública O1,1 Problema de la factorización de números O1,2 Criptosistema de RSA O1,3 Vulnerabilidades de RSA O2 Ataques cuánticos a la criptografía de clave pública O2,1 Superposición, entrelazamiento e interferencia cuántica 47 O2,2 Transformada cuántica de Fourier O2,3 Algoritmo de Shor O3 Criptografía basada en retículos O3,1 Problemas computacionalmente difíciles en retículos O3,2 Learning With Errors O3,3 CRYSTALS-Kyber O3,4 Seguridad IND-CPA e IND-CCA O4 Ataques por canal lateral O5 Implementación del algopritmo de CRYSTALS-Kyber en un lenguaje interpretado Plan de trabajo Se investigarán los estándares criptográcos aprobados actualemnte por el NIST, especialmente RSA en intercambio de clave pública. Se analizará el problema de la factorización de números, por qué funciona a día de hoy y por qué dejará de hacerlo en el futuro. Se indagará en cómo los computadores cuánticos usan el algoritmo de Shor para factorizar números y como esto rompe RSA. En la convocatoria del NIST uno de los algoritmos destacados fue Kyber, del grupo CRYSTALS. Se analizarán los problemas Learning With Errors y Module Learning With Errors (MLWE) y su importancia en Kyber. Se explicará el criptosistema basado en el problema MLWE y como actúan sus funciones en un KEM. Se estudiarán las propuestas de ataque por canal lateral más relevantes y cómo afectan a Kyber. Se intentará programar una alternativa que proteja a Kyber de los ataques por canal lateral. Se analizará el rendimiento de dicha implementación y se comparará con la ocial. Debe incluirse una comparación de ambos explicando sus ventajas y desventajas. Conclusiones y Trabajo Futuro La eciencia de la implementacion en Maple queda muy por detras de la original compilada en C. Esto era de esperar, Maple está diseñado para facilitar la implementación de algoritmos manteniendola lo más cercana posible a la proposición matemática. Para esto usa programación funcional, paradigma no tan eciente como la programación imperativa. Aun así, los resultados han sido muy satisfactorios. La versión interpretada enmascara a la perfección el proceso de multiplicación matricial al calcular el reto (t) en el KEM de Kyber. Observando la gráca 3.2 uno puede apreciar el patron de ejecución de Kyber, tal como se menciona en la sección 3.2.1, pero enmascarar la generación de polinomios podría resultar más sencillo que la NTT. Reducir los valores de la matriz pública a cero o los valores de los vectores s y e es más facil de detectar, en contraste con el ya mencionado ˆ S . De todos modos, la eciencia no es un objetivo trivial, es de hecho la característica más importante según el NIST. La proposición de Kyber destacó precisamente por su eciencia al usar la estructura de módulo para optimizar el paso más lento de Learning With Errors. La amenaza que constituyen los ataques por canal lateral a los KEMs post-cuánticos no es sucientemente signicativa como para considerar aumentar cinco órdenes de magnitud el coste en tiempo del algoritmo. Dado que otrtos algoritmos que imwplementan Learnign With Erros sin usar la NTT, como Frodo-KEM, son más ecientes podría ser más recomendable usarlos en lugar de esta versión de Kyber. Los lenguajes interpretados, especialmente los funcionales, permiten implementaciones más facilmente entendibles para personas menos familiarizadas con lenguajes de bajo nivel. Utilizando las librerias de Maple hemos diseñado un programa con el objetivo de mantenerlo lo más el posible al planteamiento matemático. Esto puede resultar útil para personas que quieran introducirse en el mundo de la criptografía post-cuántica pero no entienden C. También pretendemos terminar la traducción de Interpreted Kyber a C, puesto que no fuimos capaces en este proyecto. Traducir las funciones a C no es nada más que el principio de lo que teníamos pensado hacer. Una vez se hubiese traducido, tendríamos que reorganizar todo el proyecto, porque la estructura que tendría en C es muy distinta a la de Maple. Aun así, tarde o temprano queremos volver a terminar lo que empezamos, aunque solo sea por saciar la curiosidad. El análisis de rendimiento no pudo ser todo lo exhaustivo que nos habría gustado para una conclusión mas sólida. La falta de dispositivos de medida para los picos de consumo del algoritmo nos obli- 49 50 Chapter 4. Conclusions and Future Work gó a tomar aproximaciones basadas en el número de operaciones. En el futuro, nos gustaría poder utilizar dispositivos como el ChipWhisperer para poder medir estos picos de voltaje en Kyber interpretado y poder probar ataques por canal lateral en funciones como parsetopol y CBD. Si estas se prueban seguras podríamos considerar que Kyber interpretado verdaderamente es resistente a los atques conocidos por canal lateral y seguro frente a todas las vulknerabilidades físicas conocidas hasta la fecha. Bibliografía Díjome que no podía hacerse, y gané la apuesta. La vida es sueño, Pedro Calderón de la Barca (1636) [1] S. ÖZEREN and O. YAYLA, Methods for masking crystals-kyber against side-channel attacks, Cryptology ePrint Archive, Paper 2023/1340, 2023, https://eprint.iacr.org/2023/1340. [Online]. Available: https://eprint.iacr.org/ 2023/1340 [2] P. Ravi, B. Yang, S. Bhasin, F. Zhang, and A. Chattopadhyay, Fiddling the twiddle constants - fault injection analysis of the number theoretic transform, Cryptology ePrint Archive, Paper 2022/824, 2022, https://eprint.iacr.org/ 2022/824. [Online]. Available: https://eprint.iacr.org/2022/824 [3] S. Y. Yan, Cybercryptography: Applicable Cryptography for Cyberspace Security . Springer, 2019. [Online]. Available: https://doi.org/10.1007/978-3-319-72536-9 [4] R. L. Rivest, A. Shamir, and L. Adleman, A method for obtaining digital signatures and public-key cryptosystems, Commun. ACM , vol. 21, no. 2, p. 120126, feb 1978. [Online]. Available: https://doi.org/10.1145/359340.359342 [5] P. Shor, Algorithms for quantum computation: discrete logarithms and factoring, in Proceedings 35th Annual Symposium on Foundations of Computer Science , 1994, pp. 124134. [6] P. W. Shor, Polynomial-time algorithms for prime factorization and discrete logarithms on a quantum computer, SIAM Journal on Computing , vol. 26, no. 5, pp. 14841509, oct 1997. [Online]. Available: https: //doi.org/10.1137%2Fs0097539795293172 [7] NIST, 2022. [Online]. Available: https://csrc.nist.gov/Projects/ post-quantum-cryptography/selected-algorithms-2022 [8] Z. Brakerski, A. Langlois, C. Peikert, O. Regev, and D. Stehlé, Classical hardness of learning with errors, 2013. 51 52 BIBLIOGRAFÍA [9] O. Regev, On lattices, learning with errors, random linear codes and cryptography, 2024. [10] R. Avanzi, J. Bos, L. Ducas, E. Kiltz, T. Lepoint, V. Lyubashevsky, J. M. Schanck, P. Schwabe, G. Seiler, and D. Stehlé, Crystals-kyber algorithm specications and supporting documentation (version 3.02), Aug 2021. [Online]. Available: https://pq-crystals.org/kyber/resources.shtml [11] E. Alkim, J. W. Bos, L. Ducas, P. Longa, I. Mironov, M. Naehrig, V. Nikolaenko, C. Peikert, A. Raghunathan, D. Stebila et al. , Frodokempractical quantumsecure key encapsulation from generic lattices, 2022. [12] F. L. Zhiyong Zheng, Kun Tian, Modern Cryptography Volume 2: A Classical Introduction to Informational and Mathematical Principle . Springer, 2023. [Online]. Available: https://doi.org/10.1007/978-981-19-7644-5 [13] E. Fujisaki and T. Okamoto, Secure integration of asymmetric and symmetric encryption schemes, in Advances in Cryptology  CRYPTO'99 , M. Wiener, Ed. Berlin, Heidelberg: Springer Berlin Heidelberg, 1999, pp. 537554. [14] M. Ángel González de la Torre, L. H. Encinas, and A. Queiruga-Dios, Analysis of the fo transformation in the lattice-based post-quantum algorithms, mathematics , 2022. [15] J. Bos, L. Ducas, E. Kiltz, T. Lepoint, V. Lyubashevsky, J. M. Schanck, P. Schwabe, G. Seiler, and D. Stehle, Crystals - kyber: A cca-secure module-lattice- based kem, in 2018 IEEE European Symposium on Security and Privacy (EuroSP) , 2018, pp. 353367. [16] M. A. Nielsen and I. L. Chuang, Quantum Computation and Quantum Information: 10th Anniversary Edition . Cambridge University Press, 2010. [17] C. Peikert, A decade of lattice cryptography, Cryptology ePrint Archive, Paper 2015/939, 2015, https://eprint.iacr.org/2015/939. [Online]. Available: https://eprint.iacr.org/2015/939 [18] C. Ling, L. Luzzi, J.-C. Belore, and D. Stehle, Semantically secure lattice codes for the gaussian wiretap channel, IEEE Transactions on Information Theory , vol. 60, no. 10, pp. 63996416, oct 2014. [Online]. Available: https://doi.org/10.1109%2Ftit.2014.2343226 [19] M. Artin, Algebra . Birkhäuser, 1998. [20] C. C. Nacional, Guía de seguridad de las tic ccn-stic 221, 2023. [21] P. C. Kocher, J. Jae, and B. Jun, Dierential power analysis, in Advances in Cryptology - CRYPTO '99, 19th Annual International Cryptology Conference, Santa Barbara, California, USA, August 15-19, 1999, Proceedings , ser. Lecture Notes in Computer Science, vol. 1666. Springer, 1999, pp. 388397. BIBLIOGRAFÍA 53 [22] L. Ducas, T. Lepoint, V. Lyubashevsky, P. Schwabe, G. Seiler, and D. Stehle, Crystals  dilithium: Digital signatures from module lattices, Cryptology ePrint Archive, Paper 2017/633, 2017, https://eprint.iacr.org/2017/633. [Online]. Available: https://eprint.iacr.org/2017/633 [23] L. Fukshansky and C. Hollanti, Euclidean lattices: theory and applications, Communications in Mathematics , vol. Volume 31 (2023), Issue 2..., Oct. 2023. [Online]. Available: http://dx.doi.org/10.46298/cm.11596 [24] C. Peikert, A decade of lattice cryptography, Foundations and Trends ® in Theoretical Computer Science , vol. 10, no. 4, pp. 283424, 2016. [Online]. Available: http://dx.doi.org/10.1561/0400000074 60 Apéndice A. Interpreted Kyber code Figura A.8: Code for KyberCCA 61 Figura A.9: Code for test