add ledakemlt32

This commit is contained in:
Leon 2019-06-10 20:42:31 +02:00
parent 32b3a97809
commit 737cb1bb2e
21 changed files with 1591 additions and 0 deletions

View File

@ -0,0 +1,18 @@
name: LEDAcryptKEMLT32
type: kem
claimed-nist-level: 3
claimed-security: IND-CCA2
length-public-key: 12032
length-secret-key: 33
length-ciphertext: 12032
length-shared-secret: 48
nistkat-sha256: 5f4e10c91755d87722bc16e13c6bc5d8bcd6190589cb8924aedb8639d9f1f244
principal-submitter: Marco Baldi
auxiliary-submitters:
- Alessandro Barenghi
- Franco Chiaraluce
- Gerardo Pelosi
- Paolo Santini
implementations:
- name: clean
version: 2.0

View File

@ -0,0 +1,32 @@
#include "H_Q_matrices_generation.h"
#include "gf2x_arith_mod_xPplusOne.h"
void PQCLEAN_LEDAKEMLT32_CLEAN_generateHPosOnes_HtrPosOnes(
POSITION_T HPosOnes[N0][DV],
POSITION_T HtrPosOnes[N0][DV],
AES_XOF_struct *keys_expander) {
for (int i = 0; i < N0; i++) {
/* Generate a random block of Htr */
PQCLEAN_LEDAKEMLT32_CLEAN_rand_circulant_sparse_block(&HtrPosOnes[i][0], DV, keys_expander);
}
for (int i = 0; i < N0; i++) {
/* Obtain directly the sparse representation of the block of H */
for (int k = 0; k < DV; k++) {
HPosOnes[i][k] = (P - HtrPosOnes[i][k]) % P; /* transposes indexes */
}
}
}
void PQCLEAN_LEDAKEMLT32_CLEAN_generateQsparse(
POSITION_T pos_ones[N0][M],
AES_XOF_struct *keys_expander) {
for (int i = 0; i < N0; i++) {
int placed_ones = 0;
for (int j = 0; j < N0; j++) {
PQCLEAN_LEDAKEMLT32_CLEAN_rand_circulant_sparse_block(&pos_ones[i][placed_ones],
qBlockWeights[i][j],
keys_expander);
placed_ones += qBlockWeights[i][j];
}
}
}

View File

@ -0,0 +1,11 @@
#ifndef H_Q_MATRICES_GENERATION_H
#define H_Q_MATRICES_GENERATION_H
#include "gf2x_arith.h"
#include "qc_ldpc_parameters.h"
#include "rng.h"
void PQCLEAN_LEDAKEMLT32_CLEAN_generateHPosOnes_HtrPosOnes(POSITION_T HPosOnes[N0][DV], POSITION_T HtrPosOnes[N0][DV], AES_XOF_struct *niederreiter_keys_expander);
void PQCLEAN_LEDAKEMLT32_CLEAN_generateQsparse(POSITION_T pos_ones[N0][M], AES_XOF_struct *niederreiter_keys_expander);
#endif

View File

@ -0,0 +1,31 @@
/**
*
* LEDAcryptKEM
*
* @version 2.0 (March 2019)
*
* Adapted code from reference ISO-C11 Implementation of the LEDAcrypt KEM-LT cipher.
*
* In alphabetical order:
*
* @author Marco Baldi <m.baldi@univpm.it>
* @author Alessandro Barenghi <alessandro.barenghi@polimi.it>
* @author Franco Chiaraluce <f.chiaraluce@univpm.it>
* @author Gerardo Pelosi <gerardo.pelosi@polimi.it>
* @author Paolo Santini <p.santini@pm.univpm.it>
*
* This code is hereby placed in the public domain.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
**/

View File

@ -0,0 +1,24 @@
# This Makefile can be used with GNU Make or BSD Make
LIB=libledakemlt32_clean.a
HEADERS=api.h bf_decoding.h dfr_test.h gf2x_arith_mod_xPplusOne.h \
gf2x_arith.h H_Q_matrices_generation.h \
niederreiter.h qc_ldpc_parameters.h rng.h
OBJECTS=bf_decoding.o dfr_test.o gf2x_arith_mod_xPplusOne.o \
gf2x_arith.o H_Q_matrices_generation.o kem.o niederreiter.o rng.o
CFLAGS=-O3 -Wall -Werror -Wextra -Wvla -Wpedantic -Wmissing-prototypes -std=c99 \
-I../../../common $(EXTRAFLAGS)
all: $(LIB)
%.o: %.c $(HEADERS)
$(CC) $(CFLAGS) -c -o $@ $<
$(LIB): $(OBJECTS)
$(AR) -r $@ $(OBJECTS)
clean:
$(RM) $(OBJECTS)
$(RM) $(LIB)

View File

@ -0,0 +1,19 @@
# This Makefile can be used with Microsoft Visual Studio's nmake using the command:
# nmake /f Makefile.Microsoft_nmake
LIBRARY=libledakemlt32_clean.lib
OBJECTS=bf_decoding.obj dfr_test.obj gf2x_arith_mod_xPplusOne.obj gf2x_arith.obj H_Q_matrices_generation.obj kem.obj niederreiter.obj rng.obj
CFLAGS=/nologo /I ..\..\..\common /W4 /WX
all: $(LIBRARY)
# Make sure objects are recompiled if headers change.
$(OBJECTS): *.h
$(LIBRARY): $(OBJECTS)
LIB.EXE /NOLOGO /WX /OUT:$@ $**
clean:
-DEL $(OBJECTS)
-DEL $(LIBRARY)

View File

@ -0,0 +1,18 @@
#ifndef PQCLEAN_LEDAKEMLT32_CLEAN_API_H
#define PQCLEAN_LEDAKEMLT32_CLEAN_API_H
#define PQCLEAN_LEDAKEMLT32_CLEAN_CRYPTO_SECRETKEYBYTES 33
#define PQCLEAN_LEDAKEMLT32_CLEAN_CRYPTO_PUBLICKEYBYTES 12032
#define PQCLEAN_LEDAKEMLT32_CLEAN_CRYPTO_CIPHERTEXTBYTES 12032
#define PQCLEAN_LEDAKEMLT32_CLEAN_CRYPTO_BYTES 48
#define PQCLEAN_LEDAKEMLT32_CLEAN_CRYPTO_ALGNAME "LEDAKEMLT32"
int PQCLEAN_LEDAKEMLT32_CLEAN_crypto_kem_keypair(unsigned char *pk, unsigned char *sk);
int PQCLEAN_LEDAKEMLT32_CLEAN_crypto_kem_enc(unsigned char *ct, unsigned char *ss, const unsigned char *pk);
int PQCLEAN_LEDAKEMLT32_CLEAN_crypto_kem_dec(unsigned char *ss, const unsigned char *ct, const unsigned char *sk);
#endif

View File

@ -0,0 +1,77 @@
#include "bf_decoding.h"
#include "gf2x_arith_mod_xPplusOne.h"
#include <assert.h>
#include <string.h>
unsigned int thresholds[2] = {B0, (DV * M) / 2 + 1};
int PQCLEAN_LEDAKEMLT32_CLEAN_bf_decoding(DIGIT err[],
const POSITION_T HtrPosOnes[N0][DV],
const POSITION_T QtrPosOnes[N0][M],
DIGIT privateSyndrome[]) {
uint8_t unsatParityChecks[N0 * P];
POSITION_T currQBlkPos[M], currQBitPos[M];
DIGIT currSyndrome[NUM_DIGITS_GF2X_ELEMENT];
int check;
int iteration = 0;
do {
gf2x_copy(currSyndrome, privateSyndrome);
memset(unsatParityChecks, 0x00, N0 * P * sizeof(uint8_t));
for (int i = 0; i < N0; i++) {
for (int valueIdx = 0; valueIdx < P; valueIdx++) {
for (int HtrOneIdx = 0; HtrOneIdx < DV; HtrOneIdx++) {
POSITION_T tmp = (HtrPosOnes[i][HtrOneIdx] + valueIdx) >= P ? (HtrPosOnes[i][HtrOneIdx] + valueIdx) - P : (HtrPosOnes[i][HtrOneIdx] + valueIdx);
if (gf2x_get_coeff(currSyndrome, tmp)) {
unsatParityChecks[i * P + valueIdx]++;
}
}
}
}
/* iteration based threshold determination*/
unsigned int corrt_syndrome_based = thresholds[iteration];
//Computation of correlation with a full Q matrix
for (int i = 0; i < N0; i++) {
for (int j = 0; j < P; j++) {
int currQoneIdx = 0; // position in the column of QtrPosOnes[][...]
int endQblockIdx = 0;
unsigned int correlation = 0;
for (int blockIdx = 0; blockIdx < N0; blockIdx++) {
endQblockIdx += qBlockWeights[blockIdx][i];
int currblockoffset = blockIdx * P;
for (; currQoneIdx < endQblockIdx; currQoneIdx++) {
uint32_t tmp = QtrPosOnes[i][currQoneIdx] + j;
tmp = tmp >= P ? tmp - P : tmp;
currQBitPos[currQoneIdx] = tmp;
currQBlkPos[currQoneIdx] = blockIdx;
correlation += unsatParityChecks[tmp + currblockoffset];
}
}
/* Correlation based flipping */
if (correlation >= corrt_syndrome_based) {
gf2x_toggle_coeff(err + NUM_DIGITS_GF2X_ELEMENT * i, j);
for (int v = 0; v < M; v++) {
unsigned syndromePosToFlip;
for (int HtrOneIdx = 0; HtrOneIdx < DV; HtrOneIdx++) {
syndromePosToFlip = (HtrPosOnes[currQBlkPos[v]][HtrOneIdx] + currQBitPos[v] );
syndromePosToFlip = syndromePosToFlip >= P ? syndromePosToFlip - P : syndromePosToFlip;
gf2x_toggle_coeff(privateSyndrome, syndromePosToFlip);
}
} // end for v
} // end if
} // end for j
} // end for i
iteration = iteration + 1;
check = 0;
while (check < NUM_DIGITS_GF2X_ELEMENT && privateSyndrome[check++] == 0) {};
} while (iteration < ITERATIONS_MAX && check < NUM_DIGITS_GF2X_ELEMENT);
return (check == NUM_DIGITS_GF2X_ELEMENT);
}

