diff options
Diffstat (limited to 'src/Signature.cpp')
-rw-r--r-- | src/Signature.cpp | 97 |
1 files changed, 97 insertions, 0 deletions
diff --git a/src/Signature.cpp b/src/Signature.cpp new file mode 100644 index 0000000..804047e --- /dev/null +++ b/src/Signature.cpp @@ -0,0 +1,97 @@ +#include "../include/Signature.hpp" +#include <sodium/crypto_sign_ed25519.h> +#include <sodium/utils.h> +#include <cstring> + +using namespace std; + +namespace odhtdb +{ + namespace Signature + { + PublicKey::PublicKey(char *_data, size_t size) + { + if(size != PUBLIC_KEY_NUM_BYTES) + { + string errMsg = "Expected public key size to be "; + errMsg += to_string(PUBLIC_KEY_NUM_BYTES); + errMsg += " bytes, was: "; + errMsg += to_string(size); + throw InvalidSignatureKeySize(errMsg); + } + memmove(data, _data, PUBLIC_KEY_NUM_BYTES); + } + + PublicKey::PublicKey(const PublicKey &other) + { + memmove(data, other.data, PUBLIC_KEY_NUM_BYTES); + } + + PublicKey& PublicKey::operator=(const PublicKey &other) + { + memmove(data, other.data, PUBLIC_KEY_NUM_BYTES); + return *this; + } + + string PublicKey::toString() const + { + string result; + result.resize(PUBLIC_KEY_NUM_BYTES * 2); + sodium_bin2hex(&result[0], PUBLIC_KEY_NUM_BYTES * 2 + 1, (const unsigned char*)data, PUBLIC_KEY_NUM_BYTES); + return result; + } + + PrivateKey::PrivateKey(char *_data, size_t size) + { + if(size != PRIVATE_KEY_NUM_BYTES) + { + string errMsg = "Expected private key size to be "; + errMsg += to_string(PRIVATE_KEY_NUM_BYTES); + errMsg += " bytes, was: "; + errMsg += to_string(size); + throw InvalidSignatureKeySize(errMsg); + } + memmove(data, _data, PRIVATE_KEY_NUM_BYTES); + } + + PrivateKey::PrivateKey(const PrivateKey &other) + { + memmove(data, other.data, PRIVATE_KEY_NUM_BYTES); + } + + PrivateKey& PrivateKey::operator=(const PrivateKey &other) + { + memmove(data, other.data, PRIVATE_KEY_NUM_BYTES); + return *this; + } + + string PrivateKey::sign(const string &dataToSign) const + { + string result; + result.resize(crypto_sign_ed25519_BYTES + dataToSign.size()); + unsigned long long resultSize; + + if(crypto_sign_ed25519((unsigned char*)&result[0], &resultSize, (unsigned char*)dataToSign.data(), dataToSign.size(), (unsigned char*)data) != 0) + throw DataSignException("Failed to sign data. Is private key invalid?"); + + if(resultSize != result.size()) + throw DataSignException("Failed to sign data. The signed data is not of expected size (bug)"); + + return result; + } + + string PrivateKey::toString() const + { + string result; + result.resize(PRIVATE_KEY_NUM_BYTES * 2); + sodium_bin2hex(&result[0], PRIVATE_KEY_NUM_BYTES * 2 + 1, (const unsigned char*)data, PRIVATE_KEY_NUM_BYTES); + return result; + } + + KeyPair::KeyPair() + { + if(crypto_sign_ed25519_keypair((unsigned char*)publicKey.data, (unsigned char*)privateKey.data) != 0) + throw SignatureGenerationException("Failed to generate signature keypair"); + } + } +} |