Beispiel #1
0
void aes_gcm_encrypt(void)
{
    EVP_CIPHER_CTX *ctx;
    int outlen, tmplen;
    unsigned char outbuf[1024];
    printf("AES GCM Encrypt:\n");
    printf("Plaintext:\n");
    BIO_dump_fp(stdout, gcm_pt, sizeof(gcm_pt));
    ctx = EVP_CIPHER_CTX_new();
    /* Set cipher type and mode */
    EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
    /* Set IV length if default 96 bits is not appropriate */
    EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, sizeof(gcm_iv), NULL);
    /* Initialise key and IV */
    EVP_EncryptInit_ex(ctx, NULL, NULL, gcm_key, gcm_iv);
    /* Zero or more calls to specify any AAD */
    EVP_EncryptUpdate(ctx, NULL, &outlen, gcm_aad, sizeof(gcm_aad));
    /* Encrypt plaintext */
    EVP_EncryptUpdate(ctx, outbuf, &outlen, gcm_pt, sizeof(gcm_pt));
    /* Output encrypted block */
    printf("Ciphertext:\n");
    BIO_dump_fp(stdout, outbuf, outlen);
    /* Finalise: note get no output for GCM */
    EVP_EncryptFinal_ex(ctx, outbuf, &outlen);
    /* Get tag */
    EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, 16, outbuf);
    /* Output tag */
    printf("Tag:\n");
    BIO_dump_fp(stdout, outbuf, 16);
    EVP_CIPHER_CTX_free(ctx);
}
Beispiel #2
0
void aes_gcm_decrypt(void)
{
    EVP_CIPHER_CTX *ctx;
    int outlen, tmplen, rv;
    unsigned char outbuf[1024];
    printf("AES GCM Derypt:\n");
    printf("Ciphertext:\n");
    BIO_dump_fp(stdout, gcm_ct, sizeof(gcm_ct));
    ctx = EVP_CIPHER_CTX_new();
    /* Select cipher */
    EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL);
    /* Set IV length, omit for 96 bits */
    EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, sizeof(gcm_iv), NULL);
    /* Specify key and IV */
    EVP_DecryptInit_ex(ctx, NULL, NULL, gcm_key, gcm_iv);
    /* Zero or more calls to specify any AAD */
    EVP_DecryptUpdate(ctx, NULL, &outlen, gcm_aad, sizeof(gcm_aad));
    /* Decrypt plaintext */
    EVP_DecryptUpdate(ctx, outbuf, &outlen, gcm_ct, sizeof(gcm_ct));
    /* Output decrypted block */
    printf("Plaintext:\n");
    BIO_dump_fp(stdout, outbuf, outlen);
    /* Set expected tag value. */
    EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, sizeof(gcm_tag), 
                        (void *)gcm_tag);
    /* Finalise: note get no output for GCM */
    rv = EVP_DecryptFinal_ex(ctx, outbuf, &outlen);
    /*
     * Print out return value. If this is not successful authentication
     * failed and plaintext is not trustworthy.
     */
    printf("Tag Verify %s\n", rv > 0 ? "Successful!" : "Failed!");
    EVP_CIPHER_CTX_free(ctx);
}
Beispiel #3
0
static void ctr_BCC_block(DRBG_CTR_CTX *cctx, unsigned char *out,
				const unsigned char *in)
	{
	int i;
	for (i = 0; i < 16; i++)
		out[i] ^= in[i];
	AES_encrypt(out, out, &cctx->df_ks);
#if 0
fprintf(stderr, "BCC in+out\n");
BIO_dump_fp(stderr, in, 16);
BIO_dump_fp(stderr, out, 16);
#endif
	}