View File

@ -0,0 +1,17 @@
#ifndef BF_DECODING_H
#define BF_DECODING_H
#include "gf2x_arith.h"
#include "qc_ldpc_parameters.h"
/* Definitions for DFR level 2^-SL with SL=128 */
#define ITERATIONS_MAX (2)
#define B0 (64)
#define T_BAR (5)
int PQCLEAN_LEDAKEMLT32_CLEAN_bf_decoding(DIGIT err[],
const POSITION_T HtrPosOnes[N0][DV],
const POSITION_T QtrPosOnes[N0][M],
DIGIT privateSyndrome[]);
#endif

View File

@ -0,0 +1,120 @@
#include "bf_decoding.h"
#include "dfr_test.h"
#include "gf2x_arith_mod_xPplusOne.h"
#include "qc_ldpc_parameters.h"
#include <string.h>
/* Tests if the current code attains the desired DFR. If that is the case,
* computes the threshold for the second iteration of the decoder and stores
* it in the globally accessible vector */
extern unsigned int thresholds[2];
int PQCLEAN_LEDAKEMLT32_CLEAN_DFR_test(POSITION_T LSparse[N0][DV * M]) {
POSITION_T LSparse_loc[N0][DV * M];
/* Gamma matrix: an N0 x N0 block circulant matrix with block size p
* gamma[a][b][c] stores the intersection of the first column of the a-th
* block of L with the c-th column of the b-th block of L */
/* Gamma computation can be accelerated employing symmetry and QC properties */
unsigned int gamma[N0][N0][P] = {{{0}}};
unsigned int rotated_column[DV * M];
unsigned int firstidx, secondidx, intersectionval;
unsigned int gammaHist[N0][DV * M + 1] = {{0}};
unsigned int maxMut[N0], maxMutMinusOne[N0];
unsigned int allBlockMaxSumst, allBlockMaxSumstMinusOne;
unsigned int toAdd, histIdx;
/*transpose blocks of L, we need its columns */
for (int i = 0; i < N0; i++) {
for (int j = 0; j < DV * M; j++) {
if (LSparse[i][j] != 0) {
LSparse_loc[i][j] = (P - LSparse[i][j]);
}
}
quicksort_sparse(LSparse_loc[i]);
}
for (int i = 0; i < N0; i++ ) {
for (int j = 0; j < N0; j++ ) {
for (int k = 0; k < P; k++) {
/* compute the rotated sparse column needed */
for (int idxToRotate = 0; idxToRotate < (DV * M); idxToRotate++) {
rotated_column[idxToRotate] = (LSparse_loc[j][idxToRotate] + k) % P;
}
quicksort_sparse(rotated_column);
/* compute the intersection amount */
firstidx = 0, secondidx = 0;
intersectionval = 0;
while ( (firstidx < DV * M) && (secondidx < DV * M) ) {
if ( LSparse_loc[i][firstidx] == rotated_column[secondidx] ) {
intersectionval++;
firstidx++;
secondidx++;
} else if ( LSparse_loc[i][firstidx] > rotated_column[secondidx] ) {
secondidx++;
} else { /*if ( LSparse_loc[i][firstidx] < rotated_column[secondidx] ) */
firstidx++;
}
}
gamma[i][j][k] = intersectionval;
}
}
}
for (int i = 0; i < N0; i++ ) {
for (int j = 0; j < N0; j++ ) {
gamma[i][j][0] = 0;
}
}
/* build histogram of values in gamma */
for (int i = 0; i < N0; i++ ) {
for (int j = 0; j < N0; j++ ) {
for (int k = 0; k < P; k++) {
gammaHist[i][gamma[i][j][k]]++;
}
}
}
for (int gammaBlockRowIdx = 0; gammaBlockRowIdx < N0; gammaBlockRowIdx++) {
toAdd = T_BAR - 1;
maxMutMinusOne[gammaBlockRowIdx] = 0;
histIdx = DV * M;
while ( (histIdx > 0) && (toAdd > 0)) {
if (gammaHist[gammaBlockRowIdx][histIdx] > toAdd ) {
maxMutMinusOne[gammaBlockRowIdx] += histIdx * toAdd;
toAdd = 0;
} else {
maxMutMinusOne[gammaBlockRowIdx] += histIdx * gammaHist[gammaBlockRowIdx][histIdx];
toAdd -= gammaHist[gammaBlockRowIdx][histIdx];
histIdx--;
}
}
maxMut[gammaBlockRowIdx] = histIdx + maxMutMinusOne[gammaBlockRowIdx];
}
/*seek max values across all gamma blocks */
allBlockMaxSumst = maxMut[0];
allBlockMaxSumstMinusOne = maxMutMinusOne[0];
for (int gammaBlockRowIdx = 0; gammaBlockRowIdx < N0 ; gammaBlockRowIdx++) {
allBlockMaxSumst = allBlockMaxSumst < maxMut[gammaBlockRowIdx] ?
maxMut[gammaBlockRowIdx] :
allBlockMaxSumst;
allBlockMaxSumstMinusOne = allBlockMaxSumstMinusOne < maxMutMinusOne[gammaBlockRowIdx] ?
maxMutMinusOne[gammaBlockRowIdx] :
allBlockMaxSumstMinusOne;
}
if (DV * M > (allBlockMaxSumstMinusOne + allBlockMaxSumst)) {
thresholds[1] = allBlockMaxSumst + 1;
return 1;
}
return 0;
}

View File

@ -0,0 +1,6 @@
#ifndef DFR_TEST_H
#define DFR_TEST_H
int PQCLEAN_LEDAKEMLT32_CLEAN_DFR_test(POSITION_T LSparse[N0][DV * M]);
#endif

View File

