I am trying to make CryptoPP::SecretSharing to work with in memory byte objects.
My current solution partly works. I can reconstruct the original secret except for the last byte or two, depends on the length of original secret.
Could you please suggest me how to fix this.
std::vector<Bytes> SecretShareBytes(const Bytes& secret, int threshold, int nShares)
{
CryptoPP::AutoSeededRandomPool rng;
CryptoPP::ChannelSwitch *channelSwitch;
CryptoPP::ArraySource source( secret.data(), secret.size(), false,new CryptoPP::SecretSharing( rng, threshold, nShares, channelSwitch = new CryptoPP::ChannelSwitch) );
std::vector<Bytes> shares( nShares );
CryptoPP::vector_member_ptrs<CryptoPP::ArraySink> arraySinks( nShares );
std::string channel;
for (int i = 0; i < nShares; i++)
{
shares[i] = Bytes( secret.size() + sizeof(int) );
arraySinks[i].reset( new CryptoPP::ArraySink((byte*)shares[i].data(), shares[i].size()) );
channel = CryptoPP::WordToString<word32>(i);
arraySinks[i]->Put( (byte *)channel.data(), 4 );
channelSwitch->AddRoute( channel,*arraySinks[i],CryptoPP::BufferedTransformation::NULL_CHANNEL );
}
source.PumpAll();
return shares;
}
Bytes SecretRecoverBytes(std::vector<Bytes>& shares, int threshold)
{
Bytes bytes( shares[0].size() - sizeof( int ) );
CryptoPP::SecretRecovery recovery( threshold, new CryptoPP::ArraySink(bytes.data(), bytes.size()) );
CryptoPP::SecByteBlock channel(4);
for (int i = 0; i < threshold; i++)
{
CryptoPP::ArraySource arraySource(shares[i].data(), shares[i].size(), false);
arraySource.Pump(4);
arraySource.Get( channel, 4 );
arraySource.Attach( new CryptoPP::ChannelSwitch( recovery, std::string( (char *)channel.begin(), 4) ) );
arraySource.PumpAll();
}
return bytes;
}