#include "../include/Signature.hpp" #include #include #include 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"); } } }