i2pd/libi2pd/Signature.cpp

58 lines
1.9 KiB
C++
Raw Normal View History

2015-04-09 17:03:21 +03:00
#include <memory>
2015-04-08 22:31:13 +03:00
#include "Log.h"
2015-04-08 20:21:49 +03:00
#include "Signature.h"
namespace i2p
{
namespace crypto
{
2015-11-23 17:26:32 +03:00
EDDSA25519Verifier::EDDSA25519Verifier (const uint8_t * signingKey)
2015-04-09 17:03:21 +03:00
{
2018-01-06 06:48:51 +03:00
memcpy (m_PublicKeyEncoded, signingKey, EDDSA25519_PUBLIC_KEY_LENGTH);
2015-11-23 17:26:32 +03:00
BN_CTX * ctx = BN_CTX_new ();
m_PublicKey = GetEd25519 ()->DecodePublicKey (m_PublicKeyEncoded, ctx);
BN_CTX_free (ctx);
2015-04-09 17:03:21 +03:00
}
2015-04-08 23:28:52 +03:00
bool EDDSA25519Verifier::Verify (const uint8_t * buf, size_t len, const uint8_t * signature) const
2015-04-08 23:18:16 +03:00
{
2015-11-03 17:15:49 +03:00
uint8_t digest[64];
SHA512_CTX ctx;
SHA512_Init (&ctx);
SHA512_Update (&ctx, signature, EDDSA25519_SIGNATURE_LENGTH/2); // R
SHA512_Update (&ctx, m_PublicKeyEncoded, EDDSA25519_PUBLIC_KEY_LENGTH); // public key
2018-01-06 06:48:51 +03:00
SHA512_Update (&ctx, buf, len); // data
SHA512_Final (digest, &ctx);
2018-01-06 06:48:51 +03:00
return GetEd25519 ()->Verify (m_PublicKey, digest, signature);
2015-04-09 17:03:21 +03:00
}
2017-01-08 05:20:09 +03:00
EDDSA25519Signer::EDDSA25519Signer (const uint8_t * signingPrivateKey, const uint8_t * signingPublicKey)
2018-01-06 06:48:51 +03:00
{
2015-11-03 17:15:49 +03:00
// expand key
2018-06-05 19:53:13 +03:00
Ed25519::ExpandPrivateKey (signingPrivateKey, m_ExpandedPrivateKey);
2015-11-03 17:15:49 +03:00
// generate and encode public key
2018-01-06 06:48:51 +03:00
BN_CTX * ctx = BN_CTX_new ();
2015-11-23 17:26:32 +03:00
auto publicKey = GetEd25519 ()->GeneratePublicKey (m_ExpandedPrivateKey, ctx);
2018-01-06 06:48:51 +03:00
GetEd25519 ()->EncodePublicKey (publicKey, m_PublicKeyEncoded, ctx);
2017-01-08 05:20:09 +03:00
if (signingPublicKey && memcmp (m_PublicKeyEncoded, signingPublicKey, EDDSA25519_PUBLIC_KEY_LENGTH))
{
// keys don't match, it means older key with 0x1F
LogPrint (eLogWarning, "Older EdDSA key detected");
2018-01-06 06:48:51 +03:00
m_ExpandedPrivateKey[EDDSA25519_PRIVATE_KEY_LENGTH - 1] &= 0xDF; // drop third bit
2017-01-08 05:20:09 +03:00
publicKey = GetEd25519 ()->GeneratePublicKey (m_ExpandedPrivateKey, ctx);
2018-01-06 06:48:51 +03:00
GetEd25519 ()->EncodePublicKey (publicKey, m_PublicKeyEncoded, ctx);
2017-01-08 05:20:09 +03:00
}
2015-11-23 17:26:32 +03:00
BN_CTX_free (ctx);
2018-01-06 06:48:51 +03:00
}
2015-11-03 17:15:49 +03:00
void EDDSA25519Signer::Sign (const uint8_t * buf, int len, uint8_t * signature) const
2015-04-09 17:03:21 +03:00
{
GetEd25519 ()->Sign (m_ExpandedPrivateKey, m_PublicKeyEncoded, buf, len, signature);
2018-01-06 06:48:51 +03:00
}
2015-04-08 20:21:49 +03:00
}
}