/**1* Implementation of the Lyra2 Password Hashing Scheme (PHS).2*3* Author: The Lyra PHC team (http://www.lyra-kdf.net/) -- 2014.4*5* This software is hereby placed in the public domain.6*7* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS8* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED9* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE10* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE11* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR12* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF13* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR14* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,15* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE16* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,17* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.18*/19#include <stdio.h>20#include <stdlib.h>21#include <string.h>22#include <time.h>2324#include "Lyra2.h"25#include "Sponge.h"2627/**28* Executes Lyra2 based on the G function from Blake2b. This version supports salts and passwords29* whose combined length is smaller than the size of the memory matrix, (i.e., (nRows x nCols x b) bits,30* where "b" is the underlying sponge's bitrate). In this implementation, the "basil" is composed by all31* integer parameters (treated as type "unsigned int") in the order they are provided, plus the value32* of nCols, (i.e., basil = kLen || pwdlen || saltlen || timeCost || nRows || nCols).33*34* @param K The derived key to be output by the algorithm35* @param kLen Desired key length36* @param pwd User password37* @param pwdlen Password length38* @param salt Salt39* @param saltlen Salt length40* @param timeCost Parameter to determine the processing time (T)41* @param nRows Number or rows of the memory matrix (R)42* @param nCols Number of columns of the memory matrix (C)43*44* @return 0 if the key is generated correctly; -1 if there is an error (usually due to lack of memory for allocation)45*/46int LYRA2(void *K, int64_t kLen, const void *pwd, int32_t pwdlen, const void *salt, int32_t saltlen, int64_t timeCost, const int16_t nRows, const int16_t nCols)47{48//============================= Basic variables ============================//49int64_t row = 2; //index of row to be processed50int64_t prev = 1; //index of prev (last row ever computed/modified)51int64_t rowa = 0; //index of row* (a previous row, deterministically picked during Setup and randomly picked while Wandering)52int64_t tau; //Time Loop iterator53int64_t step = 1; //Visitation step (used during Setup and Wandering phases)54int64_t window = 2; //Visitation window (used to define which rows can be revisited during Setup)55int64_t gap = 1; //Modifier to the step, assuming the values 1 or -156int64_t i; //auxiliary iteration counter57int64_t v64; // 64bit var for memcpy58//==========================================================================/5960//========== Initializing the Memory Matrix and pointers to it =============//61//Tries to allocate enough space for the whole memory matrix6263const int64_t ROW_LEN_INT64 = BLOCK_LEN_INT64 * nCols;64const int64_t ROW_LEN_BYTES = ROW_LEN_INT64 * 8;65// for Lyra2REv2, nCols = 4, v1 was using 866const int64_t BLOCK_LEN = (nCols == 4) ? BLOCK_LEN_BLAKE2_SAFE_INT64 : BLOCK_LEN_BLAKE2_SAFE_BYTES;6768i = (int64_t)ROW_LEN_BYTES * nRows;69uint64_t *wholeMatrix = malloc(i);70if (wholeMatrix == NULL) {71return -1;72}73memset(wholeMatrix, 0, i);7475//Allocates pointers to each row of the matrix76uint64_t **memMatrix = malloc(sizeof(uint64_t*) * nRows);77if (memMatrix == NULL) {78return -1;79}80//Places the pointers in the correct positions81uint64_t *ptrWord = wholeMatrix;82for (i = 0; i < nRows; i++) {83memMatrix[i] = ptrWord;84ptrWord += ROW_LEN_INT64;85}86//==========================================================================/8788//============= Getting the password + salt + basil padded with 10*1 ===============//89//OBS.:The memory matrix will temporarily hold the password: not for saving memory,90//but this ensures that the password copied locally will be overwritten as soon as possible9192//First, we clean enough blocks for the password, salt, basil and padding93int64_t nBlocksInput = ((saltlen + pwdlen + 6 * sizeof(uint64_t)) / BLOCK_LEN_BLAKE2_SAFE_BYTES) + 1;9495byte *ptrByte = (byte*) wholeMatrix;9697//Prepends the password98memcpy(ptrByte, pwd, pwdlen);99ptrByte += pwdlen;100101//Concatenates the salt102memcpy(ptrByte, salt, saltlen);103ptrByte += saltlen;104105memset(ptrByte, 0, nBlocksInput * BLOCK_LEN_BLAKE2_SAFE_BYTES - (saltlen + pwdlen));106107//Concatenates the basil: every integer passed as parameter, in the order they are provided by the interface108memcpy(ptrByte, &kLen, sizeof(int64_t));109ptrByte += sizeof(uint64_t);110v64 = pwdlen;111memcpy(ptrByte, &v64, sizeof(int64_t));112ptrByte += sizeof(uint64_t);113v64 = saltlen;114memcpy(ptrByte, &v64, sizeof(int64_t));115ptrByte += sizeof(uint64_t);116v64 = timeCost;117memcpy(ptrByte, &v64, sizeof(int64_t));118ptrByte += sizeof(uint64_t);119v64 = nRows;120memcpy(ptrByte, &v64, sizeof(int64_t));121ptrByte += sizeof(uint64_t);122v64 = nCols;123memcpy(ptrByte, &v64, sizeof(int64_t));124ptrByte += sizeof(uint64_t);125126//Now comes the padding127*ptrByte = 0x80; //first byte of padding: right after the password128ptrByte = (byte*) wholeMatrix; //resets the pointer to the start of the memory matrix129ptrByte += nBlocksInput * BLOCK_LEN_BLAKE2_SAFE_BYTES - 1; //sets the pointer to the correct position: end of incomplete block130*ptrByte ^= 0x01; //last byte of padding: at the end of the last incomplete block131//==========================================================================/132133//======================= Initializing the Sponge State ====================//134//Sponge state: 16 uint64_t, BLOCK_LEN_INT64 words of them for the bitrate (b) and the remainder for the capacity (c)135uint64_t state[16];136initState(state);137//==========================================================================/138139//================================ Setup Phase =============================//140//Absorbing salt, password and basil: this is the only place in which the block length is hard-coded to 512 bits141ptrWord = wholeMatrix;142for (i = 0; i < nBlocksInput; i++) {143absorbBlockBlake2Safe(state, ptrWord); //absorbs each block of pad(pwd || salt || basil)144ptrWord += BLOCK_LEN; //goes to next block of pad(pwd || salt || basil)145}146147//Initializes M[0] and M[1]148reducedSqueezeRow0(state, memMatrix[0], nCols); //The locally copied password is most likely overwritten here149150reducedDuplexRow1(state, memMatrix[0], memMatrix[1], nCols);151152do {153//M[row] = rand; //M[row*] = M[row*] XOR rotW(rand)154155reducedDuplexRowSetup(state, memMatrix[prev], memMatrix[rowa], memMatrix[row], nCols);156157//updates the value of row* (deterministically picked during Setup))158rowa = (rowa + step) & (window - 1);159//update prev: it now points to the last row ever computed160prev = row;161//updates row: goes to the next row to be computed162row++;163164//Checks if all rows in the window where visited.165if (rowa == 0) {166step = window + gap; //changes the step: approximately doubles its value167window *= 2; //doubles the size of the re-visitation window168gap = -gap; //inverts the modifier to the step169}170171} while (row < nRows);172//==========================================================================/173174//============================ Wandering Phase =============================//175row = 0; //Resets the visitation to the first row of the memory matrix176for (tau = 1; tau <= timeCost; tau++) {177//Step is approximately half the number of all rows of the memory matrix for an odd tau; otherwise, it is -1178step = (tau % 2 == 0) ? -1 : nRows / 2 - 1;179do {180//Selects a pseudorandom index row*181//------------------------------------------------------------------------------------------182rowa = state[0] & (unsigned int)(nRows-1); //(USE THIS IF nRows IS A POWER OF 2)183//rowa = state[0] % nRows; //(USE THIS FOR THE "GENERIC" CASE)184//------------------------------------------------------------------------------------------185186//Performs a reduced-round duplexing operation over M[row*] XOR M[prev], updating both M[row*] and M[row]187reducedDuplexRow(state, memMatrix[prev], memMatrix[rowa], memMatrix[row], nCols);188189//update prev: it now points to the last row ever computed190prev = row;191192//updates row: goes to the next row to be computed193//------------------------------------------------------------------------------------------194row = (row + step) & (unsigned int)(nRows-1); //(USE THIS IF nRows IS A POWER OF 2)195//row = (row + step) % nRows; //(USE THIS FOR THE "GENERIC" CASE)196//------------------------------------------------------------------------------------------197198} while (row != 0);199}200201//============================ Wrap-up Phase ===============================//202//Absorbs the last block of the memory matrix203absorbBlock(state, memMatrix[rowa]);204205//Squeezes the key206squeeze(state, K, (unsigned int) kLen);207208//========================= Freeing the memory =============================//209free(memMatrix);210free(wholeMatrix);211212return 0;213}214215int LYRA2_3(void *K, int64_t kLen, const void *pwd, int32_t pwdlen, const void *salt, int32_t saltlen, int64_t timeCost, const int16_t nRows, const int16_t nCols)216{217//============================= Basic variables ============================//218int64_t row = 2; //index of row to be processed219int64_t prev = 1; //index of prev (last row ever computed/modified)220int64_t rowa = 0; //index of row* (a previous row, deterministically picked during Setup and randomly picked while Wandering)221int64_t tau; //Time Loop iterator222int64_t step = 1; //Visitation step (used during Setup and Wandering phases)223int64_t window = 2; //Visitation window (used to define which rows can be revisited during Setup)224int64_t gap = 1; //Modifier to the step, assuming the values 1 or -1225int64_t i; //auxiliary iteration counter226int64_t v64; // 64bit var for memcpy227uint64_t instance = 0;228//==========================================================================/229230//========== Initializing the Memory Matrix and pointers to it =============//231//Tries to allocate enough space for the whole memory matrix232233const int64_t ROW_LEN_INT64 = BLOCK_LEN_INT64 * nCols;234const int64_t ROW_LEN_BYTES = ROW_LEN_INT64 * 8;235const int64_t BLOCK_LEN = BLOCK_LEN_BLAKE2_SAFE_INT64;236237size_t sz = (size_t)ROW_LEN_BYTES * nRows;238uint64_t *wholeMatrix = malloc(sz);239if (wholeMatrix == NULL) {240return -1;241}242memset(wholeMatrix, 0, sz);243244//Allocates pointers to each row of the matrix245uint64_t **memMatrix = malloc(sizeof(uint64_t*) * nRows);246if (memMatrix == NULL) {247return -1;248}249//Places the pointers in the correct positions250uint64_t *ptrWord = wholeMatrix;251for (i = 0; i < nRows; i++) {252memMatrix[i] = ptrWord;253ptrWord += ROW_LEN_INT64;254}255//==========================================================================/256257//============= Getting the password + salt + basil padded with 10*1 ===============//258//OBS.:The memory matrix will temporarily hold the password: not for saving memory,259//but this ensures that the password copied locally will be overwritten as soon as possible260261//First, we clean enough blocks for the password, salt, basil and padding262int64_t nBlocksInput = ((saltlen + pwdlen + 6 * sizeof(uint64_t)) / BLOCK_LEN_BLAKE2_SAFE_BYTES) + 1;263264byte *ptrByte = (byte*) wholeMatrix;265266//Prepends the password267memcpy(ptrByte, pwd, pwdlen);268ptrByte += pwdlen;269270//Concatenates the salt271memcpy(ptrByte, salt, saltlen);272ptrByte += saltlen;273274memset(ptrByte, 0, (size_t) (nBlocksInput * BLOCK_LEN_BLAKE2_SAFE_BYTES - (saltlen + pwdlen)));275276//Concatenates the basil: every integer passed as parameter, in the order they are provided by the interface277memcpy(ptrByte, &kLen, sizeof(int64_t));278ptrByte += sizeof(uint64_t);279v64 = pwdlen;280memcpy(ptrByte, &v64, sizeof(int64_t));281ptrByte += sizeof(uint64_t);282v64 = saltlen;283memcpy(ptrByte, &v64, sizeof(int64_t));284ptrByte += sizeof(uint64_t);285v64 = timeCost;286memcpy(ptrByte, &v64, sizeof(int64_t));287ptrByte += sizeof(uint64_t);288v64 = nRows;289memcpy(ptrByte, &v64, sizeof(int64_t));290ptrByte += sizeof(uint64_t);291v64 = nCols;292memcpy(ptrByte, &v64, sizeof(int64_t));293ptrByte += sizeof(uint64_t);294295//Now comes the padding296*ptrByte = 0x80; //first byte of padding: right after the password297ptrByte = (byte*) wholeMatrix; //resets the pointer to the start of the memory matrix298ptrByte += nBlocksInput * BLOCK_LEN_BLAKE2_SAFE_BYTES - 1; //sets the pointer to the correct position: end of incomplete block299*ptrByte ^= 0x01; //last byte of padding: at the end of the last incomplete block300//==========================================================================/301302//======================= Initializing the Sponge State ====================//303//Sponge state: 16 uint64_t, BLOCK_LEN_INT64 words of them for the bitrate (b) and the remainder for the capacity (c)304uint64_t state[16];305initState(state);306//==========================================================================/307308//================================ Setup Phase =============================//309//Absorbing salt, password and basil: this is the only place in which the block length is hard-coded to 512 bits310ptrWord = wholeMatrix;311for (i = 0; i < nBlocksInput; i++) {312absorbBlockBlake2Safe(state, ptrWord); //absorbs each block of pad(pwd || salt || basil)313ptrWord += BLOCK_LEN; //goes to next block of pad(pwd || salt || basil)314}315316//Initializes M[0] and M[1]317reducedSqueezeRow0(state, memMatrix[0], nCols); //The locally copied password is most likely overwritten here318319reducedDuplexRow1(state, memMatrix[0], memMatrix[1], nCols);320321do {322//M[row] = rand; //M[row*] = M[row*] XOR rotW(rand)323324reducedDuplexRowSetup(state, memMatrix[prev], memMatrix[rowa], memMatrix[row], nCols);325326//updates the value of row* (deterministically picked during Setup))327rowa = (rowa + step) & (window - 1);328//update prev: it now points to the last row ever computed329prev = row;330//updates row: goes to the next row to be computed331row++;332333//Checks if all rows in the window where visited.334if (rowa == 0) {335step = window + gap; //changes the step: approximately doubles its value336window *= 2; //doubles the size of the re-visitation window337gap = -gap; //inverts the modifier to the step338}339340} while (row < nRows);341//==========================================================================/342343//============================ Wandering Phase =============================//344row = 0; //Resets the visitation to the first row of the memory matrix345for (tau = 1; tau <= timeCost; tau++) {346//Step is approximately half the number of all rows of the memory matrix for an odd tau; otherwise, it is -1347step = ((tau & 1) == 0) ? -1 : (nRows >> 1) - 1;348do {349//Selects a pseudorandom index row*350//------------------------------------------------------------------------------------------351instance = state[instance & 0xF];352rowa = state[instance & 0xF] & (unsigned int)(nRows-1);353354//rowa = state[0] & (unsigned int)(nRows-1); //(USE THIS IF nRows IS A POWER OF 2)355//rowa = state[0] % nRows; //(USE THIS FOR THE "GENERIC" CASE)356//------------------------------------------------------------------------------------------357358//Performs a reduced-round duplexing operation over M[row*] XOR M[prev], updating both M[row*] and M[row]359reducedDuplexRow(state, memMatrix[prev], memMatrix[rowa], memMatrix[row], nCols);360361//update prev: it now points to the last row ever computed362prev = row;363364//updates row: goes to the next row to be computed365//------------------------------------------------------------------------------------------366row = (row + step) & (unsigned int)(nRows-1); //(USE THIS IF nRows IS A POWER OF 2)367//row = (row + step) % nRows; //(USE THIS FOR THE "GENERIC" CASE)368//------------------------------------------------------------------------------------------369370} while (row != 0);371}372373//============================ Wrap-up Phase ===============================//374//Absorbs the last block of the memory matrix375absorbBlock(state, memMatrix[rowa]);376377//Squeezes the key378squeeze(state, K, (unsigned int) kLen);379380//========================= Freeing the memory =============================//381free(memMatrix);382free(wholeMatrix);383384return 0;385}386387388