1 int do_crypt(char *outfile) 2 { 3 unsigned char outbuf[1024]; 4 int outlen, tmplen; 5 /* Bogus key and IV: we'd normally set these from 6 * another source. 7 */ 8 unsigned char key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; 9 unsigned char iv[] = {1,2,3,4,5,6,7,8}; 10 char intext[] = "Some Crypto Text"; 11 EVP_CIPHER_CTX *ctx; 12 FILE *out; 13 14 ctx = EVP_CIPHER_CTX_new(); 15 EVP_EncryptInit_ex(ctx, EVP_idea_cbc(), NULL, key, iv); 16 17 if(!EVP_EncryptUpdate(ctx, outbuf, &outlen, intext, strlen(intext))) 18 { 19 /* Error */ 20 return 0; 21 } 22 /* Buffer passed to EVP_EncryptFinal() must be after data just 23 * encrypted to avoid overwriting it. 24 */ 25 if(!EVP_EncryptFinal_ex(ctx, outbuf + outlen, &tmplen)) 26 { 27 /* Error */ 28 return 0; 29 } 30 outlen += tmplen; 31 EVP_CIPHER_CTX_free(ctx); 32 /* Need binary mode for fopen because encrypted data is 33 * binary data. Also cannot use strlen() on it because 34 * it won't be null terminated and may contain embedded 35 * nulls. 36 */ 37 out = fopen(outfile, "wb"); 38 fwrite(outbuf, 1, outlen, out); 39 fclose(out); 40 return 1; 41 }
1 int do_crypt(FILE *in, FILE *out, int do_encrypt) 2 { 3 /* Allow enough space in output buffer for additional block */ 4 unsigned char inbuf[1024], outbuf[1024 + EVP_MAX_BLOCK_LENGTH]; 5 int inlen, outlen; 6 EVP_CIPHER_CTX *ctx; 7 /* Bogus key and IV: we'd normally set these from 8 * another source. 9 */ 10 unsigned char key[] = "0123456789abcdeF"; 11 unsigned char iv[] = "1234567887654321"; 12 13 /* Don't set key or IV right away; we want to check lengths */ 14 ctx = EVP_CIPHER_CTX_new(); 15 EVP_CipherInit_ex(&ctx, EVP_aes_128_cbc(), NULL, NULL, NULL, 16 do_encrypt); 17 OPENSSL_assert(EVP_CIPHER_CTX_key_length(ctx) == 16); 18 OPENSSL_assert(EVP_CIPHER_CTX_iv_length(ctx) == 16); 19 20 /* Now we can set key and IV */ 21 EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, do_encrypt); 22 23 for(;;) 24 { 25 inlen = fread(inbuf, 1, 1024, in); 26 if (inlen <= 0) break; 27 if(!EVP_CipherUpdate(ctx, outbuf, &outlen, inbuf, inlen)) 28 { 29 /* Error */ 30 EVP_CIPHER_CTX_free(ctx); 31 return 0; 32 } 33 fwrite(outbuf, 1, outlen, out); 34 } 35 if(!EVP_CipherFinal_ex(ctx, outbuf, &outlen)) 36 { 37 /* Error */ 38 EVP_CIPHER_CTX_free(ctx); 39 return 0; 40 } 41 fwrite(outbuf, 1, outlen, out); 42 43 EVP_CIPHER_CTX_free(ctx); 44 return 1; 45 }
// openssl.org/docs/man1.1.0/man3/EVP_EncryptInit_ex.html