diff --git a/include/opendht/value.h b/include/opendht/value.h index 9990147dba7cf035fac850f83f10c9b82dabf6f2..af2cc1690eae699eaaaf7b1db4839580e74ef62b 100644 --- a/include/opendht/value.h +++ b/include/opendht/value.h @@ -248,6 +248,43 @@ struct Value return owner and not signature.empty(); } + /** + * Sign the value using the provided private key. + * Afterward, checkSignature() will return true and owner will + * be set to the corresponding public key. + */ + void sign(const crypto::PrivateKey& key) { + if (isEncrypted()) + throw DhtException("Can't sign encrypted data."); + owner = std::make_shared<crypto::PublicKey>(key.getPublicKey()); + signature = key.sign(getToSign()); + } + + /** + * Check that the value is signed and that the signature matches. + * If true, the owner field will contain the signer public key. + */ + bool checkSignature() const { + return isSigned() and owner->checkSignature(getToSign(), signature); + } + + std::shared_ptr<const crypto::PublicKey> getOwner() const { + return std::static_pointer_cast<const crypto::PublicKey>(owner); + } + + /** + * + */ + Value encrypt(const crypto::PrivateKey& from, const crypto::PublicKey& to) { + if (isEncrypted()) + throw DhtException("Data is already encrypted."); + setRecipient(to.getId()); + sign(from); + Value nv {id}; + nv.setCypher(to.encrypt(getToEncrypt())); + return nv; + } + Value() {} Value (Id id) : id(id) {} @@ -380,6 +417,12 @@ struct Value void msgpack_unpack(msgpack::object o); void msgpack_unpack_body(const msgpack::object& o); + Blob getPacked() const { + msgpack::sbuffer buffer; + msgpack::packer<msgpack::sbuffer> pk(&buffer); + pk.pack(*this); + return {buffer.data(), buffer.data()+buffer.size()}; + } Id id {INVALID_ID}; diff --git a/src/securedht.cpp b/src/securedht.cpp index f1718ee9a292336d77320a36de91d384e73248fd..5a5db3a220a3317b11519eacacac9291006dac37 100644 --- a/src/securedht.cpp +++ b/src/securedht.cpp @@ -362,22 +362,13 @@ SecureDht::putEncrypted(const InfoHash& hash, const InfoHash& to, std::shared_pt void SecureDht::sign(Value& v) const { - if (v.isEncrypted()) - throw DhtException("Can't sign encrypted data."); - v.owner = std::make_shared<crypto::PublicKey>(key_->getPublicKey()); - v.signature = key_->sign(v.getToSign()); + v.sign(*key_); } Value SecureDht::encrypt(Value& v, const crypto::PublicKey& to) const { - if (v.isEncrypted()) - throw DhtException("Data is already encrypted."); - v.setRecipient(to.getId()); - sign(v); - Value nv {v.id}; - nv.setCypher(to.encrypt(v.getToEncrypt())); - return nv; + return v.encrypt(*key_, to); } Value