Пример #1
0
/* Changes the encryption level of the drive.
   If encrypt is true: encrypt drive, else decrypt */
uint8_t sd_change_encryption(uint8_t slot, bool encrypt, bool change_key, uint8_t *old_passwd, uint8_t *new_passwd)
{
	sd_mmc_err_t err;
	uint32_t i, nb_blocks;
	encrypt_config_t *config_ptr = NULL;
	
	security_get_config(&config_ptr);
	if ((encrypt == config_ptr->encryption_level) && !change_key)
		return CTRL_GOOD;
	
	if (change_key) {
		sha2(old_passwd, MAX_PASS_LENGTH, old_hash_cipher_key, 0);
		sha2(new_passwd, MAX_PASS_LENGTH, new_hash_cipher_key, 0);
	}
	
	if (old_hash_cipher_key == new_hash_cipher_key)
		return CTRL_GOOD;
	
	do {
		err = sd_mmc_check(slot);
		if ((SD_MMC_ERR_NO_CARD != err)
		&& (SD_MMC_INIT_ONGOING != err)
		&& (SD_MMC_OK != err)) {
			while (SD_MMC_ERR_NO_CARD != sd_mmc_check(slot)) {
			}
		}
	} while (SD_MMC_OK != err);
	
	nb_blocks = sd_mmc_get_capacity(slot) * (1024 / SD_MMC_BLOCK_SIZE);
	
	for (i = 0; i < nb_blocks / SD_BLOCKS_PER_ACCESS; ++i) {
		if (SD_MMC_OK != sd_mmc_init_read_blocks(slot, i, SD_BLOCKS_PER_ACCESS))
			return CTRL_FAIL;
		if (SD_MMC_OK != sd_mmc_start_read_blocks(src_buf, SD_BLOCKS_PER_ACCESS))
			return CTRL_FAIL;
		if (SD_MMC_OK != sd_mmc_wait_end_of_read_blocks())
			return CTRL_FAIL;
		aes_set_key(&AVR32_AES, (unsigned int *)old_hash_cipher_key);
		ram_aes_ram(change_key ? false : encrypt, SD_MMC_BLOCK_SIZE * SD_BLOCKS_PER_ACCESS / sizeof(unsigned int), (unsigned int *)src_buf, (unsigned int *)dest_buf);
		if (change_key) {
			aes_set_key(&AVR32_AES, (unsigned int *)new_hash_cipher_key);
			ram_aes_ram(true, SD_MMC_BLOCK_SIZE * SD_BLOCKS_PER_ACCESS / sizeof(unsigned int), (unsigned int *)dest_buf, (unsigned int *)src_buf);
		}
		if (SD_MMC_OK != sd_mmc_init_write_blocks(slot, i, SD_BLOCKS_PER_ACCESS))
			return CTRL_FAIL;
		if (SD_MMC_OK != sd_mmc_start_write_blocks(src_buf, SD_BLOCKS_PER_ACCESS))
			return CTRL_FAIL;
		if (SD_MMC_OK != sd_mmc_wait_end_of_write_blocks())
			return CTRL_FAIL;
	}	
	return CTRL_GOOD;
}
Пример #2
0
void test_aes_set_key()
{
	uint8_t key[16] = {
		0x0f,0x15,0x71,0xc9,
		0x47,0xd9,0xe8,0x59,
		0x0c,0xb7,0xad,0xd6,
		0xaf,0x7f,0x67,0x98
	};
	aes_context ctx;
	CU_ASSERT_EQUAL(aes_set_key(NULL, NULL, sizeof(key)*8), PARM_ERROR);
	CU_ASSERT_EQUAL(aes_set_key(NULL, NULL, 124), PARM_ERROR);
	CU_ASSERT_EQUAL(aes_set_key(&ctx, key, sizeof(key)*8), SUCCESS);
	CU_ASSERT_EQUAL(ctx.buf[20], 0xeb369d58);
	CU_ASSERT_EQUAL(ctx.buf[43], 0x76182686);
}
Пример #3
0
Файл: book.c Проект: dgod/yong
int y_im_book_encrypt(const char *s,char *out)
{
    uint8_t data[17]={0},edata[64];
    int len,i,count;
    aes_set_key(key,256);
    len=strlen(s);
    if(len>64)
		return -1;
	count=len/16+(len%16?1:0);
    for(i=0;i<count;i++)
    {
		int part=len-i*16;
		if(part>=16)
		{
			part=16;
			memcpy(data,s+i*16,16);
		}
		else
		{
			memset(data,0,16);
			strcpy((char*)data,s+i*16);
			data[15]=part;
		}
		aes_encrypt(data,edata+i*16);
	}
    l_base64_encode(out,edata,16*count);
    return 0;
}
Пример #4
0
/* Key values given by FIPS-192 Appendix A. */
void
show_key_schedule()
{
	struct aes_context *ctx;
	char *key_str[] = { "AES_128", "AES_192", "AES_256" };
	int key_type[] = { AES_KEY_128, AES_KEY_192, AES_KEY_256 };
	unsigned char key256[] = 
		{ 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe,
		  0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81,
		  0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7,
		  0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4 };
	unsigned char key192[] = 
		{ 0x8e, 0x73, 0xb0, 0xf7, 0xda, 0x0e, 0x64, 0x52,
		  0xc8, 0x10, 0xf3, 0x2b, 0x80, 0x90, 0x79, 0xe5,
		  0x62, 0xf8, 0xea, 0xd2, 0x52, 0x2c, 0x6b, 0x7b };
	unsigned char key128[] =
		{ 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6,
		  0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c };
	unsigned char *keys[] = { key128, key192, key256 };
	int i;

	for (i = 0; i < 3; i++) {
		printf("Testing: %s\n", key_str[i]);
		ctx = aes_context_new();
		aes_set_key(ctx, keys[i], key_type[i]);
		aes_context_free(&ctx);
	}
}
Пример #5
0
/* Encrypt or decrypt data in AES-CTR mode.  (The operations are the
 * same.)  We roll our own here just to double-check that the calls
 * libotr makes to libgcrypt are doing the right thing. */
