void AES_GCM_DECRYPT(octet *K,octet *IV,octet *H,octet *C,octet *P,octet *T)
{
	gcm g;
	gcm_init(&g,K->len,K->val,IV->len,IV->val);
	gcm_add_header(&g,H->val,H->len);
	gcm_add_cipher(&g,GCM_DECRYPTING,P->val,C->len,C->val);
	P->len=C->len;
	gcm_finish(&g,T->val); 
	T->len=16;
}
Пример #2
0
ret_code_t pm_init(void)
{
    ret_code_t err_code;

    err_code = pdb_register(pdb_evt_handler);
    if (err_code != NRF_SUCCESS)
    {
        if (err_code != NRF_ERROR_INVALID_STATE)
        {
            err_code = NRF_ERROR_INTERNAL;
        }
        return err_code;
    }

    err_code = sm_register(sm_evt_handler);
    if (err_code != NRF_SUCCESS)
    {
        return NRF_ERROR_INTERNAL;
    }

    err_code = gcm_init(gcm_evt_handler);
    if (err_code != NRF_SUCCESS)
    {
        return NRF_ERROR_INTERNAL;
    }

    err_code = im_register(im_evt_handler);
    if (err_code != NRF_SUCCESS)
    {
        return NRF_ERROR_INTERNAL;
    }

    m_pm.pairing_flag_id = ble_conn_state_user_flag_acquire();
    if (m_pm.pairing_flag_id == BLE_CONN_STATE_USER_FLAG_INVALID)
    {
        return NRF_ERROR_INTERNAL;
    }

    m_pm.bonding_flag_id = ble_conn_state_user_flag_acquire();
    if (m_pm.bonding_flag_id == BLE_CONN_STATE_USER_FLAG_INVALID)
    {
        return NRF_ERROR_INTERNAL;
    }

    m_pm.initialized = true;

    return NRF_SUCCESS;
}
/**
 * @Brief AES-GCM encrypt and tag buffer
 *
 * @param[in]	key							Encryption key
 * @param[in]	keyLength					Key buffer length, in bytes, must be 16,24 or 32
 * @param[in]	plainText					Buffer to be encrypted
 * @param[in]	plainTextLength				Length in bytes of buffer to be encrypted
 * @param[in]	authenticatedData			Buffer holding additional data to be used in tag computation
 * @param[in]	authenticatedDataLength		Additional data length in bytes
 * @param[in]	initializationVector		Buffer holding the initialisation vector
 * @param[in]	initializationVectorLength	Initialisation vector length in bytes
 * @param[out]	tag							Buffer holding the generated tag
 * @param[in]	tagLength					Requested length for the generated tag
 * @param[out]	output						Buffer holding the output, shall be at least the length of plainText buffer
 */
int32_t bctbx_aes_gcm_encrypt_and_tag(const uint8_t *key, size_t keyLength,
		const uint8_t *plainText, size_t plainTextLength,
		const uint8_t *authenticatedData, size_t authenticatedDataLength,
		const uint8_t *initializationVector, size_t initializationVectorLength,
		uint8_t *tag, size_t tagLength,
		uint8_t *output) {
	gcm_context gcmContext;
	int ret;

	ret = gcm_init(&gcmContext, key, keyLength*8);
	if (ret != 0) return ret;

	ret = gcm_crypt_and_tag(&gcmContext, GCM_ENCRYPT, plainTextLength, initializationVector, initializationVectorLength, authenticatedData, authenticatedDataLength, plainText, output, tagLength, tag);

	return ret;
}
/**
 * @Brief AES-GCM decrypt, compute authentication tag and compare it to the one provided
 *
 * @param[in]	key							Encryption key
 * @param[in]	keyLength					Key buffer length, in bytes, must be 16,24 or 32
 * @param[in]	cipherText					Buffer to be decrypted
 * @param[in]	cipherTextLength			Length in bytes of buffer to be decrypted
 * @param[in]	authenticatedData			Buffer holding additional data to be used in auth tag computation
 * @param[in]	authenticatedDataLength		Additional data length in bytes
 * @param[in]	initializationVector		Buffer holding the initialisation vector
 * @param[in]	initializationVectorLength	Initialisation vector length in bytes
 * @param[in]	tag							Buffer holding the authentication tag
 * @param[in]	tagLength					Length in bytes for the authentication tag
 * @param[out]	output						Buffer holding the output, shall be at least the length of cipherText buffer
 *
 * @return 0 on succes, BCTBX_ERROR_AUTHENTICATION_FAILED if tag doesn't match or polarssl error code
 */
int32_t bctbx_aes_gcm_decrypt_and_auth(const uint8_t *key, size_t keyLength,
		const uint8_t *cipherText, size_t cipherTextLength,
		const uint8_t *authenticatedData, size_t authenticatedDataLength,
		const uint8_t *initializationVector, size_t initializationVectorLength,
		const uint8_t *tag, size_t tagLength,
		uint8_t *output) {
	gcm_context gcmContext;
	int ret;

	ret = gcm_init(&gcmContext, key, keyLength*8);
	if (ret != 0) return ret;

	ret = gcm_auth_decrypt(&gcmContext, cipherTextLength, initializationVector, initializationVectorLength, authenticatedData, authenticatedDataLength, tag, tagLength, cipherText, output);

	if (ret == POLARSSL_ERR_GCM_AUTH_FAILED) {
		return BCTBX_ERROR_AUTHENTICATION_FAILED;
	}

	return ret;
}
/*! \brief Decrypt data using AES GCM
 *
 *  AES is run as a block cypher in the GCM  mode of operation. The key size is 128 bits.
 *  This function will decrypt any data length.
 *
 *  @param  key           128 bit secret key
 *  @param  IV            96 bit initialization vector
 *  @param  header        Additional authenticated data (AAD). This data is authenticated, but not decrypted.
 *  @param  ciphertext    Encrypted data.
 *  @return plaintext     Decrypted data. It is the same length as the ciphertext.
 *  @return tag           128 bit authentication tag.
 *  @return rtn           Returns 0 if successful or else an error code
 */
