Why does my OpenSSL C++ code create binary encryption output? -


i'm trying encrypt file using aes openssl , write output file. i'm getting messy outputs, decipherable , not.

the main code based here: https://github.com/shanet/crypto-example/blob/master/crypto-example.cpp

here's code:

int crypt::__aesencrypt(const unsigned char *msg, size_t msglen, unsigned char **encmsg) { evp_cipher_ctx *aesencryptctx = (evp_cipher_ctx*)malloc(sizeof(evp_cipher_ctx)); evp_cipher_ctx_init(aesencryptctx);  unsigned char *aeskey = (unsigned char*)malloc(aes_keylen/8); unsigned char *aesiv = (unsigned char*)malloc(aes_keylen/8);  unsigned char *aespass = (unsigned char*)malloc(aes_keylen/8); unsigned char *aessalt = (unsigned char*)malloc(8);  if(rand_bytes(aespass, aes_keylen/8) == 0) {     return failure; }  if(rand_bytes(aessalt, 8) == 0) {     return failure; }  if(evp_bytestokey(evp_aes_256_cbc(), evp_sha1(), aessalt, aespass, aes_keylen/8, aes_rounds, aeskey, aesiv) == 0) {     return failure; }  strncpy((char*)aeskey, (const char*)"b374a26a71490437aa024e4fadd5b4aa", aes_keylen/8); strncpy((char*)aesiv, (const char*)"7e892875a52c59a3b588306b13c31fbd", aes_keylen/16);  size_t blocklen = 0; size_t encmsglen = 0;  *encmsg = (unsigned char*)malloc(msglen + aes_block_size); if(encmsg == null) return failure;  if(!evp_encryptinit_ex(aesencryptctx, evp_aes_256_cbc(), null, aeskey, aesiv)) {     return failure; }  if(!evp_encryptupdate(aesencryptctx, *encmsg, (int*)&blocklen, (unsigned char*)msg, msglen)) {     return failure; } encmsglen += blocklen;  if(!evp_encryptfinal_ex(aesencryptctx, *encmsg + encmsglen, (int*)&blocklen)) {     return failure; }  evp_cipher_ctx_cleanup(aesencryptctx); free(aesencryptctx);  free(aeskey); free(aesiv);  return encmsglen + blocklen; 

}

im calling this:

unsigned char *encmsg = null;     __aesencrypt((const unsigned char*)decrypted_string.c_str(), decrypted_string.size(), &encmsg);      std::stringstream ss;     ss << encmsg;     //write ss file... 

thanks.

i'm author of example you've based code off of. whozcraig pointed out in comments above, using stringstream write encrypted message file. problem encrypted messages not regular ascii strings. binary data (values greater 127, hence need unsigned char array) , binary data cannot treated same ascii strings.

i'm not of c++ person, write data file c way fwrite, if want c++ way, think you're looking ifstream rather stringstream.

side note, i'm betting debugging, i'll point out anyway make sure: hardcoding aes key , iv (strncpy((char*)aeskey, (const char*)"b374a26a71490437aa024e4fadd5b4aa", aes_keylen/8)) defeats purpose of encryption. if want avoid pbkdf (evp_bytestokey) can use rand_bytes random data aes key.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -