Decrypt problem using Openssl aes-256-cbc

61 views
Skip to first unread message

lwmo...@gmail.com

unread,
Apr 22, 2015, 11:49:47 PM4/22/15
to openssl...@googlegroups.com

hi,all:

I'm doing Encrypt and Decrypt work with aes-256-cbc + Base64Encode; But with openssl library, I have encountered the following problem:

1\ Encrypt works:  string "1000" is encrypted to "Vz3XJBIVoIM0UcTuiA49JQ=="
2\ Decrypt seems bad: 
    The plaintext length decrypted by  "Vz3XJBIVoIM0UcTuiA49JQ=="  is always 16,  but the real length is 4. 


The following is my code of Decryption:

std::string SimpleAES::Decrypt(const std::string &cipherstr_b64)
{
    unsigned char *ciphertext = new unsigned char[CalcDecodeLength(cipherstr_b64.c_str())]();

    unsigned char *cipherstr_b64_data = new unsigned char[cipherstr_b64.size() + 1]();
    std::copy(cipherstr_b64.begin(), cipherstr_b64.end(), cipherstr_b64_data);
    cipherstr_b64_data[cipherstr_b64.size()] = '\0';

    //int ciphertext_len = Comm::DecodeBase64(cipherstr_b64_data, ciphertext, cipherstr_b64.size());
    //int ciphertext_len = Base64Decode((const char *)cipherstr_b64_data, cipherstr_b64.size(), ciphertext);
    //int ciphertext_len = Base64Decode((const char *)ciphertext, cipherstr_b64.size(), cipherstr_b64_data);
    // 原始串通过Base64 decode 到ciphertext 中
    int ciphertext_len = Base64Decode((const char *)cipherstr_b64_data, cipherstr_b64.size(), (char *)ciphertext);

    int len = 0, plaintext_len = 0;
    unsigned char *plaintext = new unsigned char[cipherstr_b64.size()]();
    //unsigned char plaintext[cipherstr_b64.size() + AES_BLOCK_SIZE]{};
    //unsigned char plaintext[ciphertext_len + AES_BLOCK_SIZE]{};

    EVP_DecryptInit_ex(&decrypt_ctx, EVP_aes_256_cbc(), NULL, key, iv);
    EVP_DecryptUpdate(&decrypt_ctx, plaintext, &len, ciphertext, ciphertext_len);
    plaintext_len = len;

    cout << "plaintext_len1:" << plaintext_len << endl;

    EVP_DecryptFinal_ex(&decrypt_ctx, plaintext + len, &len);
    plaintext_len += len;

    cout << "plaintext_len2:" << plaintext_len << endl;

    std::string plaintext_str(reinterpret_cast<const char*>(plaintext), plaintext_len);
    //std::string plaintext_str((char *)plaintext);

    delete [] ciphertext;
    delete [] cipherstr_b64_data;
    delete [] plaintext;

    return plaintext_str;
}



And the result is :


Any clue??

Best wishes 

Reply all
Reply to author
Forward
0 new messages