@ -0,0 +1,100 @@
#include "gf2x_arith.h"
#include <assert.h>
#include <string.h> // memset(...)
/* allows the second operand to be shorter than the first */
/* the result should be as large as the first operand*/
static inline void gf2x_add_asymm(const size_t nr, DIGIT Res[],
const size_t na, const DIGIT A[],
const size_t nb, const DIGIT B[]) {
assert(nr >= na && na >= nb);
size_t i;
size_t delta = na - nb;
for (i = 0; i < delta; i++) {
Res[i] = A[i];
}
for (i = 0; i < nb; i++) {
Res[i + delta] = A[i + delta] ^ B[i];
}
}
/* PRE: MAX ALLOWED ROTATION AMOUNT : DIGIT_SIZE_b */
void PQCLEAN_LEDAKEMLT32_CLEAN_right_bit_shift_n(size_t length, DIGIT in[], unsigned int amount) {
assert(amount < DIGIT_SIZE_b);
if ( amount == 0 ) {
return;
}
unsigned int j;
DIGIT mask;
mask = ((DIGIT)0x01 << amount) - 1;
for (j = length - 1; j > 0 ; j--) {
in[j] >>= amount;
in[j] |= (in[j - 1] & mask) << (DIGIT_SIZE_b - amount);
}
in[j] >>= amount;
}
/* PRE: MAX ALLOWED ROTATION AMOUNT : DIGIT_SIZE_b */
void PQCLEAN_LEDAKEMLT32_CLEAN_left_bit_shift_n(size_t length, DIGIT in[], unsigned int amount) {
assert(amount < DIGIT_SIZE_b);
if ( amount == 0 ) {
return;
}
size_t j;
DIGIT mask;
mask = ~(((DIGIT)0x01 << (DIGIT_SIZE_b - amount)) - 1);
for (j = 0 ; j < length - 1 ; j++) {
in[j] <<= amount;
in[j] |= (in[j + 1] & mask) >> (DIGIT_SIZE_b - amount);
}
in[j] <<= amount;
}
void PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mul_comb(int nr, DIGIT Res[],
int na, const DIGIT A[],
int nb, const DIGIT B[]) {
int i, j, k;
DIGIT u, h;
memset(Res, 0x00, nr * sizeof(DIGIT));
for (k = DIGIT_SIZE_b - 1; k > 0; k--) {
for (i = na - 1; i >= 0; i--) {
if ( A[i] & (((DIGIT)0x1) << k) ) {
for (j = nb - 1; j >= 0; j--) {
Res[i + j + 1] ^= B[j];
}
}
}
u = Res[na + nb - 1];
Res[na + nb - 1] = u << 0x1;
for (j = 1; j < na + nb; ++j) {
h = u >> (DIGIT_SIZE_b - 1);
u = Res[na + nb - 1 - j];
Res[na + nb - 1 - j] = h ^ (u << 0x1);
}
}
for (i = na - 1; i >= 0; i--) {
if ( A[i] & ((DIGIT)0x1) ) {
for (j = nb - 1; j >= 0; j--) {
Res[i + j + 1] ^= B[j];
}
}
}
}
static inline void gf2x_exact_div_x_plus_one(const int na, DIGIT A[]) {
DIGIT t = 0;
for (int i = na - 1; i >= 0; i--) {
t ^= A[i];
for (int j = 1; j <= DIGIT_SIZE_b / 2; j = j * 2) {
t ^= t << (unsigned) j;
}
A[i] = t;
t >>= DIGIT_SIZE_b - 1;
}
}

View File

@ -0,0 +1,63 @@
#ifndef GF2X_ARITH_H
#define GF2X_ARITH_H
#include <inttypes.h>
#include <stddef.h>
/*
* Elements of GF(2)[x] are stored in compact dense binary form.
*
* Each bit in a byte is assumed to be the coefficient of a binary
* polynomial f(x), in Big-Endian format (i.e., reading everything from
* left to right, the most significant element is met first):
*
* byte:(0000 0000) == 0x00 ... f(x) == 0
* byte:(0000 0001) == 0x01 ... f(x) == 1
* byte:(0000 0010) == 0x02 ... f(x) == x
* byte:(0000 0011) == 0x03 ... f(x) == x+1
* ... ... ...
* byte:(0000 1111) == 0x0F ... f(x) == x^{3}+x^{2}+x+1
* ... ... ...
* byte:(1111 1111) == 0xFF ... f(x) == x^{7}+x^{6}+x^{5}+x^{4}+x^{3}+x^{2}+x+1
*
*
* A "machine word" (A_i) is considered as a DIGIT.
* Bytes in a DIGIT are assumed in Big-Endian format:
* E.g., if sizeof(DIGIT) == 4:
* A_i: A_{i,3} A_{i,2} A_{i,1} A_{i,0}.
* A_{i,3} denotes the most significant byte, A_{i,0} the least significant one.
* f(x) == x^{31} + ... + x^{24} +
* + x^{23} + ... + x^{16} +
* + x^{15} + ... + x^{8} +
* + x^{7} + ... + x^{0}
*
*
* Multi-precision elements (i.e., with multiple DIGITs) are stored in
* Big-endian format:
* A = A_{n-1} A_{n-2} ... A_1 A_0
*
* position[A_{n-1}] == 0
* position[A_{n-2}] == 1
* ...
* position[A_{1}] == n-2
* position[A_{0}] == n-1
*/
typedef uint64_t DIGIT;
#define DIGIT_SIZE_B (8)
#define DIGIT_SIZE_b (DIGIT_SIZE_B << 3)
#define POSITION_T uint32_t
#define GF2X_MUL PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mul_comb
static inline void gf2x_add(DIGIT Res[], const DIGIT A[], const DIGIT B[], size_t nr) {
for (size_t i = 0; i < nr; i++) {
Res[i] = A[i] ^ B[i];
}
}
void PQCLEAN_LEDAKEMLT32_CLEAN_right_bit_shift_n(size_t length, DIGIT in[], unsigned int amount);
void PQCLEAN_LEDAKEMLT32_CLEAN_left_bit_shift_n(size_t length, DIGIT in[], unsigned int amount);
void GF2X_MUL(int nr, DIGIT Res[], int na, const DIGIT A[], int nb, const DIGIT B[]);
#endif

View File