AESGCM_EXPORT int aesGcmDecrypt(char* key, char* IV, char* header, int headerLength,
                                char* ciphertext, int ciphertextLength, char* plaintext,
                                char* tag)
{
    gcm g;
    int keyLength=AS;
    int tagLength=AS;
    gcm_init(&g,keyLength,key,IVLength,IV);

    if(!gcm_add_header(&g,header,headerLength))
    {
        return AES_INIT_ERROR;
    }

    if(!gcm_add_cipher(&g,GCM_DECRYPTING,plaintext,ciphertextLength,ciphertext))
    {
        return AES_DECRYPT_ERROR;
    }

    gcm_finish(&g,tag);
    tagLength=16;
    return 0;
}
Пример #6
0
TEE_Result tee_authenc_init(
	void *ctx, uint32_t algo, TEE_OperationMode mode, const uint8_t *key,
	size_t key_len, const uint8_t *nonce,
	size_t nonce_len, size_t tag_len, size_t aad_len, size_t payload_len)
{
	TEE_Result res;
	int ltc_res;
	int ltc_cipherindex;
	unsigned char *payload, *res_payload;
	struct tee_ccm_state *ccm;
	struct tee_gcm_state *gcm;

	res = tee_algo_to_ltc_cipherindex(algo, &ltc_cipherindex);
	if (res != TEE_SUCCESS)
		return TEE_ERROR_NOT_SUPPORTED;
	switch (algo) {
	case TEE_ALG_AES_CCM:
		/* Check the key length */
		if ((!key) || (key_len > TEE_CCM_KEY_MAX_LENGTH))
			return TEE_ERROR_BAD_PARAMETERS;

		/* check the nonce */
		if (nonce_len > TEE_CCM_NONCE_MAX_LENGTH)
			return TEE_ERROR_BAD_PARAMETERS;

		/* check the tag len */
		if ((tag_len < 4) ||
		    (tag_len > TEE_CCM_TAG_MAX_LENGTH) ||
		    (tag_len % 2 != 0))
			return TEE_ERROR_NOT_SUPPORTED;

		/* allocate payload */
		payload = malloc(payload_len + TEE_CCM_KEY_MAX_LENGTH);
		if (!payload)
			return TEE_ERROR_OUT_OF_MEMORY;
		res_payload = malloc(payload_len + TEE_CCM_KEY_MAX_LENGTH);
		if (!res_payload) {
			free(payload);
			return TEE_ERROR_OUT_OF_MEMORY;
		}

		/* initialize the structure */
		ccm = ctx;
		memset(ccm, 0, sizeof(struct tee_ccm_state));
		memcpy(ccm->key, key, key_len);
		ccm->key_len = key_len;			/* the key length */
		if (nonce && nonce_len) {
			memcpy(ccm->nonce, nonce, nonce_len);
			ccm->nonce_len = nonce_len;
		} else {
			ccm->nonce_len = 0;
		}
		ccm->tag_len = tag_len;
		ccm->aad_len = aad_len;
		ccm->payload_len = payload_len;
		ccm->payload = payload;
		ccm->res_payload = res_payload;
		ccm->ltc_cipherindex = ltc_cipherindex;

		if (ccm->aad_len) {
			ccm->header = malloc(ccm->aad_len);
			if (!ccm->header) {
				free(payload);
				free(res_payload);
				return TEE_ERROR_OUT_OF_MEMORY;
			}
		}

		/* memset the payload to 0 that will be used for padding */
		memset(ccm->payload, 0, payload_len + TEE_CCM_KEY_MAX_LENGTH);
		break;

	case TEE_ALG_AES_GCM:
		/* reset the state */
		gcm = ctx;
		memset(gcm, 0, sizeof(struct tee_gcm_state));
		gcm->tag_len = tag_len;

		ltc_res = gcm_init(
			&gcm->ctx, ltc_cipherindex, key, key_len);
		if (ltc_res != CRYPT_OK)
			return TEE_ERROR_BAD_STATE;

		/* Add the IV */
		ltc_res = gcm_add_iv(&gcm->ctx, nonce, nonce_len);
		if (ltc_res != CRYPT_OK)
			return TEE_ERROR_BAD_STATE;
		break;

	default:
		return TEE_ERROR_NOT_SUPPORTED;
	}

	return TEE_SUCCESS;
}
Пример #7
0
PlaintextMessage EncryptedMessage::decrypt(const G2& P, const G2& Ppub, G1 D, PFC *pfc) {
    G2 uCalc;
    G2 U = (*autData).getU();
    Big ud_hash = (*pfc).hash_to_aes_key((*pfc).pairing(U,D));
    Big ses_key;
    Big r;
    int nbOfRecipients = (*autData).getNbOfRecipients();

    Big W;
    Big V = (*autData).getV();
    Big rho, rho_hash;
    vector <Big> ws = (*autData).getEncryptedRecipientKeys();
    char P_text[Clen];
    bool integrity = false;

    time_t begin_time = clock();

    int i = 0;
    while(U != uCalc && i < nbOfRecipients){
        // rho = V XOR Hash(e(D,U))
        W=ws.at(i);
        rho = lxor(W, ud_hash);

        // M = W XOR Hash(rho)
        (*pfc).start_hash();
        (*pfc).add_to_hash(rho);
        rho_hash = (*pfc).finish_hash_to_group();
        ses_key = lxor(V, rho_hash);

        // r = Hash(rho,M)
        (*pfc).start_hash();
        (*pfc).add_to_hash(rho);
        (*pfc).add_to_hash(ses_key);
        r = (*pfc).finish_hash_to_group();
        uCalc = (*pfc).mult(P,r);
        i++;
    }
    cout << "ses_key is " << endl << ses_key << endl;

    /*************************************************
    *       AES GCM part of the decryption step      *
    **************************************************/
    to_binary(ses_key, HASH_LEN, sessionKey, TRUE);
    char k1[HASH_LEN/2];
    char iv[HASH_LEN/2];
    char Tdec[TAG_LEN];
    memset(P_text, 0, Clen+1);

    getIV(iv);
    getK1(k1);

    int Alen = (*autData).getLength();
    char A[Alen];
    (*autData).encodeTo(A);
    gcm g;
    gcm_init(&g, HASH_LEN/2, k1, HASH_LEN/2, iv);
    gcm_add_header(&g, A, Alen);
    gcm_add_cipher(&g, GCM_DECRYPTING, P_text, Clen, C);
    gcm_finish(&g, Tdec);

    integrity = true;
    for (int j = 0; j < TAG_LEN; j++) {
        if(Tdec[j] != T[j]) {
            integrity = false;
        }
    }

    if(integrity == false) {
        cout << "Received tag T does not correspond to decrypted T. There are some integrity issues here." << endl;
    } else {
        cout << "Successful integrity check!" << endl;
    }

    message = (string)P_text;

    return PlaintextMessage(message);
}
struct item *symmetric_encryption(struct item *key, struct item *payload)
  /*@ requires [?f]world(?pub, ?key_clsfy) &*&
               principal(?principal1, ?count1) &*&
                 [_]pub(nonce_item(principal1, count1 + 1, 0)) &*&
               item(payload, ?pay, pub) &*& item(key, ?k, pub) &*&
                 k == symmetric_key_item(?principal2, ?count2); @*/
  /*@ ensures  [f]world(pub, key_clsfy) &*&
               principal(principal1, count1 + 2) &*&
               item(payload, pay, pub) &*& item(key, k, pub) &*&
               item(result, ?enc, pub) &*&
               col ? true :
                 enc == symmetric_encrypted_item(principal2, count2,
                                                 some(pay), ?ent); @*/
{
  //@ open [f]world(pub, key_clsfy);
  debug_print("ENCRYPTING:\n");
  print_item(payload);

  struct item* result;
  result = malloc(sizeof(struct item));
  if (result == 0) abort_crypto_lib("Malloc failed");

  {
    gcm_context gcm_context;
    char iv_buffer[GCM_IV_SIZE];
    char *iv;
    char *result_cs;
    char *encrypted;

    //@ open item(key, k, pub);
    //@ assert key->content |-> ?k_cont &*& key->size |-> ?k_size;
    check_valid_symmetric_key_item_size(key->size);
    //@ open [_]item_constraints(k, ?k_cs0, pub);
    //@ assert [_]ic_parts(k)(?k_tag, ?k_cs);
    //@ crypto_chars_limits(k_cont);
    //@ crypto_chars_split(k_cont, TAG_LENGTH);
    //@ WELL_FORMED(k_tag, k_cs, TAG_SYMMETRIC_KEY)
    //@ assert crypto_chars(secret, k_cont, TAG_LENGTH, k_tag);
    //@ assert crypto_chars(secret, k_cont + TAG_LENGTH, GCM_KEY_SIZE, k_cs);
    //@ cryptogram k_cg = cg_symmetric_key(principal2, count2);
    //@ if (col) k_cg = chars_for_cg_sur(k_cs, tag_symmetric_key);
    //@ if (col) crypto_chars_to_chars(k_cont + TAG_LENGTH, GCM_KEY_SIZE);
    //@ if (col) public_chars_extract(k_cont + TAG_LENGTH, k_cg);
    //@ if (col) chars_to_secret_crypto_chars(k_cont + TAG_LENGTH, GCM_KEY_SIZE);
    //@ close cryptogram(k_cont + TAG_LENGTH, GCM_KEY_SIZE, k_cs, k_cg);
    //@ close gcm_context(&gcm_context);
    if (gcm_init(&gcm_context, POLARSSL_CIPHER_ID_AES, (key->content + TAG_LENGTH),
                (unsigned int) GCM_KEY_SIZE * 8) != 0)
      abort_crypto_lib("Init gcm failed");
    //@ assert gcm_context_initialized(&gcm_context, ?p, ?c);
    //@ assert col || (p == principal2 && c == count2);
    //@ open cryptogram(k_cont + TAG_LENGTH, GCM_KEY_SIZE, k_cs, k_cg);
    //@ crypto_chars_join(k_cont);
    //@ close item(key, k, pub);

    //@ open item(payload, pay, pub);
    //@ open [_]item_constraints(pay, ?pay_cs, pub);
    //@ assert payload->content |-> ?p_cont &*& payload->size |-> ?p_size;
    //@ crypto_chars_limits(p_cont);
    if (payload->size >= INT_MAX - TAG_LENGTH - GCM_IV_SIZE - GCM_MAC_SIZE ||
        payload->size < MINIMAL_STRING_SIZE)
      abort_crypto_lib("Gcm encryption failed: incorrect sizes");
    result->size = TAG_LENGTH + GCM_IV_SIZE + GCM_MAC_SIZE + payload->size;
    result->content = malloc(result->size);

    //@ assert result->content |-> ?r_cont &*& result->size |-> ?r_size;
    if (result->content == 0)
      abort_crypto_lib("Malloc failed");
    //@ chars_split(r_cont, TAG_LENGTH);
    write_tag(result->content, TAG_SYMMETRIC_ENC);
    //@ assert chars(r_cont, TAG_LENGTH, ?tag_cs);
    //@ public_chars(r_cont, TAG_LENGTH);
    //@ assert tag_cs == full_tag(TAG_SYMMETRIC_ENC);
    //@ assert chars(r_cont + TAG_LENGTH, GCM_IV_SIZE + p_size, _);
    //@ chars_split(r_cont + TAG_LENGTH, GCM_IV_SIZE);
    iv = result->content + TAG_LENGTH;
    //@ close nonce_request(principal1, 0);
    //@ close [f]world(pub, key_clsfy);
    create_havege_random(iv, GCM_IV_SIZE);
    //@ open cryptogram(iv, GCM_IV_SIZE, ?iv_cs, ?iv_cg);
    memcpy(iv_buffer, iv, GCM_IV_SIZE);
    //@ close cryptogram(iv, GCM_IV_SIZE, iv_cs, iv_cg);
    //@ close polarssl_pub(pub)(iv_cg);
    //@ leak polarssl_pub(pub)(iv_cg);
    //@ public_cryptogram(iv, iv_cg);
    //@ public_chars(iv, GCM_IV_SIZE);
    encrypted = iv + GCM_IV_SIZE;
    //@ chars_split(encrypted, GCM_MAC_SIZE);
    //@ open principal(principal1, count1 + 1);
    if (gcm_crypt_and_tag(&gcm_context, GCM_ENCRYPT,
                          (unsigned int) payload->size, iv_buffer, 
                          GCM_IV_SIZE, NULL, 0, payload->content, 
                          encrypted + GCM_MAC_SIZE,
                          GCM_MAC_SIZE, encrypted) != 0)
      abort_crypto_lib("Gcm encryption failed");
    //@ close principal(principal1, count1 + 2);
    zeroize(iv_buffer, GCM_IV_SIZE);
    //@ assert crypto_chars(secret, encrypted, GCM_MAC_SIZE, ?mac_cs);
    //@ assert crypto_chars(secret, encrypted + GCM_MAC_SIZE, p_size, ?enc_cs);
    //@ crypto_chars_join(encrypted);
    //@ assert exists(?enc_cg);
    //@ list<char> cg_cs = append(mac_cs, enc_cs);
    //@ assert cg_cs == chars_for_cg(enc_cg);
    //@ list<char> cont_cs = append(iv_cs, cg_cs);
    //@ take_append(GCM_IV_SIZE, iv_cs, cg_cs);
    //@ drop_append(GCM_IV_SIZE, iv_cs, cg_cs);
    //@ list<char> cs = append(tag_cs, cont_cs);
    //@ take_append(TAG_LENGTH, tag_cs, cont_cs);
    //@ drop_append(TAG_LENGTH, tag_cs, cont_cs);
    
    //@ item enc;
    //@ list<char> ent = append(iv_cs, iv_cs);
    //@ take_append(GCM_IV_SIZE, iv_cs, iv_cs);
    //@ drop_append(GCM_IV_SIZE, iv_cs, iv_cs);
    /*@ if (col)
        {
          enc_cg = chars_for_cg_sur(cg_cs, tag_auth_encrypted);
          assert enc_cg == cg_auth_encrypted(?p0, ?c0, ?pay0, ?iv0);
          ent = append(iv_cs, iv0);
          take_append(GCM_IV_SIZE, iv_cs, iv0);
          drop_append(GCM_IV_SIZE, iv_cs, iv0);
          enc = symmetric_encrypted_item(p0, c0, some(pay), ent);
          public_chars(encrypted, GCM_MAC_SIZE + p_size);
          assert chars(encrypted, GCM_MAC_SIZE + p_size, cg_cs);
          chars_join(iv);
          chars_join(r_cont);
          assert chars(r_cont, r_size, cs);
          public_chars(r_cont, r_size);
          public_generated_split(polarssl_pub(pub), cs, TAG_LENGTH);
          close ic_sym_enc(enc)(iv0, cg_cs);
        }
        else
        {
          assert enc_cg == cg_auth_encrypted(principal2, count2, pay_cs, iv_cs);
          enc = symmetric_encrypted_item(principal2, count2, some(pay), ent);
          close polarssl_pub(pub)(cg_nonce(principal1, count1 + 1));
          leak  polarssl_pub(pub)(cg_nonce(principal1, count1 + 1));
          public_generated(polarssl_pub(pub), cg_nonce(principal1, count1 + 1));
          chars_to_secret_crypto_chars(iv, GCM_IV_SIZE);
          crypto_chars_join(iv);
          chars_to_secret_crypto_chars(r_cont, TAG_LENGTH);
          crypto_chars_join(r_cont);
          assert crypto_chars(secret, r_cont, r_size, cs);
          close ic_sym_enc(enc)(iv_cs, cg_cs);
        }
    @*/
    //@ well_formed_item_constraints(pay, enc);
    //@ close ic_cg(enc)(cg_cs, enc_cg);
    //@ close ic_parts(enc)(tag_cs, cont_cs);
    //@ WELL_FORMED(tag_cs, cont_cs, TAG_SYMMETRIC_ENC)
    //@ close item_constraints(enc, cs, pub);
    //@ leak item_constraints(enc, cs, pub);
    //@ close item(result, enc, pub);
    //@ close item(payload, pay, pub);
    gcm_free(&gcm_context);
    //@ open gcm_context(&gcm_context);
  }

  debug_print("ENCRYPTING RESULT:\n");
  print_item(result);

  return result;
}
struct item *symmetric_decryption(struct item *key, struct item *item)
  /*@ requires [?f]world(?pub, ?key_clsfy) &*&
               item(item, ?enc, pub) &*&
                 enc == symmetric_encrypted_item(?principal1, ?count1,
                                                 ?pay, ?ent) &*&
               item(key, ?k, pub) &*&
                 k == symmetric_key_item(?principal2, ?count2); @*/
  /*@ ensures  [f]world(pub, key_clsfy) &*&
               item(item, enc, pub) &*& item(key, k, pub) &*&
               item(result, ?dec, pub) &*&
               col ? [_]pub(dec) :
               switch(pay)
               {
                 case some(dec2):
                   return principal1 == principal2 &&
                          count1 == count2 && dec == dec2;
                 case none:
                   return false;
               }; @*/
{
  debug_print("DECRYPTING:\n");
  print_item(item);
  check_is_symmetric_encrypted(item);

  //@ open [f]world(pub, key_clsfy);
  struct item* result;
  result = malloc(sizeof(struct item));
  if (result == 0) abort_crypto_lib("Malloc failed");

  {
    gcm_context gcm_context;
    char *iv;
    char iv_buffer[GCM_IV_SIZE];
    char *encrypted;

    //@ open item(key, k, pub);
    //@ assert key->content |-> ?k_cont &*& key->size |-> ?k_size;
    check_valid_symmetric_key_item_size(key->size);
    //@ open [_]item_constraints(k, ?k_cs0, pub);
    //@ assert [_]ic_parts(k)(?k_tag, ?k_cs);
    //@ crypto_chars_limits(k_cont);
    //@ crypto_chars_split(k_cont, TAG_LENGTH);
    //@ WELL_FORMED(k_tag, k_cs, TAG_SYMMETRIC_KEY)
    //@ assert crypto_chars(secret, k_cont, TAG_LENGTH, k_tag);
    //@ assert crypto_chars(secret, k_cont + TAG_LENGTH, GCM_KEY_SIZE, k_cs);
    //@ cryptogram k_cg = cg_symmetric_key(principal2, count2);
    //@ if (col) k_cg = chars_for_cg_sur(k_cs, tag_symmetric_key);
    //@ if (col) crypto_chars_to_chars(k_cont + TAG_LENGTH, GCM_KEY_SIZE);
    //@ if (col) public_chars_extract(k_cont + TAG_LENGTH, k_cg);
    //@ if (col) chars_to_secret_crypto_chars(k_cont + TAG_LENGTH, GCM_KEY_SIZE);
    //@ close cryptogram(k_cont + TAG_LENGTH, GCM_KEY_SIZE, k_cs, k_cg);
    //@ close gcm_context(&gcm_context);
    if (gcm_init(&gcm_context, POLARSSL_CIPHER_ID_AES, (key->content + TAG_LENGTH),
                (unsigned int) GCM_KEY_SIZE * 8) != 0)
      abort_crypto_lib("Init gcm failed");
    //@ assert gcm_context_initialized(&gcm_context, ?p, ?c);
    //@ assert col || (p == principal2 && c == count2);
    //@ open cryptogram(k_cont + TAG_LENGTH, GCM_KEY_SIZE, k_cs, k_cg);
    //@ crypto_chars_join(k_cont);
    //@ close item(key, k, pub);

    //@ open item(item, enc, pub);
    //@ assert item->content |-> ?i_cont &*& item->size |-> ?i_size;
    //@ open [_]item_constraints(enc, ?cs, pub);
    //@ open [_]ic_parts(enc)(?enc_tag, ?enc_cont);
    //@ open [_]ic_cg(enc)(_, ?enc_cg);
    //@ take_append(TAG_LENGTH, enc_tag, enc_cont);
    //@ drop_append(TAG_LENGTH, enc_tag, enc_cont);
    //@ open [_]ic_sym_enc(enc)(?enc_iv, ?cg_cs);
    //@ assert true == well_formed(cs, nat_length(cs));
    //@ close [1/2]hide_crypto_chars(_, i_cont, i_size, cs);
    check_valid_symmetric_encrypted_item_size(item->size);
    //@ assert length(cs) > TAG_LENGTH + GCM_IV_SIZE;
    int size = item->size - TAG_LENGTH - GCM_IV_SIZE - GCM_MAC_SIZE;
    if (size <= MINIMAL_STRING_SIZE) abort_crypto_lib("Gcm decryption failed");
    //@ crypto_chars_limits(i_cont);
    //@ crypto_chars_split(i_cont, TAG_LENGTH);
    iv = item->content + TAG_LENGTH;
    //@ crypto_chars_split(iv, GCM_IV_SIZE);
    //@ assert [1/2]crypto_chars(secret, iv, GCM_IV_SIZE, ?iv_cs);
    memcpy(iv_buffer, iv, GCM_IV_SIZE);
    //@ assert cs == append(enc_tag, enc_cont);
    //@ assert enc_cont == append(iv_cs, cg_cs);
    //@ public_crypto_chars(iv, GCM_IV_SIZE);
    //@ chars_to_secret_crypto_chars(iv, GCM_IV_SIZE);
    encrypted = iv + GCM_IV_SIZE;
    //@ crypto_chars_limits(encrypted);
    //@ crypto_chars_split(encrypted, GCM_MAC_SIZE);
    //@ assert [1/2]crypto_chars(secret, encrypted, GCM_MAC_SIZE, ?mac_cs);
    /*@ assert [1/2]crypto_chars(secret, encrypted + GCM_MAC_SIZE, 
                                 size, ?enc_cs); @*/
    //@ assert cg_cs == append(mac_cs, enc_cs);                             
    result->size = size;
    result->content = malloc(size);
    if (result->content == 0) abort_crypto_lib("Malloc failed");
    //@ assert result->content |-> ?r_cont &*& result->size |-> size;
    //@ if (col) enc_cg = chars_for_cg_sur(cg_cs, tag_auth_encrypted);
    //@ close exists(enc_cg);
    if (gcm_auth_decrypt(&gcm_context, (unsigned int) size,
                         iv_buffer, GCM_IV_SIZE, NULL, 0, encrypted, 
                         GCM_MAC_SIZE, encrypted + GCM_MAC_SIZE,
                         result->content) != 0)
      abort_crypto_lib("Gcm decryption failed");
    //@ assert crypto_chars(secret, r_cont, size, ?dec_cs);
    //@ assert col || enc_cg == cg_auth_encrypted(principal1, count1, dec_cs, iv_cs);
    //@ crypto_chars_join(encrypted);
    //@ crypto_chars_join(iv);
    //@ crypto_chars_join(i_cont);
    //@ open [1/2]hide_crypto_chars(_, i_cont, i_size, cs);
    //@ close item(item, enc, pub);
    gcm_free(&gcm_context);
    //@ open gcm_context(&gcm_context);
    zeroize(iv_buffer, GCM_IV_SIZE);
    //@ close [f]world(pub, key_clsfy);
    
    /*@ if (col)
        {
          crypto_chars_to_chars(r_cont, size);
          chars_to_crypto_chars(r_cont, size);
        }
        else
        {
          assert enc == symmetric_encrypted_item(principal1, count1,
                                                 pay, ent);
          assert enc_cg == cg_auth_encrypted(principal1, count1, 
                                             dec_cs, enc_iv);
          switch(pay)
          {
            case some(pay1):
              assert [_]item_constraints(pay1, dec_cs, pub);
            case none:
              open [_]ill_formed_item_chars(enc)(dec_cs);
              assert [_]public_generated(polarssl_pub(pub))(dec_cs);
              public_crypto_chars(r_cont, size);
              chars_to_crypto_chars(r_cont, size);
          }
        }
    @*/
    parse_item(result->content, size);
    /*@ if (col)
        {
          public_chars(r_cont, size);
          chars_to_secret_crypto_chars(r_cont, size);
          retreive_proof_obligations();
          deserialize_item(dec_cs, pub);
          leak proof_obligations(pub);
        }
    @*/
    //@ assert crypto_chars(secret, r_cont, size, dec_cs);
    //@ assert [_]item_constraints(?r, dec_cs, pub);
    //@ close item(result, r, pub);
  }

  debug_print("DECRYPTING RESULT:\n");
  print_item(result);

  return result;
}
Пример #10
0
ret_code_t pm_init(void)
{
    ret_code_t err_code;

    err_code = pds_init();
    if (err_code != NRF_SUCCESS)
    {
        return NRF_ERROR_INTERNAL;
    }

    err_code = pdb_init();
    if (err_code != NRF_SUCCESS)
    {
        return NRF_ERROR_INTERNAL;
    }

    err_code = sm_init();
    if (err_code != NRF_SUCCESS)
    {
        return NRF_ERROR_INTERNAL;
    }

    err_code = smd_init();
    if (err_code != NRF_SUCCESS)
    {
        return NRF_ERROR_INTERNAL;
    }

    err_code = gcm_init();
    if (err_code != NRF_SUCCESS)
    {
        return NRF_ERROR_INTERNAL;
    }

    err_code = gscm_init();
    if (err_code != NRF_SUCCESS)
    {
        return NRF_ERROR_INTERNAL;
    }

    err_code = im_init();
    if (err_code != NRF_SUCCESS)
    {
        return NRF_ERROR_INTERNAL;
    }

    internal_state_reset();

    m_pairing_flag_id = ble_conn_state_user_flag_acquire();
    if (m_pairing_flag_id == BLE_CONN_STATE_USER_FLAG_INVALID)
    {
        return NRF_ERROR_INTERNAL;
    }

    m_bonding_flag_id = ble_conn_state_user_flag_acquire();
    if (m_bonding_flag_id == BLE_CONN_STATE_USER_FLAG_INVALID)
    {
        return NRF_ERROR_INTERNAL;
    }

    m_peer_rank_initialized = false;
    m_module_initialized    = true;

    return NRF_SUCCESS;
}
Пример #11
0
static int gcm_camellia_setkey_wrap( void *ctx, const unsigned char *key,
                                     unsigned int key_length )
{
    return gcm_init( (gcm_context *) ctx, POLARSSL_CIPHER_ID_CAMELLIA,
                     key, key_length );
}
void app_send(char *key, char *message, int message_len)
  /*@ requires polarssl_generated_values(?creator, ?count1) &*&
               [?f0]polarssl_world(sc_auth_polarssl_pub) &*&
               [?f1]polarssl_cryptogram(key, KEY_BYTE_SIZE, ?key_cs, ?key_cg) &*&
                 key_cg == polarssl_symmetric_key(creator, ?key_id) &*&
               [?f2]chars(message, message_len, ?m_cs) &*&
                 message_len >= POLARSSL_MIN_ENCRYPTED_BYTE_SIZE &*&
                 message_len < POLARSSL_MAX_MESSAGE_BYTE_SIZE - 84 &*&
                 bad(creator) ?
                   [_]polarssl_public_generated_chars(sc_auth_polarssl_pub)(m_cs)
                 :
                   true == app_send_event(creator, m_cs);
  @*/
  /*@ ensures  polarssl_generated_values(creator, ?count2) &*& count2 > count1 &*&
               [f0]polarssl_world(sc_auth_polarssl_pub) &*&
               [f1]polarssl_cryptogram(key, KEY_BYTE_SIZE, key_cs, key_cg) &*&
               [f2]chars(message, message_len, m_cs);
  @*/
{
  int socket;
  havege_state havege_state;
  char iv[16];

  // init
  {
    net_usleep(20000);
    if(net_connect(&socket, NULL, APP_RECEIVE_PORT) != 0)
      abort();
    if(net_set_block(socket) != 0)
      abort();

    //@ close havege_state(&havege_state);
    havege_init(&havege_state);
  }

  // iv stuff
  {
    //@ close random_request(creator, 0, false);
    if (havege_random(&havege_state, iv, 16) != 0) abort();  
  }
  //@ open polarssl_cryptogram(iv, 16, ?iv_cs, _);

  char* m = malloc(16 + message_len + 16);
  if (m == 0) abort();
  memcpy(m, iv, 16);
  //@ assert chars(m, 16, iv_cs);
  //@ assert chars(m + 16, message_len + 16, ?cs1);
  //@ polarssl_public_generated_chars_assume(sc_auth_polarssl_pub, iv_cs);
   
  // encrypt message
  {
    unsigned int temp;
    gcm_context gcm_context;
    //@ close gcm_context(&gcm_context);
    //@ open [f1]polarssl_cryptogram(key, KEY_BYTE_SIZE, key_cs, key_cg);
    //@ close polarssl_key_id(creator, key_id);
    if (gcm_init(&gcm_context, POLARSSL_AES_CIPHER_ID, key, 
                (unsigned int) KEY_BYTE_SIZE * 8) != 0) abort();
    //@ close [f1]polarssl_cryptogram(key, KEY_BYTE_SIZE, key_cs, key_cg);
    //@ chars_split(m + 16, message_len);
    if (gcm_crypt_and_tag(&gcm_context, POLARSSL_GCM_ENCRYPT, 
                          (unsigned int) message_len,
                          iv, 16, NULL, 0, message, m + 16, 16,
                          (char*) ((m + 16) + message_len)) != 0)
      abort();
    gcm_free(&gcm_context);
    //@ open gcm_context(&gcm_context);
  }
  //@ assert polarssl_cryptogram(m + 16, message_len, ?e_cs, ?e_cg);
  /*@ assert e_cg == polarssl_auth_encrypted(
                                       creator, key_id, ?t_cs, m_cs, iv_cs); @*/
  //@ close sc_auth_polarssl_pub(e_cg);
  //@ leak sc_auth_polarssl_pub(e_cg);
  /*@ polarssl_public_message_from_cryptogram(
                     sc_auth_polarssl_pub, m + 16, message_len, e_cs, e_cg); @*/
  /*@ open polarssl_public_message(sc_auth_polarssl_pub)
                                  (m + 16, message_len, e_cs); @*/
  //@ assert chars(m + 16 + message_len, 16, t_cs);
  //@ chars_join(m);
  //@ chars_join(m);
  //@ assert chars(m, 16 + message_len + 16, ?cs);
  //@ append_assoc(iv_cs, e_cs, t_cs);
  //@ assert cs == append(iv_cs, append(e_cs, t_cs));
  
  //@ polarssl_public_generated_chars_assume(sc_auth_polarssl_pub, t_cs);
  /*@ polarssl_public_generated_chars_join(
                                         sc_auth_polarssl_pub, iv_cs, e_cs); @*/
  /*@ polarssl_public_generated_chars_join(
                           sc_auth_polarssl_pub, append(iv_cs, e_cs), t_cs); @*/
  /*@ close polarssl_public_message(sc_auth_polarssl_pub)
                                   (m, 16 + message_len + 16,
                                    append(iv_cs, append(e_cs, t_cs))); @*/
  net_send(&socket, m, (unsigned int) 16 + (unsigned int) message_len + 16);
  //@ open polarssl_public_message(sc_auth_polarssl_pub)(m, _, _);

  {
    free(m);
    havege_free(&havege_state);
    //@ open havege_state(&havege_state);
    net_close(socket);
  }
}
int app_receive(char *key, char **message)
  /*@ requires [?f0]polarssl_world(sc_auth_polarssl_pub) &*&
               [?f1]polarssl_cryptogram(key, KEY_BYTE_SIZE, ?key_cs, ?key_cg) &*&
                 key_cg == polarssl_symmetric_key(?creator, ?key_id) &*&
               pointer(message, _);
  @*/
  /*@ ensures  [f0]polarssl_world(sc_auth_polarssl_pub) &*&
               [f1]polarssl_cryptogram(key, KEY_BYTE_SIZE, key_cs, key_cg) &*&
               pointer(message, ?message_p) &*&
               malloc_block(message_p, result) &*&
               chars(message_p, result, ?m_cs) &*&
               bad(creator) ?
                 [_]polarssl_public_generated_chars(sc_auth_polarssl_pub)(m_cs)
               : 
                 true == app_send_event(creator, m_cs);
  @*/
{
  int socket1;
  int socket2;
  int size;
  int result_size;
  char buffer[POLARSSL_MAX_MESSAGE_BYTE_SIZE];

  char iv[16];
  char tag[16];
  char* encrypted;
  char* decrypted;

  // Receive message
  if(net_bind(&socket1, NULL, APP_RECEIVE_PORT) != 0)
    abort();
  if(net_accept(socket1, &socket2, NULL) != 0)
    abort();
  if(net_set_block(socket2) != 0)
    abort();
    
  size = net_recv(&socket2, buffer, POLARSSL_MAX_MESSAGE_BYTE_SIZE);
  if (size < 16 + POLARSSL_MIN_ENCRYPTED_BYTE_SIZE + 16)
    abort();
  //@ open polarssl_public_message(sc_auth_polarssl_pub)(buffer, size, ?cs);
  //@ close [1/2]hide_chars(buffer, size, cs);
  result_size = size - 16 - 16;
  encrypted = malloc(result_size);
  if (encrypted == 0) abort();
  decrypted = malloc(result_size);
  if (decrypted == 0) abort();
  
  // Extract parts of message
  memcpy(iv, buffer, 16);
  memcpy(encrypted, (void*) buffer + 16, (unsigned int) result_size);
  memcpy(tag, (void*) buffer + 16 + result_size, 16);
  //@ assert chars(iv, 16, ?iv_cs);
  //@ assert chars(encrypted, result_size, ?e_cs);
  //@ assert chars(tag, 16, ?t_cs);
  //@ chars_join(buffer);
  //@ chars_join(buffer);
  //@ open [1/2]hide_chars(buffer, size, cs);
  //@ close [1/2]hide_chars(buffer, size, cs);
  //@ assert cs == append(iv_cs, append(e_cs, t_cs));

  // Decrypt message
  {
    gcm_context gcm_context;
    //@ close gcm_context(&gcm_context);
    //@ open [f1]polarssl_cryptogram(key, KEY_BYTE_SIZE, key_cs, key_cg);
    //@ close polarssl_key_id(creator, key_id);
    if (gcm_init(&gcm_context, POLARSSL_AES_CIPHER_ID, key, 
                (unsigned int) KEY_BYTE_SIZE * 8) != 0) abort();
    /*@ assert gcm_context_initialized(&gcm_context, 
                                       some(pair(creator, key_id))); @*/
    //@ close [f1]polarssl_cryptogram(key, KEY_BYTE_SIZE, key_cs, key_cg);

    //@ polarssl_public_generated_chars_split(sc_auth_polarssl_pub, cs, 16);
    /*@ polarssl_public_generated_chars_split(
                     sc_auth_polarssl_pub, append(e_cs, t_cs), result_size); @*/
    //@ assert chars(encrypted, result_size, e_cs);
    if (gcm_auth_decrypt(&gcm_context, (unsigned int) result_size,
                         iv, 16, NULL, 0, tag, 16,
                         encrypted, decrypted) != 0) abort();
    gcm_free(&gcm_context);
    //@ open gcm_context(&gcm_context);
  }
  
  //@ assert chars(decrypted, result_size, ?dec_cs);
  //@ chars_join(buffer);
  //@ open [1/2]hide_chars(buffer, size, cs);

  /*@ polarssl_cryptogram e_cg = polarssl_auth_encrypted(
                                      creator, key_id, t_cs, dec_cs, iv_cs); @*/
  //@ assert e_cs == polarssl_chars_for_cryptogram(e_cg);
  //@ polarssl_cryptogram_constraints(e_cs, e_cg);
  /*@ polarssl_public_generated_chars_extract(
                                          sc_auth_polarssl_pub, e_cs, e_cg); @*/
  //@ open [_]sc_auth_polarssl_pub(e_cg);
  /*@ if (!bad(creator))
      {
        assert true == app_send_event(creator, dec_cs);
      }
      else
      {
        assert [_]polarssl_public_generated_chars(sc_auth_polarssl_pub)(dec_cs);
      }
  @*/

  net_close(socket1);
  net_close(socket2);
  
  free(encrypted);
  *message = decrypted;
  return result_size;
}
Пример #14
0
int main( int argc, char *argv[] )
{
    int keysize, i;
    unsigned char tmp[200];
    char title[TITLE_LEN];
    todo_list todo;

    if( argc == 1 )
        memset( &todo, 1, sizeof( todo ) );
    else
    {
        memset( &todo, 0, sizeof( todo ) );

        for( i = 1; i < argc; i++ )
        {
            if( strcmp( argv[i], "md4" ) == 0 )
                todo.md4 = 1;
            else if( strcmp( argv[i], "md5" ) == 0 )
                todo.md5 = 1;
            else if( strcmp( argv[i], "ripemd160" ) == 0 )
                todo.ripemd160 = 1;
            else if( strcmp( argv[i], "sha1" ) == 0 )
                todo.sha1 = 1;
            else if( strcmp( argv[i], "sha256" ) == 0 )
                todo.sha256 = 1;
            else if( strcmp( argv[i], "sha512" ) == 0 )
                todo.sha512 = 1;
            else if( strcmp( argv[i], "arc4" ) == 0 )
                todo.arc4 = 1;
            else if( strcmp( argv[i], "des3" ) == 0 )
                todo.des3 = 1;
            else if( strcmp( argv[i], "des" ) == 0 )
                todo.des = 1;
            else if( strcmp( argv[i], "aes_cbc" ) == 0 )
                todo.aes_cbc = 1;
            else if( strcmp( argv[i], "aes_gcm" ) == 0 )
                todo.aes_gcm = 1;
            else if( strcmp( argv[i], "camellia" ) == 0 )
                todo.camellia = 1;
            else if( strcmp( argv[i], "blowfish" ) == 0 )
                todo.blowfish = 1;
            else if( strcmp( argv[i], "havege" ) == 0 )
                todo.havege = 1;
            else if( strcmp( argv[i], "ctr_drbg" ) == 0 )
                todo.ctr_drbg = 1;
            else if( strcmp( argv[i], "hmac_drbg" ) == 0 )
                todo.hmac_drbg = 1;
            else if( strcmp( argv[i], "rsa" ) == 0 )
                todo.rsa = 1;
            else if( strcmp( argv[i], "dhm" ) == 0 )
                todo.dhm = 1;
            else if( strcmp( argv[i], "ecdsa" ) == 0 )
                todo.ecdsa = 1;
            else if( strcmp( argv[i], "ecdh" ) == 0 )
                todo.ecdh = 1;
            else
            {
                printf( "Unrecognized option: %s\n", argv[i] );
                printf( "Available options:" OPTIONS );
            }
        }
    }

    printf( "\n" );

    memset( buf, 0xAA, sizeof( buf ) );

#if defined(POLARSSL_MD4_C)
    if( todo.md4 )
        TIME_AND_TSC( "MD4", md4( buf, BUFSIZE, tmp ) );
#endif

#if defined(POLARSSL_MD5_C)
    if( todo.md5 )
        TIME_AND_TSC( "MD5", md5( buf, BUFSIZE, tmp ) );
#endif

#if defined(POLARSSL_RIPEMD160_C)
    if( todo.ripemd160 )
        TIME_AND_TSC( "RIPEMD160", ripemd160( buf, BUFSIZE, tmp ) );
#endif

#if defined(POLARSSL_SHA1_C)
    if( todo.sha1 )
        TIME_AND_TSC( "SHA-1", sha1( buf, BUFSIZE, tmp ) );
#endif

#if defined(POLARSSL_SHA256_C)
    if( todo.sha256 )
        TIME_AND_TSC( "SHA-256", sha256( buf, BUFSIZE, tmp, 0 ) );
#endif

#if defined(POLARSSL_SHA512_C)
    if( todo.sha512 )
        TIME_AND_TSC( "SHA-512", sha512( buf, BUFSIZE, tmp, 0 ) );
#endif

#if defined(POLARSSL_ARC4_C)
    if( todo.arc4 )
    {
        arc4_context arc4;
        arc4_setup( &arc4, tmp, 32 );
        TIME_AND_TSC( "ARC4", arc4_crypt( &arc4, BUFSIZE, buf, buf ) );
    }
#endif

#if defined(POLARSSL_DES_C) && defined(POLARSSL_CIPHER_MODE_CBC)
    if( todo.des3 )
    {
        des3_context des3;
        des3_set3key_enc( &des3, tmp );
        TIME_AND_TSC( "3DES",
                des3_crypt_cbc( &des3, DES_ENCRYPT, BUFSIZE, tmp, buf, buf ) );
    }

    if( todo.des )
    {
        des_context des;
        des_setkey_enc( &des, tmp );
        TIME_AND_TSC( "DES",
                des_crypt_cbc( &des, DES_ENCRYPT, BUFSIZE, tmp, buf, buf ) );
    }
#endif

#if defined(POLARSSL_AES_C)
#if defined(POLARSSL_CIPHER_MODE_CBC)
    if( todo.aes_cbc )
    {
        aes_context aes;
        for( keysize = 128; keysize <= 256; keysize += 64 )
        {
            snprintf( title, sizeof( title ), "AES-CBC-%d", keysize );

            memset( buf, 0, sizeof( buf ) );
            memset( tmp, 0, sizeof( tmp ) );
            aes_setkey_enc( &aes, tmp, keysize );

            TIME_AND_TSC( title,
                aes_crypt_cbc( &aes, AES_ENCRYPT, BUFSIZE, tmp, buf, buf ) );
        }
    }
#endif
#if defined(POLARSSL_GCM_C)
    if( todo.aes_gcm )
    {
        gcm_context gcm;
        for( keysize = 128; keysize <= 256; keysize += 64 )
        {
            snprintf( title, sizeof( title ), "AES-GCM-%d", keysize );

            memset( buf, 0, sizeof( buf ) );
            memset( tmp, 0, sizeof( tmp ) );
            gcm_init( &gcm, POLARSSL_CIPHER_ID_AES, tmp, keysize );

            TIME_AND_TSC( title,
                    gcm_crypt_and_tag( &gcm, GCM_ENCRYPT, BUFSIZE, tmp,
                        12, NULL, 0, buf, buf, 16, tmp ) );

            gcm_free( &gcm );
        }
    }
#endif
#endif

#if defined(POLARSSL_CAMELLIA_C) && defined(POLARSSL_CIPHER_MODE_CBC)
    if( todo.camellia )
    {
        camellia_context camellia;
        for( keysize = 128; keysize <= 256; keysize += 64 )
        {
            snprintf( title, sizeof( title ), "CAMELLIA-CBC-%d", keysize );

            memset( buf, 0, sizeof( buf ) );
            memset( tmp, 0, sizeof( tmp ) );
            camellia_setkey_enc( &camellia, tmp, keysize );

            TIME_AND_TSC( title,
                    camellia_crypt_cbc( &camellia, CAMELLIA_ENCRYPT,
                        BUFSIZE, tmp, buf, buf ) );
        }
    }
#endif

#if defined(POLARSSL_BLOWFISH_C) && defined(POLARSSL_CIPHER_MODE_CBC)
    if( todo.blowfish )
    {
        blowfish_context blowfish;
        for( keysize = 128; keysize <= 256; keysize += 64 )
        {
            snprintf( title, sizeof( title ), "BLOWFISH-CBC-%d", keysize );

            memset( buf, 0, sizeof( buf ) );
            memset( tmp, 0, sizeof( tmp ) );
            blowfish_setkey( &blowfish, tmp, keysize );

            TIME_AND_TSC( title,
                    blowfish_crypt_cbc( &blowfish, BLOWFISH_ENCRYPT, BUFSIZE,
                        tmp, buf, buf ) );
        }
    }
#endif

#if defined(POLARSSL_HAVEGE_C)
    if( todo.havege )
    {
        havege_state hs;
        havege_init( &hs );
        TIME_AND_TSC( "HAVEGE", havege_random( &hs, buf, BUFSIZE ) );
    }
#endif

#if defined(POLARSSL_CTR_DRBG_C)
    if( todo.ctr_drbg )
    {
        ctr_drbg_context ctr_drbg;

        if( ctr_drbg_init( &ctr_drbg, myrand, NULL, NULL, 0 ) != 0 )
            exit(1);
        TIME_AND_TSC( "CTR_DRBG (NOPR)",
                if( ctr_drbg_random( &ctr_drbg, buf, BUFSIZE ) != 0 )
                exit(1) );

        if( ctr_drbg_init( &ctr_drbg, myrand, NULL, NULL, 0 ) != 0 )
            exit(1);
        ctr_drbg_set_prediction_resistance( &ctr_drbg, CTR_DRBG_PR_ON );
        TIME_AND_TSC( "CTR_DRBG (PR)",
                if( ctr_drbg_random( &ctr_drbg, buf, BUFSIZE ) != 0 )
                exit(1) );
    }
Пример #15
0
void attacker_send_auth_decrypted(havege_state *havege_state, void* socket)
  //@ requires attacker_invariant(?pub, ?pred, ?kc, havege_state, socket, ?attacker);
  //@ ensures  attacker_invariant(pub, pred, kc, havege_state, socket, attacker);
{
  int temp;
  int size1;
  int size2;
  char buffer1[MAX_MESSAGE_SIZE];
  char buffer2[MAX_MESSAGE_SIZE];
  char buffer3[MAX_MESSAGE_SIZE];
  gcm_context gcm_context;
  char iv[16];

  //@ open attacker_invariant(pub, pred, kc, havege_state, socket, attacker);

  size1 = net_recv(socket, buffer1, MAX_MESSAGE_SIZE);
  size2 = net_recv(socket, buffer2, MAX_MESSAGE_SIZE);
  if (size1 <= 16 || size2 <= 16 ||
      (size1 != 16 && size1 != 24 && size1 != 32))
  {
    //@ close attacker_invariant(pub, pred, kc, havege_state, socket, attacker);
    return;
  }

  //@ close gcm_context(&gcm_context);
  //@ interpret_symmetric_key(buffer1, size1);
  //@ assert cryptogram(buffer1, size1, ?ccs1, ?cg_key);
  //@ assert cg_key == cg_symmetric_key(?p, ?c);
  if (gcm_init(&gcm_context, POLARSSL_CIPHER_ID_AES,
      buffer1, (unsigned int) size1 * 8) == 0)
  {
    if (get_iv(havege_state, iv) == 0)
    {
      //@ assert crypto_chars(normal, iv, 16, ?ccs_iv);
      //@ assert chars(buffer2, size2, ?cs2);
      //@ interpret_auth_encrypted(buffer2, size2);
      //@ open cryptogram(buffer2, size2, ?ccs2, ?cg_enc);
      //@ cs_to_ccs_crypto_chars(buffer2, cs2);
      //@ chars_to_crypto_chars(buffer2, size2);
      //@ close exists(cg_enc);
      //@ assert cg_enc == cg_auth_encrypted(?p2, ?c2, ?ccs_output2, ?ccs_iv2);
      //@ crypto_chars_split(buffer2, 16);
      if (gcm_auth_decrypt(&gcm_context, (unsigned int) size2 - 16,
                            iv, 16, NULL, 0, buffer2, 16,
                            (void*) buffer2 + 16, buffer3) == 0)
      {
        /*@ if (!col)
            {
              assert crypto_chars(secret, buffer3, size2 - 16, ?ccs_output);
              ccs_output == ccs_output2;
              ccs_iv == ccs_iv2;
              assert ccs2 == ccs_for_cg(cg_enc);
              assert [_]pub(cg_enc);
              assert is_public_auth_decryption_is_public(?proof3, pub, pred);
              proof3(cg_key, cg_enc);
              public_crypto_chars(buffer3, size2 - 16);
              chars_to_crypto_chars(buffer3, size2 - 16);
            }
        @*/
        zeroize(iv, 16);
        //@ chars_to_crypto_chars(iv, 16);
      }
      //@ crypto_chars_to_chars(buffer3, size2 - 16);
      net_send(socket, buffer3, (unsigned int) size2 - 16);
      //@ crypto_chars_to_chars(buffer2, 16);
      //@ crypto_chars_to_chars((void*) buffer2 + 16, size2 - 16);
      //@ chars_join(buffer2);
    }
    //@ crypto_chars_to_chars(iv, 16);
    gcm_free(&gcm_context);
  }
  //@ open gcm_context(&gcm_context);
  //@ close attacker_invariant(pub, pred, kc, havege_state, socket, attacker);
  //@ public_cryptogram(buffer1, cg_key);
}
Пример #16
0
void attacker_send_auth_encrypted(havege_state *havege_state, void* socket)
  //@ requires attacker_invariant(?pub, ?pred, ?kc, havege_state, socket, ?attacker);
  //@ ensures  attacker_invariant(pub, pred, kc, havege_state, socket, attacker);
{
  int temp;
  int size1;
  int size2;
  char buffer1[MAX_MESSAGE_SIZE];
  char buffer2[MAX_MESSAGE_SIZE];
  char buffer3[MAX_MESSAGE_SIZE];
  gcm_context gcm_context;
  char iv[16];

  //@ open attacker_invariant(pub, pred, kc, havege_state, socket, attacker);

  size1 = net_recv(socket, buffer1, MAX_MESSAGE_SIZE);
  size2 = net_recv(socket, buffer2, MAX_MESSAGE_SIZE);
  if (size1 <= 0 || size2 <= 16 || size2 > MAX_MESSAGE_SIZE - 16 ||
      (size1 != 16 && size1 != 24 && size1 != 32))
  {
    //@ close attacker_invariant(pub, pred, kc, havege_state, socket, attacker);
    return;
  }
  //@ assert chars(buffer1, size1, ?cs1);
  //@ assert chars(buffer2, size2, ?cs2);

  //@ close gcm_context(&gcm_context);
  //@ interpret_symmetric_key(buffer1, size1);
  //@ assert cryptogram(buffer1, size1, cs_to_ccs(cs1), ?cg_key);
  //@ assert cg_key == cg_symmetric_key(?p, ?c);
  if (gcm_init(&gcm_context, POLARSSL_CIPHER_ID_AES,
      buffer1, (unsigned int) size1 * 8) == 0)
  {
    if (get_iv(havege_state, iv) == 0)
    {
      //@ chars_to_crypto_chars(buffer2, size2);
      //@ chars_split(buffer3, 16);
      if (gcm_crypt_and_tag(&gcm_context, GCM_ENCRYPT,
                            (unsigned int) size2, iv, 16, NULL, 0,
                            buffer2, (void*) buffer3 + 16, 16, buffer3) == 0)
      {
        /*@
          {
            crypto_chars_to_chars(buffer2, size2);
            public_chars(buffer2, size2);
            chars_to_crypto_chars(buffer2, size2);
            assert exists(?cg_enc);
            assert is_public_auth_encryption_is_public(?proof2, pub, pred);
            proof2(cg_enc);
            assert crypto_chars(secret, buffer3, 16, ?ccs_tag);
            assert crypto_chars(secret, (void*) buffer3 + 16, size2, ?ccs_enc);
            public_cg_ccs(cg_enc);
            public_ccs_split(append(ccs_tag, ccs_enc), 16);
            take_append(16, ccs_tag, ccs_enc);
            drop_append(16, ccs_tag, ccs_enc);
            public_crypto_chars(buffer3, 16);
            public_crypto_chars((void*) buffer3 + 16, size2);
          }
        @*/
        net_send(socket, buffer3, (unsigned int) size2 + 16);
        //@ chars_to_crypto_chars(buffer3, 16);
        //@ chars_to_crypto_chars((void*) buffer3 + 16, size2);
      }
      //@ crypto_chars_to_chars(buffer2, size2);
      //@ crypto_chars_join(buffer3);
      //@ crypto_chars_to_chars(buffer3, size2 + 16);
    }
    gcm_free(&gcm_context);
    //@ crypto_chars_to_chars(iv, 16);
  }
  //@ open gcm_context(&gcm_context);
  //@ close attacker_invariant(pub, pred, kc, havege_state, socket, attacker);
  //@ public_cryptogram(buffer1, cg_key);
}
Пример #17
0
/**
  Process an entire GCM packet in one call.
  @param cipher            Index of cipher to use
  @param key               The secret key
  @param keylen            The length of the secret key
  @param IV                The initial vector 
  @param IVlen             The length of the initial vector
  @param adata             The additional authentication data (header)
  @param adatalen          The length of the adata
  @param pt                The plaintext
  @param ptlen             The length of the plaintext (ciphertext length is the same)
  @param ct                The ciphertext
  @param tag               [out] The MAC tag
  @param taglen            [in/out] The MAC tag length
  @param direction         Encrypt or Decrypt mode (GCM_ENCRYPT or GCM_DECRYPT)
  @return CRYPT_OK on success
 */
int gcm_memory(      int           cipher,
               const unsigned char *key,    unsigned long keylen,
               const unsigned char *IV,     unsigned long IVlen,
               const unsigned char *adata,  unsigned long adatalen,
                     unsigned char *pt,     unsigned long ptlen,
                     unsigned char *ct, 
                     unsigned char *tag,    unsigned long *taglen,
                               int direction)
{
    void      *orig;
    gcm_state *gcm;
    int        err;

    if ((err = cipher_is_valid(cipher)) != CRYPT_OK) {
       return err;
    }
 
    if (cipher_descriptor[cipher].accel_gcm_memory != NULL) {
       return 
         cipher_descriptor[cipher].accel_gcm_memory
                                          (key,   keylen,
                                           IV,    IVlen,
                                           adata, adatalen,
                                           pt,    ptlen,
                                           ct,
                                           tag,   taglen,
                                           direction);
    }



#ifndef LTC_GCM_TABLES_SSE2
    orig = gcm = XMALLOC(sizeof(*gcm));
#else
    orig = gcm = XMALLOC(sizeof(*gcm) + 16);
#endif
    if (gcm == NULL) {
        return CRYPT_MEM;
    }

   /* Force GCM to be on a multiple of 16 so we can use 128-bit aligned operations
    * note that we only modify gcm and keep orig intact.  This code is not portable
    * but again it's only for SSE2 anyways, so who cares?
    */
#ifdef LTC_GCM_TABLES_SSE2
   if ((unsigned long)gcm & 15) {
      gcm = (gcm_state *)((unsigned long)gcm + (16 - ((unsigned long)gcm & 15)));
   }
#endif

    if ((err = gcm_init(gcm, cipher, key, keylen)) != CRYPT_OK) {
       goto LTC_ERR;
    }
    if ((err = gcm_add_iv(gcm, IV, IVlen)) != CRYPT_OK) {
       goto LTC_ERR;
    }
    if ((err = gcm_add_aad(gcm, adata, adatalen)) != CRYPT_OK) {
       goto LTC_ERR;
    }
    if ((err = gcm_process(gcm, pt, ptlen, ct, direction)) != CRYPT_OK) {
       goto LTC_ERR;
    }
    err = gcm_done(gcm, tag, taglen);
LTC_ERR:
    XFREE(orig);
    return err;
}
Пример #18
0
static int gcm_aes_setkey_wrap( void *ctx, const unsigned char *key,
                                unsigned int key_length )
{
    return gcm_init( (gcm_context *) ctx, POLARSSL_CIPHER_ID_AES,
                     key, key_length );
}