Class: MLKEM::Math::Polynomial
- Inherits:
-
Object
- Object
- MLKEM::Math::Polynomial
- Defined in:
- lib/ml_kem/math/polynomial.rb
Overview
Implements polynomial arithmetic and compression/decompression operations used in ML-KEM (Kyber) cryptographic schemes.
Provides basic modular operations such as addition and subtraction as well as lossy compression methods used to reduce bandwidth.
Instance Method Summary collapse
-
#add(f, g) ⇒ Array<Integer>
Adds two polynomials coefficient-wise modulo q.
-
#compress(d, xv) ⇒ Array<Integer>
Compresses the coefficients of a polynomial to ‘d` bits.
-
#decompress(d, yv) ⇒ Array<Integer>
Decompresses ‘d`-bit values back into approximate polynomial coefficients.
-
#initialize(q = Constants::Q) ⇒ Polynomial
constructor
Initializes a Polynomial instance with a modulus q.
-
#subtract(f, g) ⇒ Array<Integer>
Subtracts one polynomial from another coefficient-wise modulo q.
Constructor Details
#initialize(q = Constants::Q) ⇒ Polynomial
Initializes a Polynomial instance with a modulus q.
19 20 21 |
# File 'lib/ml_kem/math/polynomial.rb', line 19 def initialize(q = Constants::Q) @q = q end |
Instance Method Details
#add(f, g) ⇒ Array<Integer>
Adds two polynomials coefficient-wise modulo q.
31 32 33 |
# File 'lib/ml_kem/math/polynomial.rb', line 31 def add(f, g) f.zip(g).map { |a, b| (a + b) % @q } end |
#compress(d, xv) ⇒ Array<Integer>
Compresses the coefficients of a polynomial to ‘d` bits.
Lossy operation used to reduce size during transmission.
57 58 59 60 61 |
# File 'lib/ml_kem/math/polynomial.rb', line 57 def compress(d, xv) xv.map do |x| (((x << d) + (@q - 1) / 2) / @q) % (1 << d) end end |
#decompress(d, yv) ⇒ Array<Integer>
Decompresses ‘d`-bit values back into approximate polynomial coefficients.
Inverse of ‘#compress`, though lossy.
73 74 75 76 77 |
# File 'lib/ml_kem/math/polynomial.rb', line 73 def decompress(d, yv) yv.map do |y| (@q * y + (1 << (d - 1))) >> d end end |
#subtract(f, g) ⇒ Array<Integer>
Subtracts one polynomial from another coefficient-wise modulo q.
43 44 45 |
# File 'lib/ml_kem/math/polynomial.rb', line 43 def subtract(f, g) f.zip(g).map { |a, b| (a - b) % @q } end |