void aes_ctr_crypt(unsigned char *out, const unsigned char *in, size_t len,
	unsigned char key[16], unsigned char ctrtop[8])
{
    unsigned char ctr[16], encctr[16];
    aes_context aesc;

    aes_set_key(&aesc, key, 128);

    memmove(ctr, ctrtop, 8);
    memset(ctr+8, 0, 8);

    while(len > 0) {
	/* How much to do at a time? */
	size_t i;
	size_t amt = len;
	if (amt > 16) amt = 16;
	aes_encrypt(&aesc, ctr, encctr);
	for(i=0;i<amt;++i) {
	    out[i] = in[i] ^ encctr[i];
	}

	/* Increment the counter */
	for (i=16;i>0;--i) {
	    if (++ctr[i-1] != 0) break;
	}

	out += amt;
	in += amt;
	len -= amt;
    }
}
Пример #6
0
raopcl_t *raopcl_open()
{
	raopcl_data_t *raopcld;
	int16_t sdata[MINIMUM_SAMPLE_SIZE*2];
	data_source_t ds={.type=MEMORY};
	u_int8_t *bp;

	raopcld=malloc(sizeof(raopcl_data_t));
	RAND_seed(raopcld,sizeof(raopcl_data_t));
	memset(raopcld, 0, sizeof(raopcl_data_t));
	if(!RAND_bytes(raopcld->iv, sizeof(raopcld->iv)) || !RAND_bytes(raopcld->key, sizeof(raopcld->key))){
		ERRMSG("%s:RAND_bytes error code=%ld\n",__func__,ERR_get_error());
		return NULL;
	}
	memcpy(raopcld->nv,raopcld->iv,sizeof(raopcld->nv));
	raopcld->volume=VOLUME_DEF;
        aes_set_key(&raopcld->ctx, raopcld->key, 128);
	// prepare a small silent data to send during pause period.
	ds.u.mem.size=MINIMUM_SAMPLE_SIZE*4;
	ds.u.mem.data=sdata;
	memset(sdata,0,sizeof(sdata));
	auds_write_pcm(NULL, raopcld->min_sdata, &bp, &raopcld->min_sdata_size,
		       MINIMUM_SAMPLE_SIZE, &ds);
	return (raopcl_t *)raopcld;
}
Пример #7
0
int AES_xcbc_mac_set_key(aes_context_mac * ctxm, const u_int8_t * key,
			 int keylen)
{
	int ret = 1;
	aes_block kn[3] = {
		{0x01010101, 0x01010101, 0x01010101, 0x01010101},
		{0x02020202, 0x02020202, 0x02020202, 0x02020202},
		{0x03030303, 0x03030303, 0x03030303, 0x03030303},
	};
	aes_set_key(&ctxm->ctx_k1, key, keylen, 0);
	aes_encrypt(&ctxm->ctx_k1, (u_int8_t *) kn[0], (u_int8_t *) kn[0]);
	aes_encrypt(&ctxm->ctx_k1, (u_int8_t *) kn[1], (u_int8_t *) ctxm->k2);
	aes_encrypt(&ctxm->ctx_k1, (u_int8_t *) kn[2], (u_int8_t *) ctxm->k3);
	aes_set_key(&ctxm->ctx_k1, (u_int8_t *) kn[0], 16, 0);
	return ret;
}
Пример #8
0
/**
 * \brief AES interrupt handler
 *
 * \note AES interrupt subroutine in CBC decryption mode.
 *
 */
