+ if (free_openssl_data)
+ OPENSSL_free (binary_data);
+}
+
+/* decode the binary data from the textual representation using OpenSSL */
+void decode_binary (char *bin_data, char *encoded)
+{
+ EVP_DecodeBlock ((unsigned char*)bin_data,
+ (const unsigned char*)encoded, strlen (encoded));
+}
+
+/* encrypt a block of text using password/passphrase with OpenSSL and
+ also encode it to textual representation */
+void encrypt_data (char *enc_data, const char *data, const char *password)
+{
+ EVP_CIPHER_CTX *ctx;
+ int len, cipher_len;
+ ctx = EVP_CIPHER_CTX_new ();
+ if (! ctx) goto err;
+
+ unsigned char encrypted[256] = { '\0' };
+
+ unsigned char key[EVP_MAX_KEY_LENGTH] = { '\0'};
+ unsigned char iv[EVP_MAX_IV_LENGTH] = { '\0' };
+
+ if (! EVP_BytesToKey (EVP_aes_256_cbc(), EVP_md5(), NULL,
+ (unsigned char*)password, strlen(password),
+ 10, key, iv))
+ goto err;
+
+ if (1 != EVP_EncryptInit_ex (ctx, EVP_aes_256_cbc(), NULL, key, iv))
+ goto err;
+
+ if (1 != EVP_EncryptUpdate (ctx, (unsigned char*) encrypted, &len,
+ (unsigned char*) data, strlen (data) ))
+ goto err;
+ cipher_len = len;
+
+ if (1 != EVP_EncryptFinal_ex (ctx, encrypted + len, &len))
+ goto err;
+
+ cipher_len += len;
+ EVP_CIPHER_CTX_free (ctx);
+
+ EVP_EncodeBlock ((unsigned char*) enc_data, (unsigned char*) encrypted,
+ cipher_len);
+ return;
+ err:
+ ERR_print_errors_fp (stderr);
+ EVP_CIPHER_CTX_free (ctx);
+ exit (2);
+}
+
+/* decrypt a block of text using password/passphrase with OpenSSL */
+void decrypt_data (char *dec_data, const char *data, const char *password)
+{
+ EVP_CIPHER_CTX *ctx;
+ int len, text_len;
+ ctx = EVP_CIPHER_CTX_new ();
+ if (! ctx) goto err;
+
+ char enc_data[256] = { '\0' };
+
+ unsigned char key[EVP_MAX_KEY_LENGTH] = { '\0'};
+ unsigned char iv[EVP_MAX_IV_LENGTH] = { '\0' };
+
+
+ if (! EVP_BytesToKey (EVP_aes_256_cbc(), EVP_md5(), NULL,
+ (unsigned char*)password, strlen(password),
+ 10, key, iv))
+ goto err;
+
+ int r = EVP_DecodeBlock ((unsigned char*)enc_data,
+ (const unsigned char*) data, strlen (data));
+ if (-1 == r)
+ goto err;
+
+
+ if (1 != EVP_DecryptInit_ex (ctx, EVP_aes_256_cbc(), NULL, key, iv))
+ goto err;
+
+ if (1 != EVP_DecryptUpdate (ctx, (unsigned char*) dec_data, &len,
+ (unsigned char*) enc_data, r - (r % 16) ))
+ goto err;
+ text_len = len;
+
+ if (1 != EVP_DecryptFinal_ex (ctx, (unsigned char *)dec_data + len, &len))
+ goto err;
+
+ text_len += len;
+ EVP_CIPHER_CTX_free (ctx);
+
+ dec_data[text_len] = '\0';
+
+ return;
+ err:
+ ERR_print_errors_fp (stderr);
+ EVP_CIPHER_CTX_free (ctx);
+ exit (2);