Class: MLKEM::Math::Polynomial

Inherits:
Object
  • Object
show all
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.

Since:

  • 0.1.0

Instance Method Summary collapse

Constructor Details

#initialize(q = Constants::Q) ⇒ Polynomial

Initializes a Polynomial instance with a modulus q.

Examples:

poly = Polynomial.new

Parameters:

  • q (Integer) (defaults to: Constants::Q)

    The modulus used for polynomial arithmetic.

Since:

  • 0.1.0



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.

Examples:

result = poly.add([1, 2], [3, 4]) # => [4, 6]

Parameters:

  • f (Array<Integer>)

    First polynomial.

  • g (Array<Integer>)

    Second polynomial.

Returns:

  • (Array<Integer>)

    Resulting polynomial (f + g) mod q.

Since:

  • 0.1.0



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.

Examples:

compressed = poly.compress(4, [0, 1000, 2000])

Parameters:

  • d (Integer)

    Number of bits to compress to.

  • xv (Array<Integer>)

    Polynomial coefficients.

Returns:

  • (Array<Integer>)

    Compressed coefficients.

Since:

  • 0.1.0



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.

Examples:

decompressed = poly.decompress(4, [0, 5, 10])

Parameters:

  • d (Integer)

    Number of bits the coefficients were compressed to.

  • yv (Array<Integer>)

    Compressed coefficients.

Returns:

  • (Array<Integer>)

    Approximate original coefficients.

Since:

  • 0.1.0



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.

Examples:

result = poly.subtract([5, 3], [2, 1]) # => [3, 2]

Parameters:

  • f (Array<Integer>)

    Minuend polynomial.

  • g (Array<Integer>)

    Subtrahend polynomial.

Returns:

  • (Array<Integer>)

    Resulting polynomial (f - g) mod q.

Since:

  • 0.1.0



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