From 4a5eedbf0a77f9eb4e9c84e29c005661e7b24575 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adrien=20B=C3=A9raud?= <adrien.beraud@savoirfairelinux.com> Date: Tue, 14 Jun 2016 18:13:02 -0400 Subject: [PATCH] value: add common crypto ops --- include/opendht/value.h | 43 +++++++++++++++++++++++++++++++++++++++++ src/securedht.cpp | 13 ++----------- 2 files changed, 45 insertions(+), 11 deletions(-) diff --git a/include/opendht/value.h b/include/opendht/value.h index 9990147d..af2cc169 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 f1718ee9..5a5db3a2 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 -- GitLab