separate X25519Keys

This commit is contained in:
orignal 2018-09-08 16:52:42 -04:00
parent 50399e5194
commit 1babd3a5a2
4 changed files with 101 additions and 49 deletions

View file

@ -12,9 +12,8 @@
#if LEGACY_OPENSSL
#include "ChaCha20.h"
#include "Poly1305.h"
#else
#include <openssl/evp.h>
#endif
#include "Ed25519.h"
#include "I2PEndian.h"
#include "Log.h"
@ -278,6 +277,58 @@ namespace crypto
BN_free (pk);
}
// x25519
X25519Keys::X25519Keys ()
{
#if OPENSSL_X25519
m_Ctx = EVP_PKEY_CTX_new_id (NID_X25519, NULL);
#else
m_Ctx = BN_CTX_new ();
#endif
}
X25519Keys::~X25519Keys ()
{
#if OPENSSL_X25519
EVP_PKEY_CTX_free (m_Ctx);
if (m_Pkey)
EVP_PKEY_free (m_Pkey);
#else
BN_CTX_free (m_Ctx);
#endif
}
void X25519Keys::GenerateKeys ()
{
#if OPENSSL_X25519
m_Pkey = nullptr;
EVP_PKEY_keygen_init (m_Ctx);
EVP_PKEY_keygen (m_Ctx, &m_Pkey);
size_t len = 32;
EVP_PKEY_get_raw_public_key (m_Pkey, m_PublicKey, &len);
// TODO: remove
len = 32;
EVP_PKEY_get_raw_private_key (m_EphemeralPkey, m_PrivateKey, &len);
#else
RAND_bytes (m_PrivateKey, 32);
GetEd25519 ()->ScalarMulB (m_PrivateKey, m_PublicKey, m_Ctx);
#endif
}
void X25519Keys::Agree (const uint8_t * pub, uint8_t * shared)
{
#if OPENSSL_X25519
EVP_PKEY_derive_init (m_Ctx);
auto pkey = EVP_PKEY_new_raw_public_key (EVP_PKEY_X25519, NULL, pub, 32);
EVP_PKEY_derive_set_peer (m_Ctx, pkey);
size_t len = 32;
EVP_PKEY_derive (m_Ctx, shared, &len);
EVP_PKEY_free (pkey);
#else
GetEd25519 ()->ScalarMul (pub, m_PrivateKey, shared, m_Ctx);
#endif
}
// ElGamal
void ElGamalEncrypt (const uint8_t * key, const uint8_t * data, uint8_t * encrypted, BN_CTX * ctx, bool zeroPadding)
{