@ -0,0 +1,481 @@
#include "gf2x_arith_mod_xPplusOne.h"
#include "rng.h"
#include <assert.h>
#include <string.h> // memcpy(...), memset(...)
static void gf2x_mod(DIGIT out[], const DIGIT in[]) {
int i, j, posTrailingBit, maskOffset, to_copy;
DIGIT mask, aux[2 * NUM_DIGITS_GF2X_ELEMENT];
memcpy(aux, in, 2 * NUM_DIGITS_GF2X_ELEMENT * DIGIT_SIZE_B);
memset(out, 0x00, NUM_DIGITS_GF2X_ELEMENT * DIGIT_SIZE_B);
for (i = 0; i < (2 * NUM_DIGITS_GF2X_ELEMENT) - NUM_DIGITS_GF2X_MODULUS; i += 1) {
for (j = DIGIT_SIZE_b - 1; j >= 0; j--) {
mask = ((DIGIT)0x1) << j;
if (aux[i] & mask) {
aux[i] ^= mask;
posTrailingBit = (DIGIT_SIZE_b - 1 - j) + i * DIGIT_SIZE_b + P;
maskOffset = (DIGIT_SIZE_b - 1 - (posTrailingBit % DIGIT_SIZE_b));
mask = (DIGIT) 0x1 << maskOffset;
aux[posTrailingBit / DIGIT_SIZE_b] ^= mask;
}
}
}
for (j = DIGIT_SIZE_b - 1; j >= MSb_POSITION_IN_MSB_DIGIT_OF_MODULUS; j--) {
mask = ((DIGIT)0x1) << j;
if (aux[i] & mask) {
aux[i] ^= mask;
posTrailingBit = (DIGIT_SIZE_b - 1 - j) + i * DIGIT_SIZE_b + P;
maskOffset = (DIGIT_SIZE_b - 1 - (posTrailingBit % DIGIT_SIZE_b));
mask = (DIGIT) 0x1 << maskOffset;
aux[posTrailingBit / DIGIT_SIZE_b] ^= mask;
}
}
to_copy = (2 * NUM_DIGITS_GF2X_ELEMENT > NUM_DIGITS_GF2X_ELEMENT) ? NUM_DIGITS_GF2X_ELEMENT : 2 * NUM_DIGITS_GF2X_ELEMENT;
for (i = 0; i < to_copy; i++) {
out[NUM_DIGITS_GF2X_ELEMENT - 1 - i] = aux[2 * NUM_DIGITS_GF2X_ELEMENT - 1 - i];
}
}
static void left_bit_shift(const int length, DIGIT in[]) {
int j;
for (j = 0; j < length - 1; j++) {
in[j] <<= 1; /* logical shift does not need clearing */
in[j] |= in[j + 1] >> (DIGIT_SIZE_b - 1);
}
in[j] <<= 1;
}
static void right_bit_shift(unsigned int length, DIGIT in[]) {
unsigned int j;
for (j = length - 1; j > 0 ; j--) {
in[j] >>= 1;
in[j] |= (in[j - 1] & (DIGIT)0x01) << (DIGIT_SIZE_b - 1);
}
in[j] >>= 1;
}
/* shifts by whole digits */
static inline void left_DIGIT_shift_n(unsigned int length, DIGIT in[], unsigned int amount) {
unsigned int j;
for (j = 0; (j + amount) < length; j++) {
in[j] = in[j + amount];
}
for (; j < length; j++) {
in[j] = (DIGIT)0;
}
}
/* may shift by an arbitrary amount*/
static void left_bit_shift_wide_n(const int length, DIGIT in[], unsigned int amount) {
left_DIGIT_shift_n(length, in, amount / DIGIT_SIZE_b);
PQCLEAN_LEDAKEMLT32_CLEAN_left_bit_shift_n(length, in, amount % DIGIT_SIZE_b);
}
/* Hackers delight, reverses a uint64_t */
static DIGIT reverse_digit(DIGIT x) {
uint64_t t;
x = (x << 31) | (x >> 33);
t = (x ^ (x >> 20)) & 0x00000FFF800007FFLL;
x = (t | (t << 20)) ^ x;
t = (x ^ (x >> 8)) & 0x00F8000F80700807LL;
x = (t | (t << 8)) ^ x;
t = (x ^ (x >> 4)) & 0x0808708080807008LL;
x = (t | (t << 4)) ^ x;
t = (x ^ (x >> 2)) & 0x1111111111111111LL;
x = (t | (t << 2)) ^ x;
return x;
}
void PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_transpose_in_place(DIGIT A[]) {
/* it keeps the lsb in the same position and
* inverts the sequence of the remaining bits */
DIGIT mask = (DIGIT)0x1;
DIGIT rev1, rev2, a00;
int i, slack_bits_amount = NUM_DIGITS_GF2X_ELEMENT * DIGIT_SIZE_b - P;
a00 = A[NUM_DIGITS_GF2X_ELEMENT - 1] & mask;
right_bit_shift(NUM_DIGITS_GF2X_ELEMENT, A);
for (i = NUM_DIGITS_GF2X_ELEMENT - 1; i >= (NUM_DIGITS_GF2X_ELEMENT + 1) / 2; i--) {
rev1 = reverse_digit(A[i]);
rev2 = reverse_digit(A[NUM_DIGITS_GF2X_ELEMENT - 1 - i]);
A[i] = rev2;
A[NUM_DIGITS_GF2X_ELEMENT - 1 - i] = rev1;
}
// A[NUM_DIGITS_GF2X_ELEMENT / 2] = reverse_digit(A[NUM_DIGITS_GF2X_ELEMENT / 2]); // reverse middle digit
if (slack_bits_amount) {
PQCLEAN_LEDAKEMLT32_CLEAN_right_bit_shift_n(NUM_DIGITS_GF2X_ELEMENT, A, slack_bits_amount);
}
A[NUM_DIGITS_GF2X_ELEMENT - 1] = (A[NUM_DIGITS_GF2X_ELEMENT - 1] & (~mask)) | a00;
}
static void rotate_bit_left(DIGIT in[]) { /* equivalent to x * in(x) mod x^P+1 */
DIGIT mask, rotated_bit;
int msb_offset_in_digit = MSb_POSITION_IN_MSB_DIGIT_OF_MODULUS - 1;
mask = ((DIGIT)0x1) << msb_offset_in_digit;
rotated_bit = !!(in[0] & mask);
in[0] &= ~mask;
left_bit_shift(NUM_DIGITS_GF2X_ELEMENT, in);
in[NUM_DIGITS_GF2X_ELEMENT - 1] |= rotated_bit;
}
static void rotate_bit_right(DIGIT in[]) { /* x^{-1} * in(x) mod x^P+1 */
DIGIT rotated_bit = in[NUM_DIGITS_GF2X_ELEMENT - 1] & ((DIGIT)0x1);
right_bit_shift(NUM_DIGITS_GF2X_ELEMENT, in);
int msb_offset_in_digit = MSb_POSITION_IN_MSB_DIGIT_OF_MODULUS - 1;
rotated_bit = rotated_bit << msb_offset_in_digit;
in[0] |= rotated_bit;
}
static void gf2x_swap(const int length,
DIGIT f[],
DIGIT s[]) {
DIGIT t;
for (int i = length - 1; i >= 0; i--) {
t = f[i];
f[i] = s[i];
s[i] = t;
}
}
/*
* Optimized extended GCD algorithm to compute the multiplicative inverse of
* a non-zero element in GF(2)[x] mod x^P+1, in polyn. representation.
*
* H. Brunner, A. Curiger, and M. Hofstetter. 1993.
* On Computing Multiplicative Inverses in GF(2^m).
* IEEE Trans. Comput. 42, 8 (August 1993), 1010-1015.
* DOI=http://dx.doi.org/10.1109/12.238496
*
*
* Henri Cohen, Gerhard Frey, Roberto Avanzi, Christophe Doche, Tanja Lange,
* Kim Nguyen, and Frederik Vercauteren. 2012.
* Handbook of Elliptic and Hyperelliptic Curve Cryptography,
* Second Edition (2nd ed.). Chapman & Hall/CRC.
* (Chapter 11 -- Algorithm 11.44 -- pag 223)
*
*/
int PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mod_inverse(DIGIT out[], const DIGIT in[]) { /* in^{-1} mod x^P-1 */
int i;
long int delta = 0;
DIGIT u[NUM_DIGITS_GF2X_ELEMENT] = {0};
DIGIT v[NUM_DIGITS_GF2X_ELEMENT] = {0};
DIGIT s[NUM_DIGITS_GF2X_MODULUS] = {0};
DIGIT f[NUM_DIGITS_GF2X_MODULUS] = {0}; // alignas(32)?
DIGIT mask;
u[NUM_DIGITS_GF2X_ELEMENT - 1] = 0x1;
v[NUM_DIGITS_GF2X_ELEMENT - 1] = 0x0;
s[NUM_DIGITS_GF2X_MODULUS - 1] = 0x1;
mask = (((DIGIT)0x1) << MSb_POSITION_IN_MSB_DIGIT_OF_MODULUS);
s[0] |= mask;
for (i = NUM_DIGITS_GF2X_ELEMENT - 1; i >= 0 && in[i] == 0; i--) { };
if (i < 0) {
return 0;
}
for (i = NUM_DIGITS_GF2X_MODULUS - 1; i >= 0 ; i--) {
f[i] = in[i];
}
for (i = 1; i <= 2 * P; i++) {
if ( (f[0] & mask) == 0 ) {
left_bit_shift(NUM_DIGITS_GF2X_MODULUS, f);
rotate_bit_left(u);
delta += 1;
} else {
if ( (s[0] & mask) != 0) {
gf2x_add(s, s, f, NUM_DIGITS_GF2X_MODULUS);
gf2x_mod_add(v, v, u);
}
left_bit_shift(NUM_DIGITS_GF2X_MODULUS, s);
if ( delta == 0 ) {
gf2x_swap(NUM_DIGITS_GF2X_MODULUS, f, s);
gf2x_swap(NUM_DIGITS_GF2X_ELEMENT, u, v);
rotate_bit_left(u);
delta = 1;
} else {
rotate_bit_right(u);
delta = delta - 1;
}
}
}
for (i = NUM_DIGITS_GF2X_ELEMENT - 1; i >= 0 ; i--) {
out[i] = u[i];
}
return (delta == 0);
}
void PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mod_mul(DIGIT Res[], const DIGIT A[], const DIGIT B[]) {
DIGIT aux[2 * NUM_DIGITS_GF2X_ELEMENT];
GF2X_MUL(2 * NUM_DIGITS_GF2X_ELEMENT, aux,
NUM_DIGITS_GF2X_ELEMENT, A,
NUM_DIGITS_GF2X_ELEMENT, B);
gf2x_mod(Res, aux);
}
/*PRE: the representation of the sparse coefficients is sorted in increasing
order of the coefficients themselves */
void PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mod_mul_dense_to_sparse(
DIGIT Res[],
const DIGIT dense[],
POSITION_T sparse[], unsigned int nPos) {
DIGIT aux[2 * NUM_DIGITS_GF2X_ELEMENT] = {0x00};
DIGIT resDouble[2 * NUM_DIGITS_GF2X_ELEMENT] = {0x00};
memcpy(aux + NUM_DIGITS_GF2X_ELEMENT, dense, NUM_DIGITS_GF2X_ELEMENT * DIGIT_SIZE_B);
memcpy(resDouble + NUM_DIGITS_GF2X_ELEMENT, dense,
NUM_DIGITS_GF2X_ELEMENT * DIGIT_SIZE_B);
if (sparse[0] != INVALID_POS_VALUE) {
left_bit_shift_wide_n(2 * NUM_DIGITS_GF2X_ELEMENT, resDouble, sparse[0]);
left_bit_shift_wide_n(2 * NUM_DIGITS_GF2X_ELEMENT, aux, sparse[0]);
for (unsigned int i = 1; i < nPos; i++) {
if (sparse[i] != INVALID_POS_VALUE) {
left_bit_shift_wide_n(2 * NUM_DIGITS_GF2X_ELEMENT, aux, (sparse[i] - sparse[i - 1]) );
gf2x_add(resDouble, aux, resDouble, 2 * NUM_DIGITS_GF2X_ELEMENT);
}
}
}
gf2x_mod(Res, resDouble);
}
void PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_transpose_in_place_sparse(int sizeA, POSITION_T A[]) {
POSITION_T t;
int i = 0, j;
if (A[i] == 0) {
i = 1;
}
j = i;
for (; i < sizeA && A[i] != INVALID_POS_VALUE; i++) {
A[i] = P - A[i];
}
for (i -= 1; j < i; j++, i--) {
t = A[j];
A[j] = A[i];
A[i] = t;
}
}
void PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mod_mul_sparse(size_t sizeR, POSITION_T Res[],
size_t sizeA, const POSITION_T A[],
size_t sizeB, const POSITION_T B[]) {
/* compute all the coefficients, filling invalid positions with P*/
size_t lastFilledPos = 0;
for (size_t i = 0 ; i < sizeA ; i++) {
for (size_t j = 0 ; j < sizeB ; j++) {
uint32_t prod = A[i] + B[j];
prod = ( (prod >= P) ? prod - P : prod);
if ((A[i] != INVALID_POS_VALUE) &&
(B[j] != INVALID_POS_VALUE)) {
Res[lastFilledPos] = prod;
} else {
Res[lastFilledPos] = INVALID_POS_VALUE;
}
lastFilledPos++;
}
}
while (lastFilledPos < sizeR) {
Res[lastFilledPos] = INVALID_POS_VALUE;
lastFilledPos++;
}
quicksort_sparse(Res);
/* eliminate duplicates */
POSITION_T lastReadPos = Res[0];
int duplicateCount;
size_t write_idx = 0;
size_t read_idx = 0;
while (read_idx < sizeR && Res[read_idx] != INVALID_POS_VALUE) {
lastReadPos = Res[read_idx];
read_idx++;
duplicateCount = 1;
while ( (Res[read_idx] == lastReadPos) && (Res[read_idx] != INVALID_POS_VALUE)) {
read_idx++;
duplicateCount++;
}
if (duplicateCount % 2) {
Res[write_idx] = lastReadPos;
write_idx++;
}
}
/* fill remaining cells with INVALID_POS_VALUE */
for (; write_idx < sizeR; write_idx++) {
Res[write_idx] = INVALID_POS_VALUE;
}
}
/* the implementation is safe even in case A or B alias with the result */
/* PRE: A and B should be sorted and have INVALID_POS_VALUE at the end */
void PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mod_add_sparse(
int sizeR, POSITION_T Res[],
int sizeA, const POSITION_T A[],
int sizeB, const POSITION_T B[]) {
POSITION_T tmpRes[DV * M]; // TODO: now function only works for adding (disjunct) DV and M positions
int idxA = 0, idxB = 0, idxR = 0;
while ( idxA < sizeA &&
idxB < sizeB &&
A[idxA] != INVALID_POS_VALUE &&
B[idxB] != INVALID_POS_VALUE ) {
if (A[idxA] == B[idxB]) {
idxA++;
idxB++;
} else {
if (A[idxA] < B[idxB]) {
tmpRes[idxR] = A[idxA];
idxA++;
} else {
tmpRes[idxR] = B[idxB];
idxB++;
}
idxR++;
}
}
while (idxA < sizeA && A[idxA] != INVALID_POS_VALUE) {
tmpRes[idxR] = A[idxA];
idxA++;
idxR++;
}
while (idxB < sizeB && B[idxB] != INVALID_POS_VALUE) {
tmpRes[idxR] = B[idxB];
idxB++;
idxR++;
}
while (idxR < sizeR) {
tmpRes[idxR] = INVALID_POS_VALUE;
idxR++;
}
memcpy(Res, tmpRes, sizeof(POSITION_T)*sizeR);
}
/* Return a uniform random value in the range 0..n-1 inclusive,
* applying a rejection sampling strategy and exploiting as a random source
* the NIST seedexpander seeded with the proper key.
* Assumes that the maximum value for the range n is 2^32-1
*/
static uint32_t rand_range(const unsigned int n, const int logn, AES_XOF_struct *seed_expander_ctx) {
unsigned long required_rnd_bytes = (logn + 7) / 8;
unsigned char rnd_char_buffer[4];
uint32_t rnd_value;
uint32_t mask = ( (uint32_t)1 << logn) - 1;
do {
PQCLEAN_LEDAKEMLT32_CLEAN_seedexpander(seed_expander_ctx, rnd_char_buffer, required_rnd_bytes);
/* obtain an endianness independent representation of the generated random
bytes into an unsigned integer */
rnd_value = ((uint32_t)rnd_char_buffer[3] << 24) +
((uint32_t)rnd_char_buffer[2] << 16) +
((uint32_t)rnd_char_buffer[1] << 8) +
((uint32_t)rnd_char_buffer[0] << 0) ;
rnd_value = mask & rnd_value;
} while (rnd_value >= n);
return rnd_value;
}
/* Obtains fresh randomness and seed-expands it until all the required positions
* for the '1's in the circulant block are obtained */
void PQCLEAN_LEDAKEMLT32_CLEAN_rand_circulant_sparse_block(POSITION_T *pos_ones,
int countOnes,
AES_XOF_struct *seed_expander_ctx) {
int duplicated, placedOnes = 0;
uint32_t p;
while (placedOnes < countOnes) {
p = rand_range(NUM_BITS_GF2X_ELEMENT,
P_BITS,
seed_expander_ctx);
duplicated = 0;
for (int j = 0; j < placedOnes; j++) {
if (pos_ones[j] == p) {
duplicated = 1;
}
}
if (duplicated == 0) {
pos_ones[placedOnes] = p;
placedOnes++;
}
}
}
/* Returns random weight-t circulant block */
void PQCLEAN_LEDAKEMLT32_CLEAN_rand_circulant_blocks_sequence(
DIGIT sequence[N0 * NUM_DIGITS_GF2X_ELEMENT],
AES_XOF_struct *seed_expander_ctx) {
int rndPos[NUM_ERRORS_T], duplicated, counter = 0;
memset(sequence, 0x00, N0 * NUM_DIGITS_GF2X_ELEMENT * DIGIT_SIZE_B);
while (counter < NUM_ERRORS_T) {
int p = rand_range(N0 * NUM_BITS_GF2X_ELEMENT, P_BITS,
seed_expander_ctx);
duplicated = 0;
for (int j = 0; j < counter; j++) {
if (rndPos[j] == p) {
duplicated = 1;
}
}
if (duplicated == 0) {
rndPos[counter] = p;
counter++;
}
}
for (int j = 0; j < counter; j++) {
int polyIndex = rndPos[j] / P;
int exponent = rndPos[j] % P;
gf2x_set_coeff( sequence + NUM_DIGITS_GF2X_ELEMENT * polyIndex, exponent,
( (DIGIT) 1));
}
}
void PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_tobytes(uint8_t *bytes, const DIGIT *poly) {
size_t i, j;
for (i = 0; i < NUM_DIGITS_GF2X_ELEMENT; i++) {
for (j = 0; j < DIGIT_SIZE_B; j++) {
bytes[i * DIGIT_SIZE_B + j] = (uint8_t) ((poly[i] >> (8 * j)) & 0xFF);
}
}
}

