I want to use bcrypt encryption for storing passwords and I know OpenSSL implements Blowfish Cipher (which I'm assuming is the same thing).
I made some adaptations from the code shown in this page https://wiki.openssl.org/index.php/EVP_Symmetric_Encryption_and_Decryption and came up with this:
int OpenSSLEncrypt(
unsigned char* plaintext,
int plaintext_len,
unsigned char* key,
unsigned char* iv,
unsigned char* ciphertext)
{
EVP_CIPHER_CTX *ctx;
int len;
int ciphertext_len;
if (!(ctx = EVP_CIPHER_CTX_new())) OpenSSLHandleErrors();
if (1 != EVP_EncryptInit_ex(ctx, EVP_bf_cbc(), 0, key, 0))
OpenSSLHandleErrors();
if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
OpenSSLHandleErrors();
ciphertext_len = len;
if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len))
OpenSSLHandleErrors();
ciphertext_len += len;
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}
int OpenSSLDecrypt(
unsigned char* ciphertext,
int ciphertext_len,
unsigned char* key,
unsigned char* iv,
unsigned char* plaintext)
{
EVP_CIPHER_CTX *ctx;
int len;
int plaintext_len;
if (!(ctx = EVP_CIPHER_CTX_new())) OpenSSLHandleErrors();
if (1 != EVP_DecryptInit_ex(ctx, EVP_bf_cbc(), NULL, key, 0))
OpenSSLHandleErrors();
if (1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
OpenSSLHandleErrors();
plaintext_len = len;
if (1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len))
OpenSSLHandleErrors();
plaintext_len += len;
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
return plaintext_len;
}
But the length of the cipher that I get from OpenSSLEncrypt(...) depends on the length of the plaintext input parameter, which is not what I was expecting. I was expecting the output to be 64 bytes long no matter the length of the password.
Also, I don't know if EVP_EncryptInit_ex needs an iv (initialization vector) or not for EVP_bf_cbc, and I found no documentation that could help me with this.
As it was pointed out in the comments, I was wrong in assuming Blowfish and BCrypt are the same thing, just because I read somewhere B stands for Blowfish.
I ended up following the suggestion from Cinder Biscuits of using the OpenBSD implementation of bcrypt, avaiable at
https://github.com/libressl-portable/openbsd/blob/master/src/lib/libc/crypt/bcrypt.c