Beispiel #4
0
void test_encrypt_decrypt_result(unsigned char *plaintext, unsigned char *key, unsigned char *iv)
{
    /* Buffer for ciphertext. Ensure the buffer is long enough for the
     * ciphertext which may be longer than the plaintext, dependant on the
     * algorithm and mode
     */
    unsigned char ciphertext[1024];

    /* Buffer for the decrypted text */
    unsigned char decryptedtext[1024];

    int decryptedtext_len, ciphertext_len;

    clock_t start = clock();

    /* Encrypt the plaintext */
    ciphertext_len = encrypt(plaintext, static_cast<int>(strlen((char *)plaintext)), key, iv, ciphertext);

    /* Do something useful with the ciphertext here */
    printf("Ciphertext(length: %d) is:\n", ciphertext_len);
    BIO_dump_fp (stdout, (const char *)ciphertext, ciphertext_len);
    printf("\n\n");

    /* Decrypt the ciphertext */
    decryptedtext_len = decrypt(ciphertext, ciphertext_len, key, iv, decryptedtext);

    /* Add a NULL terminator. We are expecting printable text */
    decryptedtext[decryptedtext_len] = '\0';

    /* Show the decrypted text */
    printf("Decrypted text(length: %d) is:\n", decryptedtext_len);
    printf("%s\n\n", decryptedtext);

    std::cout << "Elapsed time: " << static_cast<double>(clock() - start) /CLOCKS_PER_SEC << "s.\n\n" << std::endl;
}
Beispiel #5
0
static void ctr_Update(DRBG_CTX *dctx,
		const unsigned char *in1, size_t in1len,
		const unsigned char *in2, size_t in2len,
		const unsigned char *nonce, size_t noncelen)
	{
	DRBG_CTR_CTX *cctx = &dctx->d.ctr;
	/* ks is already setup for correct key */
	inc_128(cctx);
	AES_encrypt(cctx->V, cctx->K, &cctx->ks);
	/* If keylen longer than 128 bits need extra encrypt */
	if (cctx->keylen != 16)
		{
		inc_128(cctx);
		AES_encrypt(cctx->V, cctx->K + 16, &cctx->ks);
		}
	inc_128(cctx);
	AES_encrypt(cctx->V, cctx->V, &cctx->ks);
	/* If 192 bit key part of V is on end of K */
	if (cctx->keylen == 24)
		{
		memcpy(cctx->V + 8, cctx->V, 8);
		memcpy(cctx->V, cctx->K + 24, 8);
		}

	if (dctx->flags & DRBG_FLAG_CTR_USE_DF)
		{
		/* If no input reuse existing derived value */
		if (in1 || nonce || in2)
			ctr_df(cctx, in1, in1len, nonce, noncelen, in2, in2len);
		/* If this a reuse input in1len != 0 */
		if (in1len)
			ctr_XOR(cctx, cctx->KX, dctx->seedlen);
		}
	else
		{
		ctr_XOR(cctx, in1, in1len);
		ctr_XOR(cctx, in2, in2len);
		}

	AES_set_encrypt_key(cctx->K, dctx->strength, &cctx->ks);
#if 0
fprintf(stderr, "K+V after update is:\n");
BIO_dump_fp(stderr, cctx->K, cctx->keylen);
BIO_dump_fp(stderr, cctx->V, 16);
#endif
	}
Beispiel #6
0
/* INFO: Setting it up
   
         The code below sets up the program. In this example we are going to
         take a simple message("The quick brown fox jumps over the lazy dog"),
         and then encrypt it using a predefined key and IV. In this example the
         key and IV have been hard coded in - in a real situation you would
         never do this! Following encryption we will then decrypt the resulting
         ciphertext, and(hopefully!) end up with the message we first started
         with. This program expects two functions to be defined: "encrypt" and
         "decrypt". We will define those further down the page. */