static void aes_isr_cbc_decrypt_handler(void)
{
	/* When CBC is used the answer must be xored with the previous cipher text
	 * or the initialization vector to reconstruct the plaintext. */

	/* Set AES decryption of a single block in manual mode. */
	aes_configure(AES_DECRYPT, AES_MANUAL, AES_XOR_ON);
	if(byte_count == 0) {
		aes_write_inputdata(init);
	}else {
		aes_write_inputdata((cipher_block_ans + byte_count -
			BLOCK_LENGTH));
	}

	aes_read_outputdata((plain_block_ans + byte_count));
	byte_count += BLOCK_LENGTH;
	if(byte_count >= BLOCK_LENGTH * BLOCK_COUNT) {
		int_end = true;
	}else {
		aes_configure(AES_DECRYPT, AES_AUTO, AES_XOR_OFF);
		/* Load key into AES key memory. */
		aes_set_key(lastsubkey);

		/* Load data into AES state memory. */
		aes_write_inputdata((cipher_block_ans + byte_count));
		// NOTE: since we're in auto mode, the ciphering process will start as
		// soon as the correct number of input data is written. In this case,
		// the process should start when we write the sixteenth byte.
	}
}
Пример #9
0
/**
 * \brief Test AES decryption function.
 *
 * This test decrypts the pre-encrypted data and checks
 * whether it is correct.
 *
 * \param test Current test case.
 */
static void run_aes_decryption_test(const struct test_case *test)
{
	t_key decrypted_data;
	bool  success;

	set_buffer(decrypted_data, 0x00);
	set_buffer(lastsubkey, 0x00);

	/* Call helper function to generate a last subkey for decryption */
	if (!aes_lastsubkey_generate(encryption_key, lastsubkey)) {
		success = false;
		test_assert_true(test, !success,
				"Could not generate last subkey");
	} else {
		/* Configure module for manual decryption */
		aes_software_reset();
		aes_set_key(lastsubkey);
		aes_configure(AES_DECRYPT, AES_MANUAL, AES_XOR_OFF);
		aes_write_inputdata(pre_encrypted_data);

		aes_start();

		do {
			/* Wait until AES is finished or an error occurs. */
		} while (aes_is_busy());

		aes_read_outputdata(decrypted_data);

		/* Verify that the decrypted data is correct */
		success = compare_data_block(decrypted_data, encryption_data);

		test_assert_true(test, success,
				"Decrypted values do not match excepted values");
	}
}
Пример #10
0
int mbedtls_aes_setkey_dec( mbedtls_aes_context *ctx, const unsigned char *key,
                            unsigned int keybits )
{
    int ret_val = 0;
    ret_val = aes_set_key(ctx, key, keybits);
    return( ret_val );
}
Пример #11
0
static int32_t secmon_auth_client(uchar *ucrc)
{
	uint32_t crc;
	struct s_auth *account;
	struct s_client *cur_cl = cur_client();
	unsigned char md5tmp[MD5_DIGEST_LENGTH];

	if (cur_cl->auth)
	{
		int32_t s=memcmp(cur_cl->ucrc, ucrc, 4);
		if (s)
			cs_log("wrong user-crc or garbage !?");
		return !s;
	}
	cur_cl->crypted=1;
	crc=(ucrc[0]<<24) | (ucrc[1]<<16) | (ucrc[2]<<8) | ucrc[3];
	for (account=cfg.account; (account) && (!cur_cl->auth); account=account->next)
		if ((account->monlvl) &&
				(crc==crc32(0L, MD5((unsigned char *)account->usr, strlen(account->usr), md5tmp), MD5_DIGEST_LENGTH)))
		{
			memcpy(cur_cl->ucrc, ucrc, 4);
			aes_set_key(cur_cl, (char *)MD5((unsigned char *)ESTR(account->pwd), strlen(ESTR(account->pwd)), md5tmp));
			if (cs_auth_client(cur_cl, account, NULL))
				return -1;
			cur_cl->auth=1;
		}
	if (!cur_cl->auth)
	{
		cs_auth_client(cur_cl, (struct s_auth *)0, "invalid user");
		return -1;
	}
	return cur_cl->auth;
}
Пример #12
0
void test_aes_decrypt_block()
{
	uint8_t ret_text[16] = {0};
	uint8_t text[16] = {
		0x01,0x23,0x45,0x67,
		0x89,0xab,0xcd,0xef,
		0xfe,0xdc,0xba,0x98,
		0x76,0x54,0x32,0x10
	};
	uint8_t cipher_text[16] = {
		0xff,0x0b,0x84,0x4a,
		0x08,0x53,0xbf,0x7c,
		0x69,0x34,0xab,0x43,
		0x64,0x14,0x8f,0xb9
	};
	uint8_t key[16] = {
		0x0f,0x15,0x71,0xc9,
		0x47,0xd9,0xe8,0x59,
		0x0c,0xb7,0xad,0xd6,
		0xaf,0x7f,0x67,0x98
	};
	aes_context ctx;
	CU_ASSERT_EQUAL(aes_set_key(&ctx, key, sizeof(key)*8), SUCCESS);
	CU_ASSERT_EQUAL(aes_decrypt_block(&ctx, ret_text, cipher_text), SUCCESS);
	int ret = memcmp(ret_text, text, 16);
	CU_ASSERT_EQUAL(memcmp(ret_text, text, 16), 0);
}
Пример #13
0
/**
 * \brief Generate AES sub key
 *
 * Get AES sub key by encryption of dummy data.
 *
 * \param key           Pointer to AES key input.
 * \param last_sub_key  Pointer to AES sub key output.
 *
 */
