Class: MLKEM::Math::ByteOperations
- Inherits:
-
Object
- Object
- MLKEM::Math::ByteOperations
- Defined in:
- lib/ml_kem/math/byte_operations.rb
Overview
Byte and bit manipulation operations used in the ML-KEM standard (2024).
Provides methods to convert between bit arrays and byte strings, and to encode and decode arrays according to given parameters.
Class Method Summary collapse
-
.bits_to_bytes(b) ⇒ String
Converts an array of bits into a byte string.
-
.byte_decode(d, b, q) ⇒ Array<Integer>
Decodes a byte string into an array of values using dimension d and modulus q.
-
.byte_encode(d, f, q) ⇒ String
Encodes an array of values into a byte string using dimension d and modulus q.
-
.bytes_to_bits(b) ⇒ Array<Integer>
Converts a byte string into an array of bits.
Class Method Details
.bits_to_bytes(b) ⇒ String
Converts an array of bits into a byte string.
Implements Algorithm 3, BitsToBytes(b).
25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/ml_kem/math/byte_operations.rb', line 25 def self.bits_to_bytes(b) l = b.length a = Array.new(l / 8, 0) (0...l).step(8) do |i| x = 0 8.times do |j| x += b[i + j] << j end a[i / 8] = x end a.pack('C*') end |
.byte_decode(d, b, q) ⇒ Array<Integer>
Decodes a byte string into an array of values using dimension d and modulus q.
Implements Algorithm 6, ByteDecode_d(B).
106 107 108 109 110 111 112 113 114 115 116 117 118 |
# File 'lib/ml_kem/math/byte_operations.rb', line 106 def self.byte_decode(d, b, q) bits_array = bytes_to_bits(b) f = Array.new(256, 0) 256.times do |i| a = 0 d.times do |j| a += bits_array[d * i + j] << j end f[i] = a % q end f end |
.byte_encode(d, f, q) ⇒ String
Encodes an array of values into a byte string using dimension d and modulus q.
Implements Algorithm 5, ByteEncode_d(F).
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
# File 'lib/ml_kem/math/byte_operations.rb', line 77 def self.byte_encode(d, f, q) if f.first.is_a?(Array) return f.map { |x| byte_encode(d, x, q) }.join end b = Array.new(256 * d, 0) 256.times do |i| a = f[i] d.times do |j| b[d * i + j] = (a >> j) & 1 end end bits_to_bytes(b) end |
.bytes_to_bits(b) ⇒ Array<Integer>
Converts a byte string into an array of bits.
Implements Algorithm 4, BytesToBits(B).
48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/ml_kem/math/byte_operations.rb', line 48 def self.bytes_to_bits(b) l = b.length a = Array.new(8 * l, 0) (0...(8 * l)).step(8) do |i| x = b.bytes[i / 8] 8.times do |j| a[i + j] = (x >> j) & 1 end end a end |