How to use hard-coded keys for two parties to form key agreement using ECDH from cryptopp library?

Hi folks!.
need help here and don’t say “just google” because i have already done that. I need your help through this code, how it can be corrected to produce correct “Agreed shared secret key” which is supposed to be "1ed885b1064ae5e041cef89365eb7a63b87a6e3e59f6b3ec74c117b74c4e89a4"

The code:

#include <iostream>
using std::cout;
using std::cerr;
using std::endl;

#include <string>
using std::string;

#include <stdexcept>
using std::runtime_error;

#include <cstdlib>
using std::exit;

#include "cryptopp/osrng.h"
using CryptoPP::AutoSeededRandomPool;
using CryptoPP::AutoSeededX917RNG;

#include "cryptopp/aes.h"
using CryptoPP::AES;

#include "cryptopp/eccrypto.h"
using CryptoPP::ECP;
using CryptoPP::ECDH;

#include "cryptopp/secblock.h"
using CryptoPP::SecByteBlock;

#include "cryptopp/oids.h"
using CryptoPP::OID;

// ASN1 is a namespace, not an object
#include "cryptopp/asn.h"
using namespace CryptoPP::ASN1;

#include "cryptopp/integer.h"
using CryptoPP::Integer;

#include <cryptopp/hex.h>

int main( int, char** ) {

    OID CURVE = secp256r1();

    ECDH < ECP >::Domain dhA( CURVE ), dhB( CURVE );
    string privatekeyA = "e8586d5fa27ffb6a37817c171c94189ad20d8fcf29fa58ba0e6cbe4cf2bb1079";
    string publickeyB = "4f0609f35a0be01caa1287862680b803ea50fb66af2ad65e990aa4a8944c6191ac0d13d98612e12ba1d9afa86f997aab2827a0cee43bf963e8e995eb95df2fb33";

    SecByteBlock privA(dhA.PrivateKeyLength());
    SecByteBlock pubB(dhB.PublicKeyLength());  
    string Prkey, Pukey;
    unsigned char privateky[32];
    unsigned char publicky[64];

    CryptoPP::StringSource ssk(privatekeyA, true ,
        new CryptoPP::HexDecoder(
            new CryptoPP::StringSink(Prkey)

    CryptoPP::StringSource ssv(publickeyB, true ,
        new CryptoPP::HexDecoder(
            new CryptoPP::StringSink(Pukey)

    for(int i=0;i<32;i++) {
		    if (Prkey[i]<0) privateky[i]=Prkey[i]+256;
		    else privateky[i]=Prkey[i];

    for(int i=0;i<64;i++) {
		    if (Pukey[i]<0) publicky[i]=Pukey[i]+256;
		    else publicky[i]=Pukey[i];
    privA.Assign(privateky, sizeof(privateky));
    pubB.Assign(publicky, sizeof(publicky));

    SecByteBlock sharedA(dhA.AgreedValueLength());

    dhA.Agree(sharedA, privA, pubB);

    Integer a;

    a.Decode(sharedA.BytePtr(), sharedA.SizeInBytes());
    cout << "Agreed to shared secret: " << std::hex << a << endl;

    return 0;

The output of this code is wrong. Am just playing around to understand the concept so any help even in comments will be highly appreciated.

This topic was automatically closed after 121 days. New replies are no longer allowed.