View File

@ -0,0 +1,129 @@
#ifndef GF2X_ARITH_MOD_XPLUSONE_H
#define GF2X_ARITH_MOD_XPLUSONE_H
#include "qc_ldpc_parameters.h"
#include "gf2x_arith.h"
#include "rng.h"
#define NUM_BITS_GF2X_ELEMENT (P) // 96221
#define NUM_DIGITS_GF2X_ELEMENT ((P+DIGIT_SIZE_b-1)/DIGIT_SIZE_b)
#define MSb_POSITION_IN_MSB_DIGIT_OF_ELEMENT ((P % DIGIT_SIZE_b) ? (P % DIGIT_SIZE_b)-1 : DIGIT_SIZE_b-1)
#define NUM_BITS_GF2X_MODULUS (P+1)
#define NUM_DIGITS_GF2X_MODULUS ((P+1+DIGIT_SIZE_b-1)/DIGIT_SIZE_b)
#define MSb_POSITION_IN_MSB_DIGIT_OF_MODULUS (P-DIGIT_SIZE_b*(NUM_DIGITS_GF2X_MODULUS-1))
#define INVALID_POS_VALUE (P)
#define P_BITS (17) // log_2(p) = 16.55406417
static inline void gf2x_copy(DIGIT dest[], const DIGIT in[]) {
for (int i = NUM_DIGITS_GF2X_ELEMENT - 1; i >= 0; i--) {
dest[i] = in[i];
}
}
/* returns the coefficient of the x^exponent term as the LSB of a digit */
static inline DIGIT gf2x_get_coeff(const DIGIT poly[], unsigned int exponent) {
unsigned int straightIdx = (NUM_DIGITS_GF2X_ELEMENT * DIGIT_SIZE_b - 1) - exponent;
unsigned int digitIdx = straightIdx / DIGIT_SIZE_b;
unsigned int inDigitIdx = straightIdx % DIGIT_SIZE_b;
return (poly[digitIdx] >> (DIGIT_SIZE_b - 1 - inDigitIdx)) & ((DIGIT) 1) ;
}
/* sets the coefficient of the x^exponent term as the LSB of a digit */
static inline void gf2x_set_coeff(DIGIT poly[], unsigned int exponent, DIGIT value) {
unsigned int straightIdx = (NUM_DIGITS_GF2X_ELEMENT * DIGIT_SIZE_b - 1) - exponent;
unsigned int digitIdx = straightIdx / DIGIT_SIZE_b;
unsigned int inDigitIdx = straightIdx % DIGIT_SIZE_b;
/* clear given coefficient */
DIGIT mask = ~( ((DIGIT) 1) << (DIGIT_SIZE_b - 1 - inDigitIdx));
poly[digitIdx] = poly[digitIdx] & mask;
poly[digitIdx] = poly[digitIdx] | (( value & ((DIGIT) 1)) << (DIGIT_SIZE_b - 1 - inDigitIdx));
}
/* toggles (flips) the coefficient of the x^exponent term as the LSB of a digit */
static inline void gf2x_toggle_coeff(DIGIT poly[], unsigned int exponent) {
unsigned int straightIdx = (NUM_DIGITS_GF2X_ELEMENT * DIGIT_SIZE_b - 1) - exponent;
unsigned int digitIdx = straightIdx / DIGIT_SIZE_b;
unsigned int inDigitIdx = straightIdx % DIGIT_SIZE_b;
/* clear given coefficient */
DIGIT mask = ( ((DIGIT) 1) << (DIGIT_SIZE_b - 1 - inDigitIdx));
poly[digitIdx] = poly[digitIdx] ^ mask;
}
/* population count for an unsigned 64-bit integer
Source: Hacker's delight, p.66 */
static int popcount_uint64t(uint64_t x) {
x -= (x >> 1) & 0x5555555555555555;
x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333);
x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f;
return (int)((x * 0x0101010101010101) >> 56);
}
/* population count for a single polynomial */
static inline int population_count(DIGIT *poly) {
int ret = 0;
for (int i = NUM_DIGITS_GF2X_ELEMENT - 1; i >= 0; i--) {
ret += popcount_uint64t(poly[i]);
}
return ret;
}
static inline void gf2x_mod_add(DIGIT Res[], const DIGIT A[], const DIGIT B[]) {
gf2x_add(Res, A, B, NUM_DIGITS_GF2X_ELEMENT);
}
static inline int partition(POSITION_T arr[], int lo, int hi) {
POSITION_T x = arr[hi];
POSITION_T tmp;
int i = (lo - 1);
for (int j = lo; j <= hi - 1; j++) {
if (arr[j] <= x) {
i++;
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
tmp = arr[i + 1];
arr[i + 1] = arr[hi];
arr[hi] = tmp;
return i + 1;
}
static inline void quicksort_sparse(POSITION_T Res[]) {
int stack[DV * M];
int hi, lo, pivot, tos = -1;
stack[++tos] = 0;
stack[++tos] = (DV * M) - 1;
while (tos >= 0 ) {
hi = stack[tos--];
lo = stack[tos--];
pivot = partition(Res, lo, hi);
if ( (pivot - 1) > lo) {
stack[++tos] = lo;
stack[++tos] = pivot - 1;
}
if ( (pivot + 1) < hi) {
stack[++tos] = pivot + 1;
stack[++tos] = hi;
}
}
}
void PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mod_mul(DIGIT Res[], const DIGIT A[], const DIGIT B[]);
void PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_transpose_in_place(DIGIT A[]);
void PQCLEAN_LEDAKEMLT32_CLEAN_rand_circulant_sparse_block(POSITION_T *pos_ones, int countOnes, AES_XOF_struct *seed_expander_ctx);
void PQCLEAN_LEDAKEMLT32_CLEAN_rand_circulant_blocks_sequence(DIGIT *sequence, AES_XOF_struct *seed_expander_ctx);
void PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mod_add_sparse(int sizeR, POSITION_T Res[], int sizeA, const POSITION_T A[], int sizeB, const POSITION_T B[]);
void PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_transpose_in_place_sparse(int sizeA, POSITION_T A[]);
void PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mod_mul_sparse(size_t sizeR, POSITION_T Res[], size_t sizeA, const POSITION_T A[], size_t sizeB, const POSITION_T B[]);
void PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mod_mul_dense_to_sparse(DIGIT Res[], const DIGIT dense[], POSITION_T sparse[], unsigned int nPos);
void PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_tobytes(uint8_t *bytes, const DIGIT *poly);
int PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mod_inverse(DIGIT out[], const DIGIT in[]);
#endif

View File

@ -0,0 +1,56 @@
#include "api.h"
#include "niederreiter.h"
#include "randombytes.h"
#include "rng.h"
#include <string.h>
/* Generates a keypair - pk is the public key and sk is the secret key. */
int PQCLEAN_LEDAKEMLT32_CLEAN_crypto_kem_keypair(unsigned char *pk, unsigned char *sk) {
AES_XOF_struct niederreiter_keys_expander;
randombytes(((privateKeyNiederreiter_t *)sk)->prng_seed, TRNG_BYTE_LENGTH);
PQCLEAN_LEDAKEMLT32_CLEAN_seedexpander_from_trng(&niederreiter_keys_expander, ((privateKeyNiederreiter_t *)sk)->prng_seed);
PQCLEAN_LEDAKEMLT32_CLEAN_niederreiter_keygen((publicKeyNiederreiter_t *) pk, (privateKeyNiederreiter_t *) sk, &niederreiter_keys_expander);
return 0;
}
static void pack_error(uint8_t *error_bytes, const DIGIT *error_digits) {
size_t i;
for (i = 0; i < N0; i++) {
PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_tobytes(error_bytes + i * NUM_DIGITS_GF2X_ELEMENT * DIGIT_SIZE_B, error_digits + i * NUM_DIGITS_GF2X_ELEMENT);
}
}
/* Encrypt - pk is the public key, ct is a key encapsulation message
(ciphertext), ss is the shared secret.*/
int PQCLEAN_LEDAKEMLT32_CLEAN_crypto_kem_enc(unsigned char *ct, unsigned char *ss, const unsigned char *pk) {
AES_XOF_struct niederreiter_encap_key_expander;
unsigned char encapsulated_key_seed[TRNG_BYTE_LENGTH];
DIGIT error_vector[N0 * NUM_DIGITS_GF2X_ELEMENT];
uint8_t error_bytes[N0 * NUM_DIGITS_GF2X_ELEMENT * DIGIT_SIZE_B];
randombytes(encapsulated_key_seed, TRNG_BYTE_LENGTH);
PQCLEAN_LEDAKEMLT32_CLEAN_seedexpander_from_trng(&niederreiter_encap_key_expander, encapsulated_key_seed);
PQCLEAN_LEDAKEMLT32_CLEAN_rand_circulant_blocks_sequence(error_vector, &niederreiter_encap_key_expander);
pack_error(error_bytes, error_vector);
HASH_FUNCTION(ss, error_bytes, (N0 * NUM_DIGITS_GF2X_ELEMENT * DIGIT_SIZE_B));
PQCLEAN_LEDAKEMLT32_CLEAN_niederreiter_encrypt((DIGIT *) ct, (publicKeyNiederreiter_t *) pk, error_vector);
return 0;
}
/* Decrypt - ct is a key encapsulation message (ciphertext), sk is the private
key, ss is the shared secret */
int PQCLEAN_LEDAKEMLT32_CLEAN_crypto_kem_dec(unsigned char *ss, const unsigned char *ct, const unsigned char *sk) {
DIGIT decoded_error_vector[N0 * NUM_DIGITS_GF2X_ELEMENT];
uint8_t decoded_error_bytes[N0 * NUM_DIGITS_GF2X_ELEMENT * DIGIT_SIZE_B];
PQCLEAN_LEDAKEMLT32_CLEAN_niederreiter_decrypt(decoded_error_vector, (privateKeyNiederreiter_t *)sk, (DIGIT *)ct);
pack_error(decoded_error_bytes, decoded_error_vector);
HASH_FUNCTION(ss, decoded_error_bytes, (N0 * NUM_DIGITS_GF2X_ELEMENT * DIGIT_SIZE_B));
return 0;
}

View File

@ -0,0 +1,198 @@
#include "H_Q_matrices_generation.h"
#include "bf_decoding.h"
#include "dfr_test.h"
#include "gf2x_arith_mod_xPplusOne.h"
#include "niederreiter.h"
#include "qc_ldpc_parameters.h"
#include "rng.h"
#include <string.h>
void PQCLEAN_LEDAKEMLT32_CLEAN_niederreiter_keygen(publicKeyNiederreiter_t *pk, privateKeyNiederreiter_t *sk, AES_XOF_struct *keys_expander) {
// sequence of N0 circ block matrices (p x p): Hi
POSITION_T HPosOnes[N0][DV];
POSITION_T HtrPosOnes[N0][DV];
/* Sparse representation of the transposed circulant matrix H,
with weight DV. Each index contains the position of a '1' digit in the
corresponding Htr block */
/* Sparse representation of the matrix (Q).
A matrix containing the positions of the ones in the circulant
blocks of Q. Each row contains the position of the
ones of all the blocks of a row of Q as exponent+
P*block_position */
POSITION_T QPosOnes[N0][M];
/*Rejection-sample for a full L*/
POSITION_T LPosOnes[N0][DV * M];
int is_L_full = 0;
int isDFRok = 0;
sk->rejections = (int8_t) 0;
do {
PQCLEAN_LEDAKEMLT32_CLEAN_generateHPosOnes_HtrPosOnes(HPosOnes, HtrPosOnes, keys_expander);
PQCLEAN_LEDAKEMLT32_CLEAN_generateQsparse(QPosOnes, keys_expander);
for (int i = 0; i < N0; i++) {
for (int j = 0; j < DV * M; j++) {
LPosOnes[i][j] = INVALID_POS_VALUE;
}
}
POSITION_T auxPosOnes[DV * M];
unsigned char processedQOnes[N0] = {0};
for (int colQ = 0; colQ < N0; colQ++) {
for (int i = 0; i < N0; i++) {
PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mod_mul_sparse(DV * M, auxPosOnes,
DV, HPosOnes[i],
qBlockWeights[i][colQ], QPosOnes[i] + processedQOnes[i]);
PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mod_add_sparse(DV * M, LPosOnes[colQ],
DV * M, LPosOnes[colQ],
DV * M, auxPosOnes);
processedQOnes[i] += qBlockWeights[i][colQ];
}
}
is_L_full = 1;
for (int i = 0; i < N0; i++) {
is_L_full = is_L_full && (LPosOnes[i][DV * M - 1] != INVALID_POS_VALUE);
}
sk->rejections = sk->rejections + 1;
if (is_L_full) {
isDFRok = PQCLEAN_LEDAKEMLT32_CLEAN_DFR_test(LPosOnes);
}
} while (!is_L_full || !isDFRok);
sk->rejections = sk->rejections - 1;
DIGIT Ln0dense[NUM_DIGITS_GF2X_ELEMENT] = {0x00};
for (int j = 0; j < DV * M; j++) {
if (LPosOnes[N0 - 1][j] != INVALID_POS_VALUE) {
gf2x_set_coeff(Ln0dense, LPosOnes[N0 - 1][j], 1);
}
}
DIGIT Ln0Inv[NUM_DIGITS_GF2X_ELEMENT] = {0x00};
PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mod_inverse(Ln0Inv, Ln0dense);
for (int i = 0; i < N0 - 1; i++) {
PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mod_mul_dense_to_sparse(pk->Mtr + i * NUM_DIGITS_GF2X_ELEMENT,
Ln0Inv,
LPosOnes[i],
DV * M);
}
for (int i = 0; i < N0 - 1; i++) {
PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_transpose_in_place(pk->Mtr + i * NUM_DIGITS_GF2X_ELEMENT);
}
}
void PQCLEAN_LEDAKEMLT32_CLEAN_niederreiter_encrypt(DIGIT *syndrome, const publicKeyNiederreiter_t *pk, const DIGIT *err) {
int i;
DIGIT saux[NUM_DIGITS_GF2X_ELEMENT];
memset(syndrome, 0x00, NUM_DIGITS_GF2X_ELEMENT * DIGIT_SIZE_B);
for (i = 0; i < N0 - 1; i++) {
PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mod_mul(saux,
pk->Mtr + i * NUM_DIGITS_GF2X_ELEMENT,
err + i * NUM_DIGITS_GF2X_ELEMENT);
gf2x_mod_add(syndrome, syndrome, saux);
} // end for
gf2x_mod_add(syndrome, syndrome, err + (N0 - 1)*NUM_DIGITS_GF2X_ELEMENT);
}
int PQCLEAN_LEDAKEMLT32_CLEAN_niederreiter_decrypt(DIGIT *err, const privateKeyNiederreiter_t *sk, const DIGIT *syndrome) {
AES_XOF_struct niederreiter_decrypt_expander;
PQCLEAN_LEDAKEMLT32_CLEAN_seedexpander_from_trng(&niederreiter_decrypt_expander, sk->prng_seed);
// sequence of N0 circ block matrices (p x p):
POSITION_T HPosOnes[N0][DV];
POSITION_T HtrPosOnes[N0][DV];
POSITION_T QPosOnes[N0][M];
int rejections = sk->rejections;
POSITION_T LPosOnes[N0][DV * M];
do {
PQCLEAN_LEDAKEMLT32_CLEAN_generateHPosOnes_HtrPosOnes(HPosOnes, HtrPosOnes, &niederreiter_decrypt_expander);
PQCLEAN_LEDAKEMLT32_CLEAN_generateQsparse(QPosOnes, &niederreiter_decrypt_expander);
for (int i = 0; i < N0; i++) {
for (int j = 0; j < DV * M; j++) {
LPosOnes[i][j] = INVALID_POS_VALUE;
}
}
POSITION_T auxPosOnes[DV * M];
unsigned char processedQOnes[N0] = {0};
for (int colQ = 0; colQ < N0; colQ++) {
for (int i = 0; i < N0; i++) {
PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mod_mul_sparse(DV * M, auxPosOnes,
DV, HPosOnes[i],
qBlockWeights[i][colQ], QPosOnes[i] + processedQOnes[i]);
PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mod_add_sparse(DV * M, LPosOnes[colQ],
DV * M, LPosOnes[colQ],
DV * M, auxPosOnes);
processedQOnes[i] += qBlockWeights[i][colQ];
}
}
rejections--;
} while (rejections >= 0);
POSITION_T QtrPosOnes[N0][M];
unsigned transposed_ones_idx[N0] = {0x00};
for (unsigned source_row_idx = 0; source_row_idx < N0 ; source_row_idx++) {
int currQoneIdx = 0; // position in the column of QtrPosOnes[][...]
int endQblockIdx = 0;
for (int blockIdx = 0; blockIdx < N0; blockIdx++) {
endQblockIdx += qBlockWeights[source_row_idx][blockIdx];
for (; currQoneIdx < endQblockIdx; currQoneIdx++) {
QtrPosOnes[blockIdx][transposed_ones_idx[blockIdx]] = (P -
QPosOnes[source_row_idx][currQoneIdx]) % P;
transposed_ones_idx[blockIdx]++;
}
}
}
POSITION_T auxSparse[DV * M];
POSITION_T Ln0trSparse[DV * M];
for (int i = 0; i < DV * M; i++) {
Ln0trSparse[i] = INVALID_POS_VALUE;
auxSparse[i] = INVALID_POS_VALUE;
}
for (int i = 0; i < N0; i++) {
PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mod_mul_sparse(DV * M, auxSparse,
DV, HPosOnes[i],
qBlockWeights[i][N0 - 1], &QPosOnes[i][ M - qBlockWeights[i][N0 - 1]]);
PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mod_add_sparse(DV * M, Ln0trSparse,
DV * M, Ln0trSparse,
DV * M, auxSparse);
}
PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_transpose_in_place_sparse(DV * M, Ln0trSparse);
DIGIT privateSyndrome[NUM_DIGITS_GF2X_ELEMENT];
PQCLEAN_LEDAKEMLT32_CLEAN_gf2x_mod_mul_dense_to_sparse(privateSyndrome, syndrome, Ln0trSparse, DV * M);
/* prepare mockup error vector in case a decoding failure occurs */
DIGIT mockup_error_vector[N0 * NUM_DIGITS_GF2X_ELEMENT];
memset(mockup_error_vector, 0x00, N0 * NUM_DIGITS_GF2X_ELEMENT * DIGIT_SIZE_B);
memcpy(mockup_error_vector, syndrome, NUM_DIGITS_GF2X_ELEMENT * DIGIT_SIZE_B);
PQCLEAN_LEDAKEMLT32_CLEAN_seedexpander(&niederreiter_decrypt_expander,
((unsigned char *) mockup_error_vector) + (NUM_DIGITS_GF2X_ELEMENT * DIGIT_SIZE_B),
TRNG_BYTE_LENGTH);
int decryptOk = 0;
memset(err, 0x00, N0 * NUM_DIGITS_GF2X_ELEMENT * DIGIT_SIZE_B);
decryptOk = PQCLEAN_LEDAKEMLT32_CLEAN_bf_decoding(err, (const POSITION_T (*)[DV]) HtrPosOnes,
(const POSITION_T (*)[M]) QtrPosOnes, privateSyndrome);
int err_weight = 0;
for (int i = 0 ; i < N0; i++) {
err_weight += population_count(err + (NUM_DIGITS_GF2X_ELEMENT * i));
}
decryptOk = decryptOk && (err_weight == NUM_ERRORS_T);
if (!decryptOk) { // TODO: not constant time, replace with cmov?
memcpy(err, mockup_error_vector, N0 * NUM_DIGITS_GF2X_ELEMENT * DIGIT_SIZE_B);
}
return decryptOk;
}

View File

@ -0,0 +1,28 @@
#ifndef NIEDERREITER_H
#define NIEDERREITER_H
#include "gf2x_arith_mod_xPplusOne.h"
#include "qc_ldpc_parameters.h"
#include "rng.h"
typedef struct {
/* raw entropy extracted from TRNG, will be deterministically expanded into
* H and Q during decryption */
unsigned char prng_seed[TRNG_BYTE_LENGTH];
int8_t rejections;
} privateKeyNiederreiter_t;
typedef struct {
DIGIT Mtr[(N0 - 1)*NUM_DIGITS_GF2X_ELEMENT];
// Dense representation of the matrix M=Ln0*L,
// An array including a sequence of (N0-1) gf2x elements;
// each gf2x element is stored as a binary polynomial(mod x^P+1)
// with P coefficients.
} publicKeyNiederreiter_t;
void PQCLEAN_LEDAKEMLT32_CLEAN_niederreiter_keygen(publicKeyNiederreiter_t *pk, privateKeyNiederreiter_t *sk, AES_XOF_struct *keys_expander);
void PQCLEAN_LEDAKEMLT32_CLEAN_niederreiter_encrypt(DIGIT syndrome[], const publicKeyNiederreiter_t *pk, const DIGIT *err);
int PQCLEAN_LEDAKEMLT32_CLEAN_niederreiter_decrypt(DIGIT *err, const privateKeyNiederreiter_t *sk, const DIGIT *syndrome);
#endif

View File

@ -0,0 +1,27 @@
#ifndef QC_LDPC_PARAMETERS_H
#define QC_LDPC_PARAMETERS_H
#include "fips202.h"
#define TRNG_BYTE_LENGTH (32)
#define HASH_BYTE_LENGTH (48)
#define HASH_FUNCTION sha3_384
#define N0 (2)
#define P (96221) // modulus(x) = x^P-1
#define DV (11) // odd number
#define M (11)
#define M0 (6)
#define M1 (5)
#define NUM_ERRORS_T (199)
// Derived parameters, they are useful for QC-LDPC algorithms
#define HASH_BIT_LENGTH (HASH_BYTE_LENGTH << 3)
#define K ((N0-1)*P)
#define N (N0*P)
#define DC (N0*DV)
#define Q_BLOCK_WEIGHTS {{M0,M1},{M1,M0}}
static const unsigned char qBlockWeights[N0][N0] = Q_BLOCK_WEIGHTS;
#endif

View File

@ -0,0 +1,113 @@
#include "rng.h"
#include <string.h> // void *memset(void *s, int c, size_t n);
#include "aes.h"
#include "qc_ldpc_parameters.h"
/*
seedexpander_init()
ctx - stores the current state of an instance of the seed expander
seed - a 32 byte random value
diversifier - an 8 byte diversifier
maxlen - maximum number of bytes (less than 2**32) generated under this seed and diversifier
*/
static int seedexpander_init(AES_XOF_struct *ctx,
unsigned char *seed,
unsigned char *diversifier,
uint64_t maxlen) {
if ( maxlen >= 0x100000000 ) {
return RNG_BAD_MAXLEN;
}
ctx->length_remaining = maxlen;
memset(ctx->key, 0, 32);
int max_accessible_seed_len = TRNG_BYTE_LENGTH < 32 ? 32 : TRNG_BYTE_LENGTH;
memcpy(ctx->key, seed, max_accessible_seed_len);
memcpy(ctx->ctr, diversifier, 8);
ctx->ctr[11] = maxlen % 256;
maxlen >>= 8;
ctx->ctr[10] = maxlen % 256;
maxlen >>= 8;
ctx->ctr[9] = maxlen % 256;
maxlen >>= 8;
ctx->ctr[8] = maxlen % 256;
memset(ctx->ctr + 12, 0x00, 4);
ctx->buffer_pos = 16;
memset(ctx->buffer, 0x00, 16);
return RNG_SUCCESS;
}
void PQCLEAN_LEDAKEMLT32_CLEAN_seedexpander_from_trng(AES_XOF_struct *ctx,
const unsigned char *trng_entropy
/* TRNG_BYTE_LENGTH wide buffer */) {
/*the NIST seedexpander will however access 32B from this buffer */
unsigned int prng_buffer_size = TRNG_BYTE_LENGTH < 32 ? 32 : TRNG_BYTE_LENGTH;
unsigned char prng_buffer[TRNG_BYTE_LENGTH < 32 ? 32 : TRNG_BYTE_LENGTH] = { 0x00 };
unsigned char diversifier[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
memcpy(prng_buffer,
trng_entropy,
TRNG_BYTE_LENGTH < prng_buffer_size ? TRNG_BYTE_LENGTH : prng_buffer_size);
/* the required seed expansion will be quite small, set the max number of
* bytes conservatively to 10 MiB*/
seedexpander_init(ctx, prng_buffer, diversifier, 10 * 1024 * 1024);
}
/*
seedexpander()
ctx - stores the current state of an instance of the seed expander
x - returns the XOF data
xlen - number of bytes to return
*/
int PQCLEAN_LEDAKEMLT32_CLEAN_seedexpander(AES_XOF_struct *ctx, unsigned char *x, size_t xlen) {
uint32_t offset;
aes256ctx ctx256;
if ( x == NULL ) {
return RNG_BAD_OUTBUF;
}
if ( xlen >= ctx->length_remaining ) {
return RNG_BAD_REQ_LEN;
}
aes256_keyexp(&ctx256, ctx->key);
ctx->length_remaining -= xlen;
offset = 0;
while ( xlen > 0 ) {
if ( xlen <= (16 - ctx->buffer_pos) ) { // buffer has what we need
memcpy(x + offset, ctx->buffer + ctx->buffer_pos, xlen);
ctx->buffer_pos += xlen;
return RNG_SUCCESS;
}
// take what's in the buffer
memcpy(x + offset, ctx->buffer + ctx->buffer_pos, 16 - ctx->buffer_pos);
xlen -= 16 - ctx->buffer_pos;
offset += 16 - ctx->buffer_pos;
aes256_ecb(ctx->buffer, ctx->ctr, 16 / AES_BLOCKBYTES, &ctx256);
ctx->buffer_pos = 0;
//increment the counter
for (int i = 15; i >= 12; i--) {
if ( ctx->ctr[i] == 0xff ) {
ctx->ctr[i] = 0x00;
} else {
ctx->ctr[i]++;
break;
}
}
}
return RNG_SUCCESS;
}

View File

@ -0,0 +1,23 @@
#ifndef RNG_H
#define RNG_H
#include <stddef.h>
#include <stdint.h>
#define RNG_SUCCESS ( 0)
#define RNG_BAD_MAXLEN (-1)
#define RNG_BAD_OUTBUF (-2)
#define RNG_BAD_REQ_LEN (-3)
typedef struct {
unsigned char buffer[16];
unsigned int buffer_pos;
uint64_t length_remaining;
unsigned char key[32];
unsigned char ctr[16];
} AES_XOF_struct;
int PQCLEAN_LEDAKEMLT32_CLEAN_seedexpander(AES_XOF_struct *ctx, unsigned char *x, size_t xlen);
void PQCLEAN_LEDAKEMLT32_CLEAN_seedexpander_from_trng(AES_XOF_struct *ctx, const unsigned char *trng_entropy);
#endif