Search code examples
c++cryptographycrypto++

SecByteBlock to ECDSA<ECP, SHA256>::PublicKey and reverse in CryptoPP


As the title says is there a way to transform a Key in SecByteBlock to ECDSA<ECP, SHA256>::PublicKey and the reverse?

From what I have read I just managed to transform PublicKey to strin using:

    PubicKey pubKey;
    string s;
    StringSink ss(s);
    pubKey.Save(ss);

Solution

  •  //To string
    
     string encoded;
    
    
        // Pretty print key
        encoded.clear();
    
          
            StringSource(key, key.size(), true,
                         new HexEncoder(
                                 new StringSink(encoded)
                         ) // HexEncoder
            ); // StringSource
    
    PublicKey string_to_publicKey(string keyInHex){
        string decodedKey;
        HexDecoder decoder;
        decoder.Put( (byte*)keyInHex.data(), keyInHex.size() );
        decoder.MessageEnd();
    
        word64 size = decoder.MaxRetrievable();
        if(size && size <= SIZE_MAX)
        {
            decodedKey.resize(size);
            decoder.Get((byte*)&decodedKey[0], decodedKey.size());
        }
        cout << "Decoded : " << decodedKey << endl;
        StringSource ss(decodedKey, true);
        PublicKey pubKey;
        pubKey.Load(ss);
    
        return pubKey;
    }
    string public_key_to_string(PublicKey publicKey){
        string ss;
        StringSink sink(ss);
        publicKey.Save(sink);
        string encoded;
        HexEncoder encoder;
        encoder.Put((byte*)ss.data(), ss.size());
        encoder.MessageEnd();
        word64 size = encoder.MaxRetrievable();
        if(size)
        {
            encoded.resize(size);
            encoder.Get((byte*)&encoded[0], encoded.size());
        }
        std::cout << "key in hex: " << encoded;
    
        return encoded;
    }