[openssl-users] OpenSSL occasionally generates wrong signature

Jakob Bohm jb-openssl at wisemo.com
Tue Oct 16 14:46:04 UTC 2018


On 16/10/2018 16:39, Dmitry wrote:
> Hello!
>
> I have a C++ programme, ECDSA key pair and some string to sign. The 
> programme generates signature and saves it into a file 
> (signature.bin). Then I check the validity of the signature via the 
> following command:
>
> openssl dgst -verify ec_public.pem -signature signature.bin ToSign.txt
>
> the problem is that *my programme sometimes generates wrong 
> signature*. 16 times out of 21 the signature produced is invalid and 
> the above command outputs:
> Error Verifying Data
>
> while in the remaining 5 occurrences it outputs:
> Verified OK
>
> Do you have any ideas of how it can be possible? What am I doing wrong?
>
>
> Here is the programme:
>
> SSL_library_init();
> OPENSSL_config(nullptr);
> SSL_load_error_strings();
> OpenSSL_add_all_algorithms();
> ERR_load_BIO_strings();
> CRYPTO_set_id_callback(ThreadIdFunction);
> CRYPTO_set_locking_callback(LockingFunction);
>
> const TString pk = "-----BEGIN EC PRIVATE KEY-----\n"
>  "MHcCAQEEIG90zmo1o3NWNFa8wp2z4rdQXGSN8xAP/OATLpwlgi+1oAoGCCqGSM49\n"
>  "AwEHoUQDQgAE5TwpzBhjUWZoOf629GfwGG5WlRJD7TSuz+ZTHUaiK5mj2qgxBOPk\n"
>  "eqOrTYXsiPwnaWe23zHjIM8NOhAm1BiGgA==\n"
>                      "-----END EC PRIVATE KEY-----\n";
>
> const TString ToSign = 
> "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhc2RmIn0";
>
> EVP_MD_CTX *Ctx    = EVP_MD_CTX_create();
> BIO *       Bio    = BIO_new_mem_buf(pk.data(), pk.size());
> EVP_PKEY *  EVPKey = PEM_read_bio_PrivateKey(Bio, nullptr, nullptr, 
> nullptr);
>
> EVP_DigestSignInit(Ctx, nullptr, EVP_sha256(), nullptr, EVPKey);
> EVP_DigestSignUpdate(Ctx, ToSign.data(), ToSign.size());
> size_t SignatureLength;
> EVP_DigestSignFinal(Ctx, nullptr, &SignatureLength);
>
> TString Result;
^^^^^^^ You are treating binary data as a string.
Chances are the TString class will truncate at the first byte with
the value zero, and/or do some other text-specific thing that is bad
for binary data.

> Result.resize(SignatureLength);
> EVP_DigestSignFinal(Ctx, reinterpret_cast<unsigned char 
> *>(const_cast<char *>(Result.data())), &SignatureLength);
>
> // Saving to file...
>

Enjoy

Jakob
-- 
Jakob Bohm, CIO, Partner, WiseMo A/S.  https://www.wisemo.com
Transformervej 29, 2860 Søborg, Denmark.  Direct +45 31 13 16 10
This public discussion message is non-binding and may contain errors.
WiseMo - Remote Service Management for PCs, Phones and Embedded



More information about the openssl-users mailing list