Commit 18135561 authored by Dr. Stephen Henson's avatar Dr. Stephen Henson
Browse files

Add examples to EVP_EncryptInit manual page.

parent b49a5b2d
Loading
Loading
Loading
Loading
+89 −0
Original line number Diff line number Diff line
@@ -367,6 +367,95 @@ Set the effective key length used in RC2:
 int key_bits;
 EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_SET_RC2_KEY_BITS, key_bits, NULL);

Encrypt a string using blowfish:

 int do_crypt(char *outfile)
 	{
	unsigned char outbuf[1024];
	int outlen, tmplen;
	/* Bogus key and IV: we'd normally set these from
	 * another source.
	 */
	unsigned char key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
	unsigned char iv[] = {1,2,3,4,5,6,7,8};
	char intext[] = "Some Crypto Text";
	EVP_CIPHER_CTX ctx;
	FILE *out;
	EVP_EncryptInit(&ctx, EVP_bf_cbc(), key, iv);

	if(!EVP_EncryptUpdate(&ctx, outbuf, &outlen, intext, strlen(intext)))
		{
		/* Error */
		return 0;
		}
	/* Buffer passed to EVP_EncryptFinal() must be after data just
	 * encrypted to avoid overwriting it.
	 */
	if(!EVP_EncryptFinal(&ctx, outbuf + outlen, &tmplen))
		{
		/* Error */
		return 0;
		}
	outlen += tmplen;
	EVP_CIPHER_CTX_cleanup(&ctx);
	/* Need binary mode for fopen because encrypted data is
	 * binary data. Also cannot use strlen() on it because
         * it wont be null terminated and may contain embedded
	 * nulls.
	 */
	out = fopen(outfile, "wb");
	fwrite(outbuf, 1, outlen, out);
	fclose(out);
	return 1;
	}

The ciphertext from the above example can be decrypted using the B<openssl>
utility with the command line:
 
 S<openssl bf -in cipher.bin -K 000102030405060708090A0B0C0D0E0F -iv 0102030405060708 -d>

General encryption, decryption function example using FILE I/O and RC2 with an
80 bit key:

 int do_crypt(FILE *in, FILE *out, int do_encrypt)
 	{
	/* Allow enough space in output buffer for additional block */
	inbuf[1024], outbuf[1024 + EVP_MAX_BLOCK_LENGTH];
	int inlen, outlen;
	/* Bogus key and IV: we'd normally set these from
	 * another source.
	 */
	unsigned char key[] = "0123456789";
	unsigned char iv[] = "12345678";
	/* Don't set key or IV because we will modify the parameters */
	EVP_CipherInit(&ctx, EVP_rc2(), NULL, NULL, do_encrypt);
	EVP_CIPHER_CTX_set_key_length(&ctx, 10);
	/* We finished modifying parameters so now we can set key and IV */
	EVP_CipherInit(&ctx, NULL, key, iv, do_encrypt);

	for(;;) 
		{
		inlen = fread(inbuf, 1, 1024, in);
		if(inlen <= 0) break;
		if(!EVP_CipherUpdate(&ctx, outbuf, &outlen, inbuf, inlen))
			{
			/* Error */
			return 0;
			}
		fwrite(outbuf, 1, outlen, out);
		}
	if(!EVP_CipherFinal(&ctx, outbuf, &outlen))
		{
		/* Error */
		return 0;
		}
	fwrite(outbuf, 1, outlen, out);

	EVP_CIPHER_CTX_cleanup(&ctx);
	return 1;
	}


=head1 SEE ALSO

L<evp(3)|evp(3)>