static bool aes_lastsubkey_generate(t_key key, t_key last_sub_key)
{
	bool keygen_ok;

	aes_software_reset();

	/* Set AES encryption of a single block in manual mode. */
	aes_configure(AES_ENCRYPT, AES_MANUAL, AES_XOR_OFF);

	/* Load key into AES key memory. */
	aes_set_key(key);

	/* Load dummy data into AES state memory. It isn't important what is
	 * written, just that a write cycle occurs. */
	aes_write_inputdata(dummy_data);

	/* Start encryption. */
	aes_start();

	do {
		/* Wait until AES is finished or an error occurs. */
	} while (aes_is_busy());

	/* If not error. */
	if (!aes_is_error()) {
		/* Store the last subkey. */
		aes_get_key(last_sub_key);
		aes_clear_interrupt_flag();
		keygen_ok = true;
	} else {
		aes_clear_error_flag();
		keygen_ok = false;
	}
	return keygen_ok;
}
Пример #14
0
int testAES()
{
    unsigned char keysssss[] =
	{
		0x2b, 0x7e, 0x15, 0x16,
		0x28, 0xae, 0xd2, 0xa6,
		0xab, 0xf7, 0x15, 0x88,
		0x09, 0xcf, 0x4f, 0x3c
	};
   unsigned char input[] =
	{
		0x32, 0x43, 0xf6, 0xa8,
		0x88, 0x5a, 0x30, 0x8d,
		0x31, 0x31, 0x98, 0xa2,
		0xe0, 0x37, 0x07, 0x34,
	};
	printf("Original data   : ");
	print(input);
    aes_set_key(keysssss);
    aes_encrypt(input,input);
    printf("After encrpytion: ");
    print(input);

    aes_decrypt(input,input);
    printf("After decrpytion: ");
    print(input);
}
Пример #15
0
static int cbc_aes_set_key(struct crypto_tfm *tfm, const u8 *in_key,
			   unsigned int key_len)
{
	struct s390_aes_ctx *sctx = crypto_tfm_ctx(tfm);
	int ret;

	ret = need_fallback(key_len);
	if (ret > 0) {
		sctx->key_len = key_len;
		return setkey_fallback_blk(tfm, in_key, key_len);
	}

	switch (key_len) {
	case 16:
		sctx->enc = KMC_AES_128_ENCRYPT;
		sctx->dec = KMC_AES_128_DECRYPT;
		break;
	case 24:
		sctx->enc = KMC_AES_192_ENCRYPT;
		sctx->dec = KMC_AES_192_DECRYPT;
		break;
	case 32:
		sctx->enc = KMC_AES_256_ENCRYPT;
		sctx->dec = KMC_AES_256_DECRYPT;
		break;
	}

	return aes_set_key(tfm, in_key, key_len);
}
Пример #16
0
bool aes_set_key_alloc(struct aes_keys **aes, char *key)
{
	if (!cs_malloc(aes, sizeof(struct aes_keys)))
		return false;
	aes_set_key(*aes, key);
	return true;
}
Пример #17
0
void *crypt_init(const char *pwdfile, int pwdmax)
{
  aes_context *aesctx;
  char *pwd;
  int pwdlen;
  char key[33];//加密密码,最多32字符,256bits

  if (!pwdfile || (pwdmax != 16 && pwdmax != 24 && pwdmax != 32))
    return NULL;

  pwd = loadfile(pwdfile, NULL);
  if (!pwd)
    return NULL;
  
  trim(pwd);
  pwdlen = strlen(pwd);
  if (pwdlen > pwdmax)
  {
    xfree(pwd);
    return NULL;
  }
  memset(key, 0, 33);
  strcpy(key, pwd);
  xfree(pwd);

  aesctx = (aes_context *)xcalloc(1, sizeof(aes_context));
  if (aes_set_key(aesctx, (uint8 *)key, pwdmax*8))
  {
    xfree(aesctx);
    return NULL;
  }

  return aesctx;
}
Пример #18
0
/* Return values: 0 = success, ERR_CIPHER_INIT_FAILURE (fatal), ERR_CIPHER_INIT_WEAK_KEY (non-fatal) */
int CipherInit (int cipher, unsigned char *key, unsigned __int8 *ks)
{
	int retVal = ERR_SUCCESS;

	switch (cipher)
	{
	case AES:
#ifndef TC_WINDOWS_BOOT
		if (aes_encrypt_key256 (key, (aes_encrypt_ctx *) ks) != EXIT_SUCCESS)
			return ERR_CIPHER_INIT_FAILURE;

		if (aes_decrypt_key256 (key, (aes_decrypt_ctx *) (ks + sizeof(aes_encrypt_ctx))) != EXIT_SUCCESS)
			return ERR_CIPHER_INIT_FAILURE;
#else
		if (aes_set_key (key, (length_type) CipherGetKeySize(AES), (aes_context *) ks) != 0)
			return ERR_CIPHER_INIT_FAILURE;
#endif
		break;

	case SERPENT:
		serpent_set_key (key, ks);
		break;
		
	case TWOFISH:
		twofish_set_key ((TwofishInstance *)ks, (const u4byte *)key);
		break;

	default:
		// Unknown/wrong cipher ID
		return ERR_CIPHER_INIT_FAILURE;
	}

	return retVal;
}
Пример #19
0
/* Return values: 0 = success, ERR_CIPHER_INIT_FAILURE (fatal), ERR_CIPHER_INIT_WEAK_KEY (non-fatal) */
int CipherInit (int cipher, unsigned char *key, unsigned __int8 *ks)
{
	int retVal = ERR_SUCCESS;

	switch (cipher)
	{
	case AES:
#ifndef TC_WINDOWS_BOOT
		if (aes_encrypt_key256 (key, (aes_encrypt_ctx *) ks) != EXIT_SUCCESS)
			return ERR_CIPHER_INIT_FAILURE;

		if (aes_decrypt_key256 (key, (aes_decrypt_ctx *) (ks + sizeof(aes_encrypt_ctx))) != EXIT_SUCCESS)
			return ERR_CIPHER_INIT_FAILURE;
#else
		if (aes_set_key (key, (length_type) CipherGetKeySize(AES), (aes_context *) ks) != 0)
			return ERR_CIPHER_INIT_FAILURE;
#endif
		break;

	case SERPENT:
		serpent_set_key (key, CipherGetKeySize(SERPENT) * 8, ks);
		break;
		
	case TWOFISH:
		twofish_set_key ((TwofishInstance *)ks, (const u4byte *)key, CipherGetKeySize(TWOFISH) * 8);
		break;

#ifndef TC_WINDOWS_BOOT
		
	case BLOWFISH:
		/* Deprecated/legacy */
		BlowfishSetKey ((BF_KEY *)ks, CipherGetKeySize(BLOWFISH), key);
		break;

	case CAST:
		/* Deprecated/legacy */
		Cast5SetKey ((CAST_KEY *) ks, CipherGetKeySize(CAST), key);
		break;

	case TRIPLEDES:
		/* Deprecated/legacy */
		TripleDesSetKey (key, CipherGetKeySize (TRIPLEDES), (TDES_KEY *) ks);

		// Verify whether all three DES keys are mutually different
		if (((*((__int64 *) key) ^ *((__int64 *) key+1)) & 0xFEFEFEFEFEFEFEFEULL) == 0
		|| ((*((__int64 *) key+1) ^ *((__int64 *) key+2)) & 0xFEFEFEFEFEFEFEFEULL) == 0
		|| ((*((__int64 *) key) ^ *((__int64 *) key+2)) & 0xFEFEFEFEFEFEFEFEULL) == 0)
			retVal = ERR_CIPHER_INIT_WEAK_KEY;		// Non-fatal error

		break;

#endif	// TC_WINDOWS_BOOT

	default:
		// Unknown/wrong cipher ID
		return ERR_CIPHER_INIT_FAILURE;
	}

	return retVal;
}
Пример #20
0
/**
 * Decrypt Decrypts data based on cipher text, cipher key and IV
 * @param b_input Cipher text
 * @param p_key Cipher key
 * @param p_iv Initialization vector
 * @return Decrypted data
 */
