From e51a6bf4e8a9a057d47e2cc1a884460d28ae29c4 Mon Sep 17 00:00:00 2001 From: ENGO150 Date: Sat, 1 Feb 2025 14:54:11 +0100 Subject: [PATCH] created why2_chat_ecc_encrypt fn --- include/chat/crypto.h | 2 ++ src/chat/crypto.c | 50 ++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/include/chat/crypto.h b/include/chat/crypto.h index d6abcf0..1a34497 100644 --- a/include/chat/crypto.h +++ b/include/chat/crypto.h @@ -49,6 +49,8 @@ why2_bool why2_chat_ecc_verify_signature(char *message, char *signature, EVP_PKE char *why2_chat_ecc_serialize_public_key(); //GET PUBLIC ECC KEY IN BASE64 EVP_PKEY* why2_chat_ecc_deserialize_public_key(char *pubkey); //GET EVP_PKEY FROM BASE64 PUBLIC ECC KEY +char *why2_chat_ecc_encrypt(char *message, char *key); //ENCRYPT message WITH ECC key + char *why2_sha256(char *input, size_t length); //HASH input USING SHA256 AND RETURN IN STRING #ifdef __cplusplus diff --git a/src/chat/crypto.c b/src/chat/crypto.c index b8626f4..738a369 100644 --- a/src/chat/crypto.c +++ b/src/chat/crypto.c @@ -24,14 +24,15 @@ along with this program. If not, see . #include #include -#include -#include - #include #include #include #include +#include +#include +#include + EVP_PKEY *keypair = NULL; //KEYPAIR //LOCAL @@ -258,6 +259,49 @@ EVP_PKEY* why2_chat_ecc_deserialize_public_key(char *pubkey) return key; } +char *why2_chat_ecc_encrypt(char *message, char *key) +{ + //VARIABLES + size_t key_length; + char *secret = NULL; + size_t secret_len; + char *recipient_pubkey_decoded = base64_decode(key, &key_length); //DECODE key + why2_output_flags encrypted; + char *encrypted_text; + char *returning; + char *sym_key; + BIO *bio = BIO_new_mem_buf(recipient_pubkey_decoded, -1); + EVP_PKEY *recipient_pubkey = PEM_read_bio_PUBKEY(bio, NULL, NULL, NULL); + + //CALCULATE SHARED SECRET + calculate_ecdh_secret(keypair, recipient_pubkey, &secret, &secret_len); + + //DERIVE WHY2 KEY (SHA256) + sym_key = why2_sha256(secret, secret_len); + + //ENCRYPTION SETTINGS + if (why2_get_key_length() < strlen(sym_key)) why2_set_key_length(strlen(sym_key)); //ALLOW sym_key'S LENGTH + why2_set_flags((why2_input_flags) { 0, 0, 0, WHY2_v4, WHY2_OUTPUT_TEXT, WHY2_CHAT_PADDING(strlen(sym_key)) }); + + //ENCRYPT MESSAGE + encrypted = why2_encrypt_text(message, sym_key); + encrypted_text = why2_strdup(encrypted.output_text); + + //CONVERT TO BASE64 + returning = base64_encode(encrypted_text, strlen(encrypted_text)); + + //DEALLOCATION + BIO_free(bio); + EVP_PKEY_free(recipient_pubkey); + why2_deallocate(secret); + why2_deallocate(sym_key); + why2_deallocate(recipient_pubkey_decoded); + why2_deallocate(encrypted_text); + why2_deallocate_output(encrypted); + + return returning; +} + void why2_chat_deallocate_keys(void) { //DEALLOCATE THE pkey