Path: blob/master/libs/tomcrypt/src/encauth/gcm/gcm_init.c
5972 views
/* LibTomCrypt, modular cryptographic library -- Tom St Denis1*2* LibTomCrypt is a library that provides various cryptographic3* algorithms in a highly modular and flexible manner.4*5* The library is free for all purposes without any express6* guarantee it works.7*/89/**10@file gcm_init.c11GCM implementation, initialize state, by Tom St Denis12*/13#include "tomcrypt.h"1415#ifdef LTC_GCM_MODE1617/**18Initialize a GCM state19@param gcm The GCM state to initialize20@param cipher The index of the cipher to use21@param key The secret key22@param keylen The length of the secret key23@return CRYPT_OK on success24*/25int gcm_init(gcm_state *gcm, int cipher,26const unsigned char *key, int keylen)27{28int err;29unsigned char B[16];30#ifdef LTC_GCM_TABLES31int x, y, z, t;32#endif3334LTC_ARGCHK(gcm != NULL);35LTC_ARGCHK(key != NULL);3637#ifdef LTC_FAST38if (16 % sizeof(LTC_FAST_TYPE)) {39return CRYPT_INVALID_ARG;40}41#endif4243/* is cipher valid? */44if ((err = cipher_is_valid(cipher)) != CRYPT_OK) {45return err;46}47if (cipher_descriptor[cipher].block_length != 16) {48return CRYPT_INVALID_CIPHER;49}5051/* schedule key */52if ((err = cipher_descriptor[cipher].setup(key, keylen, 0, &gcm->K)) != CRYPT_OK) {53return err;54}5556/* H = E(0) */57zeromem(B, 16);58if ((err = cipher_descriptor[cipher].ecb_encrypt(B, gcm->H, &gcm->K)) != CRYPT_OK) {59return err;60}6162/* setup state */63zeromem(gcm->buf, sizeof(gcm->buf));64zeromem(gcm->X, sizeof(gcm->X));65gcm->cipher = cipher;66gcm->mode = LTC_GCM_MODE_IV;67gcm->ivmode = 0;68gcm->buflen = 0;69gcm->totlen = 0;70gcm->pttotlen = 0;7172#ifdef LTC_GCM_TABLES73/* setup tables */7475/* generate the first table as it has no shifting (from which we make the other tables) */76zeromem(B, 16);77for (y = 0; y < 256; y++) {78B[0] = y;79gcm_gf_mult(gcm->H, B, &gcm->PC[0][y][0]);80}8182/* now generate the rest of the tables based the previous table */83for (x = 1; x < 16; x++) {84for (y = 0; y < 256; y++) {85/* now shift it right by 8 bits */86t = gcm->PC[x-1][y][15];87for (z = 15; z > 0; z--) {88gcm->PC[x][y][z] = gcm->PC[x-1][y][z-1];89}90gcm->PC[x][y][0] = gcm_shift_table[t<<1];91gcm->PC[x][y][1] ^= gcm_shift_table[(t<<1)+1];92}93}9495#endif9697return CRYPT_OK;98}99100#endif101102103