int aes_main(void) {
	/* INFO: Set up the key and iv. Do I need to say to not hard code these
	         in a real application? :-) */

	/* INFO: A 256 bit key */
	unsigned char * key =
		(unsigned char *)"01234567890123456789012345678901";

	/* INFO: A 128 bit IV */
	unsigned char * iv =(unsigned char *)"01234567890123456";

	/* INFO: Message to be encrypted */
	unsigned char *plaintext =
		(unsigned char *)"The quick brown fox jumps over the lazy dog";

	/* INFO: Buffer for ciphertext. Ensure the buffer is long enough for
	         the ciphertext which may be longer than the plaintext,
	         dependant on the algorithm and mode */
	unsigned char ciphertext[128];

	/* INFO: Buffer for the decrypted text */
	unsigned char decryptedtext[128];

	int decryptedtext_len, ciphertext_len;

	/* INFO: Initialise the library */
	ERR_load_crypto_strings();
	OpenSSL_add_all_algorithms();
	/* TODO: deprecated. Ude OPENSSL_init_crypto instead of it. */
	OPENSSL_config(NULL);

	/* INFO: Encrypt the plaintext */
	ciphertext_len = encrypt(plaintext, strlen((char *)plaintext), key,
		iv, ciphertext);

	/* INFO: Do something useful with the ciphertext here */
	printf("Ciphertext is:\n");
	BIO_dump_fp(stdout,(const char *)ciphertext, ciphertext_len);

	/* INFO: Decrypt the ciphertext */
	decryptedtext_len = decrypt(ciphertext, ciphertext_len, key, iv,
		decryptedtext);

	/* INFO: Add a NULL terminator. We are expecting printable text */
	decryptedtext[decryptedtext_len] = '\0';

	/* INFO: Show the decrypted text */
	printf("Decrypted text is:\n");
	printf("%s\n", decryptedtext);

	/* INFO: Clean up */
	EVP_cleanup();
	ERR_free_strings();

	return 0;
}
Beispiel #7
0
void GenerateKey()
{
    // Key and IV values.
    const char *pcCode = "543210";

    unsigned char acKey[EVP_MAX_KEY_LENGTH + 1];
    unsigned char acIV[EVP_MAX_IV_LENGTH + 1];

    // Load all the encryption ciphers and lookup the one we want to use.
    OpenSSL_add_all_algorithms();
    const EVP_CIPHER *cipher = EVP_get_cipherbyname("aes-128-xts");
    const EVP_MD *digest = EVP_get_digestbyname("sha1");

    // Generate HashKey for the password.
    int nrounds = 2;
    int nCnt = EVP_BytesToKey(cipher, digest, NULL, (const unsigned char *) pcCode, strlen(pcCode), nrounds, acKey, acIV);

    std::cout << "nCnt: " << nCnt << " key length: " << EVP_MAX_KEY_LENGTH << " iv length: " << EVP_MAX_IV_LENGTH << std::endl;
    BIO_dump_fp(stdout, (const char*)acKey, nCnt);
    printf("\n\n");
    BIO_dump_fp(stdout, (const char*)acIV, EVP_MAX_IV_LENGTH);
}
Beispiel #8
0
int main(int argc, char **argv)  
{  
        unsigned char *plain;
	int i;
	pt_len = atoi(argv[1]);
	plain = (unsigned char *)malloc(sizeof(unsigned char)*pt_len);
	printf("pt_len:%d\n",pt_len);
	for(i=0;i<pt_len;i++)
	   plain[i]=gcm_pte[i%16];
        gcm_pt = plain;
//        printf("plain size: %d gcm_pt size: %d\n",sizeof(gcm_pte),sizeof(plain));
	
	cycle_t tStart, tEnd;
	
	RDTSC_LL(tStart);
	
	aes_gcm_encrypt();  
        
	RDTSC_LL(tEnd);
	printf("Encrypt time: %lf us\n",(tEnd-tStart)/2600.0);
	
	RDTSC_LL(tStart);
	aes_gcm_decrypt();
	RDTSC_LL(tEnd);
	printf("tStart:%ld\n",tStart);
    	printf("tEnd  :%ld\n",tEnd);
    	printf("Decrypt time: %lf us\n",(tEnd-tStart)/2600.0); 

	printf("orignal plain text:");
	printf("encrypt text:\n");
	BIO_dump_fp(stdout, enbuf, pt_len);
	printf("plain text:\n");
	BIO_dump_fp(stdout, gcm_pt, pt_len);
	printf("decrypt text:\n");
	BIO_dump_fp(stdout, debuf, pt_len); 
} 
Beispiel #9
0
void task_body (void *cookie)
{
        int ciphertext_len; 
        unsigned char key[] = "01234567890123456789012345678901";
	unsigned char iv[] = "01234567890123456";
        unsigned char plaintext[] = "the quick brown fox jumps over the lazy dog";
        unsigned char ciphertext[128];
	// init library
	ERR_load_crypto_strings();
	OpenSSL_add_all_algorithms();
	OPENSSL_config(NULL);  
	// notify switch to userspace
	//rt_task_set_mode(T_WARNSW, 0, NULL); 
	#ifdef DEBUG
		rt_printf ("Task Start\n");
		delay(1000);
	#endif
	for(;;) {
		// poll input pin for trigger
		if(digitalRead(INPUT_PIN) != 0){
			//start task marker
			digitalWrite(0, 1);
			#ifdef DEBUG
				rt_printf ("Trigger\n");
			#endif
			// when triggered, do security task
			// alternatively, use delay or sleep
			//rt_task_sleep(100000);
			//delay(100);
			ciphertext_len = encrypt(plaintext, strlen(plaintext), key, iv, ciphertext);
			#ifdef DEBUG
				rt_printf("Ciphertext is %d:\n", ciphertext_len);
				BIO_dump_fp(stdout, ciphertext, ciphertext_len);
			#endif
			digitalWrite(0, 0);
			while(digitalRead(INPUT_PIN!=0)) {
				// wait for response
			}
		}
		else{
			// debug delay or sleep
			//delay(1);
			//rt_task_sleep(1);
		}
	}
	EVP_cleanup();
	ERR_free_strings();
}
Beispiel #10
0
static void ctr_df(DRBG_CTR_CTX *cctx,
			const unsigned char *in1, size_t in1len,
			const unsigned char *in2, size_t in2len,
			const unsigned char *in3, size_t in3len)
	{
	size_t inlen;
	unsigned char *p = cctx->bltmp;
	static unsigned char c80 = 0x80;

	ctr_BCC_init(cctx);
	if (!in1)
		in1len = 0;
	if (!in2)
		in2len = 0;
	if (!in3)
		in3len = 0;
	inlen = in1len + in2len + in3len;
	/* Initialise L||N in temporary block */
	*p++ = (inlen >> 24) & 0xff;
	*p++ = (inlen >> 16) & 0xff;
	*p++ = (inlen >> 8) & 0xff;
	*p++ = inlen & 0xff;
	/* NB keylen is at most 32 bytes */
	*p++ = 0;
	*p++ = 0;
	*p++ = 0;
	*p = (unsigned char)((cctx->keylen + 16) & 0xff);
	cctx->bltmp_pos = 8;
	ctr_BCC_update(cctx, in1, in1len);
	ctr_BCC_update(cctx, in2, in2len);
	ctr_BCC_update(cctx, in3, in3len);
	ctr_BCC_update(cctx, &c80, 1);
	ctr_BCC_final(cctx);
	/* Set up key K */
	AES_set_encrypt_key(cctx->KX, cctx->keylen * 8, &cctx->df_kxks);
	/* X follows key K */
	AES_encrypt(cctx->KX + cctx->keylen, cctx->KX, &cctx->df_kxks);
	AES_encrypt(cctx->KX, cctx->KX + 16, &cctx->df_kxks);
	if (cctx->keylen != 16)
		AES_encrypt(cctx->KX + 16, cctx->KX + 32, &cctx->df_kxks);
#if 0
fprintf(stderr, "Output of ctr_df:\n");
BIO_dump_fp(stderr, cctx->KX, cctx->keylen + 16);
#endif
	}
