From 181355616e66ba8d1a5931209cb606073f7f2fab Mon Sep 17 00:00:00 2001 From: "Dr. Stephen Henson" Date: Thu, 17 May 2001 13:03:20 +0000 Subject: [PATCH] Add examples to EVP_EncryptInit manual page. --- doc/crypto/EVP_EncryptInit.pod | 89 ++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) diff --git a/doc/crypto/EVP_EncryptInit.pod b/doc/crypto/EVP_EncryptInit.pod index 9e8c16eb41..e830a191cc 100644 --- a/doc/crypto/EVP_EncryptInit.pod +++ b/doc/crypto/EVP_EncryptInit.pod @@ -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 +utility with the command line: + + S + +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 -- 2.25.1