File indexing completed on 2024-05-12 05:04:18
0001 // SPDX-FileCopyrightText: 2023 Joshua Goins <josh@redstrate.com> 0002 // SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL 0003 0004 #include "ecdh.h" 0005 0006 #include <openssl/obj_mac.h> 0007 0008 constexpr int PRIVATE_KEY_LENGTH = 32; 0009 constexpr int PUBLIC_KEY_LENGTH = 65; 0010 0011 EC_KEY *generateECDHKeypair() 0012 { 0013 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); 0014 if (!key) { 0015 return nullptr; 0016 } 0017 0018 if (EC_KEY_generate_key(key) != 1) { 0019 EC_KEY_free(key); 0020 return nullptr; 0021 } 0022 return key; 0023 } 0024 0025 QByteArray exportPrivateKey(const EC_KEY *key) 0026 { 0027 uint8_t rawPrivKey[PRIVATE_KEY_LENGTH]; 0028 if (!EC_KEY_priv2oct(key, rawPrivKey, PRIVATE_KEY_LENGTH)) { 0029 return {}; 0030 } 0031 0032 return {reinterpret_cast<const char *>(rawPrivKey), PRIVATE_KEY_LENGTH}; 0033 } 0034 0035 QByteArray exportPublicKey(const EC_KEY *key) 0036 { 0037 uint8_t rawPubKey[PUBLIC_KEY_LENGTH]; 0038 if (!EC_POINT_point2oct(EC_KEY_get0_group(key), EC_KEY_get0_public_key(key), POINT_CONVERSION_UNCOMPRESSED, rawPubKey, PUBLIC_KEY_LENGTH, nullptr)) { 0039 return {}; 0040 } 0041 0042 return {reinterpret_cast<const char *>(rawPubKey), PUBLIC_KEY_LENGTH}; 0043 }