int main(){

	// printf("Testing RSA functions with EVP_DigestSign and EVP_DigestVerify\n");
	char response[1000];

	OpenSSL_add_all_algorithms();

	/* Sign and Verify HMAC keys */
	EVP_PKEY *skey = NULL, *vkey = NULL;
	
	int rc = make_keys(&skey, &vkey);
	assert(rc == 0);
	if(rc != 0)
	exit(1);

	assert(skey != NULL);
	if(skey == NULL)
	exit(1);

	assert(vkey != NULL);
	if(vkey == NULL)
	exit(1);
	DH *privkey=createPubkey();
	//char *dh_param_pub=BN_bn2dec(privkey->pub_key); 
	const byte *msg = BN_bn2dec(privkey->pub_key);//msg contains dh_param_pub
	printf("DH public key Generated:%s \n",msg);
	byte* sig = NULL;
	size_t slen = 0;

	
	
	sock=establishConnection();
	int i=0;
	//int count = split(data1, "$", tokens);
	sendMsg(sock,msg);
	
	 if( recv(sock, response , 6000 , 0) < 0)
	{
	puts("recv failed");
	}
	printf("Recieved Successfully:length of data=%d \n",(int)strlen(response));
	printf("DH public key Recieved:%s \n",response);
	//printf("Sent Successfully: length of data=%d\n",sumSend);
	char *pubkey=response;
	struct sec s=performDH(pubkey,privkey);
	printf("Shared key is:%s\n ",s.value);
	puts("The DH Key is");
	BIO_dump_fp(stdout, s.value, s.length);
	//free(msg);
	verifySignature(sock,msg);
	if(sig)
	OPENSSL_free(sig);

	if(skey)
	EVP_PKEY_free(skey);

	if(vkey)
	EVP_PKEY_free(vkey);
	
	return 0;
}
Beispiel #12
0
int EVP_PBE_scrypt(const char *pass, size_t passlen,
                   const unsigned char *salt, size_t saltlen,
                   uint64_t N, uint64_t r, uint64_t p, uint64_t maxmem,
                   unsigned char *key, size_t keylen)
{
    int rv = 0;
    unsigned char *B;
    uint32_t *X, *V, *T;
    uint64_t i, Blen, Vlen;

    /* Sanity check parameters */
    /* initial check, r,p must be non zero, N >= 2 and a power of 2 */
    if (r == 0 || p == 0 || N < 2 || (N & (N - 1)))
        return 0;
    /* Check p * r < SCRYPT_PR_MAX avoiding overflow */
    if (p > SCRYPT_PR_MAX / r)
        return 0;

    /*
     * Need to check N: if 2^(128 * r / 8) overflows limit this is
     * automatically satisfied since N <= UINT64_MAX.
     */

    if (16 * r <= LOG2_UINT64_MAX) {
        if (N >= (1UL << (16 * r)))
            return 0;
    }

    /* Memory checks: check total allocated buffer size fits in uint64_t */

    /*
     * B size in section 5 step 1.S
     * Note: we know p * 128 * r < UINT64_MAX because we already checked
     * p * r < SCRYPT_PR_MAX
     */
    Blen = p * 128 * r;

    /*
     * Check 32 * r * (N + 2) * sizeof(uint32_t) fits in uint64_t.
     * This is combined size V, X and T (section 4)
     */
    i = UINT64_MAX / (32 * sizeof(uint32_t));
    if (N + 2 > i / r)
        return 0;
    Vlen = 32 * r * (N + 2) * sizeof(uint32_t);

    /* check total allocated size fits in uint64_t */
    if (Blen > UINT64_MAX - Vlen)
        return 0;

    if (maxmem == 0)
        maxmem = SCRYPT_MAX_MEM;

    if (Blen + Vlen > maxmem) {
        EVPerr(EVP_F_EVP_PBE_SCRYPT, EVP_R_MEMORY_LIMIT_EXCEEDED);
        return 0;
    }

    /* If no key return to indicate parameters are OK */
    if (key == NULL)
        return 1;

    B = OPENSSL_malloc(Blen + Vlen);
    if (B == NULL)
        return 0;
    X = (uint32_t *)(B + Blen);
    T = X + 32 * r;
    V = T + 32 * r;
    if (PKCS5_PBKDF2_HMAC(pass, passlen, salt, saltlen, 1, EVP_sha256(),
                          Blen, B) == 0)
        goto err;

    for (i = 0; i < p; i++)
        scryptROMix(B + 128 * r * i, r, N, X, T, V);

    if (PKCS5_PBKDF2_HMAC(pass, passlen, B, Blen, 1, EVP_sha256(),
                          keylen, key) == 0)
        goto err;
    rv = 1;
#ifdef SCRYPT_DEBUG
    fprintf(stderr, "scrypt parameters:\n");
    fprintf(stderr, "N=%lu, p=%lu, r=%lu\n", N, p, r);
    fprintf(stderr, "Salt:\n");
    BIO_dump_fp(stderr, (char *)salt, saltlen);
    fprintf(stderr, "Password:\n");
    BIO_dump_fp(stderr, (char *)pass, passlen);
    fprintf(stderr, "Key:\n");
    BIO_dump_fp(stderr, (char *)key, keylen);
#endif
 err:
    OPENSSL_clear_free(B, Blen + Vlen);
    return rv;
}
Beispiel #13
0
void pr_data(FILE *fp, const char *name, char *data, int len)
{
	fprintf(fp, "%s:\n", name);
	BIO_dump_fp(fp, (void *)data, len);
}
Beispiel #14
0
void evp_dump(unsigned char *ciphertext, int ciphertext_len)
{
  BIO_dump_fp (stdout, ciphertext, ciphertext_len);
}