I have the following string:
char *str = "\x45\x00\x10";
I need to encrypt it using openssl, send it over the network and decrypt to get back the same string.
I use the following code for encryption (programming in C in Ubuntu Linux):
int do_encrypt(char *cipher, char *key, char *iv, char *plaintext, int len)
{
unsigned char outbuf[BUFSIZE];
int outlen, tmplen;
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key, iv);
if(!EVP_EncryptUpdate(&ctx, outbuf, &outlen, plaintext, len))
{
EVP_CIPHER_CTX_cleanup(&ctx);
return 0;
}
if(!EVP_EncryptFinal_ex(&ctx, outbuf + outlen, &tmplen))
{
EVP_CIPHER_CTX_cleanup(&ctx);
return 0;
}
outlen += tmplen;
EVP_CIPHER_CTX_cleanup(&ctx);
outbuf[outlen] = '\0';
strcpy(cipher,outbuf);
return 1;
}
I use the following code for decryption:
int do_decrypt(char *plain, char *key, char *iv, char *cipher)
{
unsigned char outbuf[BUFSIZE];
int outlen, tmplen;
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key, iv);
if(!EVP_DecryptUpdate(&ctx, outbuf, &outlen, cipher, strlen(cipher)))
{
EVP_CIPHER_CTX_cleanup(&ctx);
return 0;
}
if(!EVP_DecryptFinal_ex(&ctx, outbuf + outlen, &tmplen))
{
EVP_CIPHER_CTX_cleanup(&ctx);
return 0;
}
outlen += tmplen;
EVP_CIPHER_CTX_cleanup(&ctx);
outbuf[outlen] = '\0';
strcpy(plain,outbuf);
return outlen;
}
When I encrypt str using the first function, and passing the third argument as 3 (I don’t want to pass strlen(str) as it will not encrypt entire string), and decrypt it using the second function, I get the following plain text back:
\x45\x00\x00 // recovered plain text
What correction should I make to my code so that I may encrypt the whole string and still get the entire string back, even if original string contained null characters ?
Thanks.
You… do know that
strcpy()will stop at the first NUL, right? Usestrncpy()instead.