QByteArray AES::decrypt(QByteArray b_input, QByteArray p_key, QByteArray p_iv)
{
    if (b_input.isEmpty()) {
        qDebug() << "Error while decryption: Cannot decrypt empty input";
        return QByteArray();
    }

    QByteArray result;

    int keySize = p_key.size();
    int ivSize = p_iv.size();

    if (keySize != 16 && keySize != 24 && keySize != 32) {
        qDebug() << "Error while decryption: Invalid keysize";
        return QByteArray();
    }

    if (ivSize != 16) {
        qDebug() << "Error while decryption: Invalid keysize";
        return QByteArray();
    }

    // 500KB blocks
    qint64 chunksCount = (b_input.size()/500000) + 1;

    for (int part = 0; part < chunksCount; part++) {
        // Out of range checks
        if (part*500000 > b_input.size()) {
            qDebug() << "Error while decryption: Skipped: Buffer overflow";
            continue;
        }

        QByteArray p_chunk = b_input.mid(part*500000, 500000);

        int inputSize = p_chunk.size();

        unsigned char key[keySize];
        qByteArrayToUCharArray(p_key, key);

        unsigned char iv[ivSize];
        qByteArrayToUCharArray(p_iv, iv);

        unsigned char encrypted[inputSize];
        qByteArrayToUCharArray(p_chunk, encrypted);

        unsigned char decrypted[inputSize]; // Decrypted text

        aes_context context;
        aes_set_key(key, keySize * 8, &context);
        aes_cbc_decrypt(encrypted, decrypted, inputSize, iv, &context);

        QByteArray temp_result = uCharArrayToQByteArray(decrypted, inputSize);

        result.append( temp_result);
    }

    removePadding(&result);
    return result;
}
Пример #21
0
/**
 * Encrypts data based on ciper text, cipher key and IV
 * @param b_input Plaintext
 * @param p_key Cipher key
 * @param p_iv Initialization vector
 * @return Encrypted data
 */
QByteArray AES::encrypt(QByteArray b_input, QByteArray p_key, QByteArray p_iv)
{
    if (b_input.isEmpty()) {
        qDebug() << "Error while encryption: Cannot encrypt empty input";
        return QByteArray();
    }

    addPadding(&b_input);

    QByteArray result;

    int keySize = p_key.size();
    int ivSize = p_iv.size();

    if (keySize != 16 && keySize != 24 && keySize != 32) {
        qDebug() << "Error while encryption: Invalid keysize";
        return QByteArray();
    }

    if (ivSize != 16) {
        qDebug() << "Error while encryption: Invalid keysize";
        return QByteArray();
    }

    // Chunks have to stay < 1MB (1.050MB to be exactly)
    qint64 chunksCount = (b_input.size()/500000) + 1;

    for (int part = 0; part < chunksCount; part++) {
        // Out of range checks
        if (part*500000 > b_input.size()) {
            qDebug() << "Error while encryption: Skipped: Buffer overflow";
            continue;
        }

        QByteArray p_chunk = b_input.mid(part*500000, 500000);
        int inputSize = p_chunk.size();

        unsigned char key[keySize];
        qByteArrayToUCharArray(p_key, key);

        unsigned char iv[ivSize];
        qByteArrayToUCharArray(p_iv, iv);

        unsigned char decrypted[inputSize];
        qByteArrayToUCharArray(p_chunk, decrypted);

        unsigned char encrypted[inputSize]; // Encrypted text

        aes_context context;
        aes_set_key(key, keySize * 8, &context);
        aes_cbc_encrypt(decrypted, encrypted, inputSize, iv, &context);

        result.append( uCharArrayToQByteArray(encrypted, inputSize));
    }

    result.prepend(p_iv);
    return result;
}
Пример #22
0
bool CCCrypto::aes_decrypt(const char *pBegin, const char *pEnd, const std::string &sKey ,char* pResult,int iBufferSize)
{
	aes_context ctx; 
	if (aes_set_key(&ctx, (unsigned char *)sKey.c_str(), sKey.size() * 8) != 0)
	{
		return false;
	}
	return CCCrypto::cbc_decrypt(pBegin, pEnd, (CCCrypto::block_decrypt_func)::aes_decrypt, 16, &ctx, pResult, iBufferSize);
}
Пример #23
0
int main(int argc, char**argv)
{
	int n, opt, port = 0, accountok = 0;
	struct sockaddr_in servaddr;
	socklen_t len;
	char mbuf[1000];
	unsigned char md5tmp[MD5_DIGEST_LENGTH];
	
	while ((opt = getopt(argc, argv, "a:p:")) != -1) {
		switch (opt) {
			case 'a': {
				char *ptr = strtok(optarg, ":");
				cs_strncpy((char *)&cl_user, ptr, sizeof(cl_user));
				ptr = strtok(NULL, ":");
				if(ptr) {
					cs_strncpy((char *)&cl_passwd, ptr, sizeof(cl_passwd));
					accountok = 1;
				}
				break;
			}
			case 'p':
				port = atoi(optarg);
				break;
			default:
				fprintf(stderr, "Usage: %s -a <user>:<password> -p <port>\n", argv[0]);
				exit(0);
		}
	}
	if(port == 0 || accountok == 0){
		fprintf(stderr, "Usage: %s -a <user>:<password> -p <port>\n", argv[0]);
		exit(0);
	}
	
	cl_sockfd = socket(AF_INET,SOCK_DGRAM,0);
	
	bzero(&servaddr,sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(port);
	bind(cl_sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
	
	aes_set_key(&cl_aes_keys, (char *) MD5(cl_passwd, strlen((char *)cl_passwd), md5tmp));
	
	for (;;){
		len = sizeof(cl_socket);
		n = recvfrom(cl_sockfd,mbuf,sizeof(mbuf),0,(struct sockaddr *)&cl_socket,&len);
		
		camd35_recv(mbuf, n);     
		
		if(mbuf[0] == 0 || mbuf[0] == 3) {
			camd35_process_ecm(mbuf, n);
		} else {
			cs_log("unknown/not implemented camd35 command! (%d) n=%d", mbuf[0], n);
		}
	}
}
Пример #24
0
/**
 * Return a newly allocated counter-mode AES128 cipher implementation,
 * using the 128-bit key <b>key</b> and the 128-bit IV <b>iv</b>.
 */
aes_cnt_cipher_t*
aes_new_cipher(const char *key, const char *iv)
{
  aes_cnt_cipher_t* result = tor_malloc_zero(sizeof(aes_cnt_cipher_t));

  aes_set_key(result, key, 128);
  aes_set_iv(result, iv);

  return result;
}
Пример #25
0
/**
 * Return a newly allocated counter-mode AES128 cipher implementation,
 * using the 128-bit key <b>key</b> and the 128-bit IV <b>iv</b>.
 */
aes_cnt_cipher_t*
aes_new_cipher(const uint8_t *key, const uint8_t *iv, int bits)
{
  aes_cnt_cipher_t* result = tor_malloc_zero(sizeof(aes_cnt_cipher_t));

  aes_set_key(result, key, bits);
  aes_set_iv(result, iv);

  return result;
}
Пример #26
0
/*----------------------- AES API --------------------------------------------*/
void hal_aes_setup(bool decrypt, aes_modes_t mode, uint8_t *keyin, uint8_t *ivin)
{
    aes_set_key(keyin);

    // Not used in LE1, included to prevent compile-warnings------ |
    decrypt = decrypt; 	                                        // |
    mode = mode;                                                // |
    ivin = ivin;                                                // |
    //-------------------------------------------------------------|
}
Пример #27
0
bool CCCrypto::aes_encrypt(const char *pBegin, const char *pEnd, const std::string &sKey, std::string &sResult)
{
	aes_context ctx;
	if (aes_set_key(&ctx, (unsigned char *)sKey.c_str(), sKey.size() * 8) != 0)
	{
		return false;
	}

	return CCCrypto::cbc_encrypt(pBegin, pEnd, (CCCrypto::block_encrypt_func)::aes_encrypt, 16, &ctx, sResult);
}
Пример #28
0
int main(int argc, char* argv[])
{
	aes_context_t aes_ctx;
	aes_init(&aes_ctx);
	aes_set_key(&aes_ctx, s_key);
	//aes_encrypt(&aes_ctx, s_in, s_enc);
	//aes_decrypt(&aes_ctx, s_enc, s_dec);
	aes_encrypt_ctr(&aes_ctx, s_in, s_enc, sizeof(s_in), s_iv);
	aes_decrypt_ctr(&aes_ctx, s_enc, s_dec, sizeof(s_in), s_iv);
	return 0;
}
Пример #29
0
void encrypt_IOS(IOS *ios)
{
	u8 key[16];
	get_title_key(ios->ticket, key);
	aes_set_key(key);
	
	int i;
	for (i = 0; i < ios->content_count; i++)
	{
		encrypt_buffer(i, ios->decrypted_buffer[i], ios->encrypted_buffer[i], ios->buffer_size[i]);
	}
}
/*******************************************************************************
**
** Function         smp_encrypt_data
**
** Description      This function is called to generate passkey.
**
** Returns          void
**
*******************************************************************************/
BOOLEAN smp_encrypt_data (UINT8 *key, UINT8 key_len,
                          UINT8 *plain_text, UINT8 pt_len,
                          tSMP_ENC *p_out)
{
    aes_context     ctx;
    UINT8           *p_start = NULL;
    UINT8           *p = NULL;
    UINT8           *p_rev_data = NULL;    /* input data in big endilan format */
    UINT8           *p_rev_key = NULL;     /* input key in big endilan format */
    UINT8           *p_rev_output = NULL;  /* encrypted output in big endilan format */

    SMP_TRACE_DEBUG0 ("smp_encrypt_data");
    if ( (p_out == NULL ) || (key_len != SMP_ENCRYT_KEY_SIZE) )
    {
        BTM_TRACE_ERROR0 ("smp_encrypt_data Failed");
        return(FALSE);
    }

    if ((p_start = (UINT8 *)GKI_getbuf((SMP_ENCRYT_DATA_SIZE*4))) == NULL)
    {
        BTM_TRACE_ERROR0 ("smp_encrypt_data Failed unable to allocate buffer");
        return(FALSE);
    }

    if (pt_len > SMP_ENCRYT_DATA_SIZE)
        pt_len = SMP_ENCRYT_DATA_SIZE;

    memset(p_start, 0, SMP_ENCRYT_DATA_SIZE * 4);
    p = p_start;
    ARRAY_TO_STREAM (p, plain_text, pt_len); /* byte 0 to byte 15 */
    p_rev_data = p = p_start + SMP_ENCRYT_DATA_SIZE; /* start at byte 16 */
    REVERSE_ARRAY_TO_STREAM (p, p_start, SMP_ENCRYT_DATA_SIZE);  /* byte 16 to byte 31 */
    p_rev_key = p; /* start at byte 32 */
    REVERSE_ARRAY_TO_STREAM (p, key, SMP_ENCRYT_KEY_SIZE); /* byte 32 to byte 47 */

    smp_debug_print_nbyte_little_endian(key, (const UINT8 *)"Key", SMP_ENCRYT_KEY_SIZE);
    smp_debug_print_nbyte_little_endian(p_start, (const UINT8 *)"Plain text", SMP_ENCRYT_DATA_SIZE);
    p_rev_output = p;
    aes_set_key(p_rev_key, SMP_ENCRYT_KEY_SIZE, &ctx);
    aes_encrypt(p_rev_data, p, &ctx);  /* outputs in byte 48 to byte 63 */

    p = p_out->param_buf;
    REVERSE_ARRAY_TO_STREAM (p, p_rev_output, SMP_ENCRYT_DATA_SIZE);
    smp_debug_print_nbyte_little_endian(p_out->param_buf, (const UINT8 *)"Encrypted text", SMP_ENCRYT_KEY_SIZE);

    p_out->param_len = SMP_ENCRYT_KEY_SIZE;
    p_out->status = HCI_SUCCESS;
    p_out->opcode =  HCI_BLE_ENCRYPT;

    GKI_freebuf(p_start);

    return(TRUE);
}