initial commit
This commit is contained in:
commit
be13205ffd
19 changed files with 33596 additions and 0 deletions
66
implementations/Nostro-Crypto.cpp
Normal file
66
implementations/Nostro-Crypto.cpp
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
//SPDX-License-Identifier: LGPL-3.0-only
|
||||
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||
|
||||
module;
|
||||
|
||||
#include <openssl/evp.h>
|
||||
#include <openssl/pem.h>
|
||||
#include <openssl/rsa.h>
|
||||
#include <openssl/err.h>
|
||||
|
||||
module Nostro:Crypto_impl;
|
||||
import :Crypto;
|
||||
import std;
|
||||
|
||||
using namespace Nostro;
|
||||
|
||||
long Crypto::ThrowOnOpenssl(long status) {
|
||||
if(status <= 0) {
|
||||
ERR_print_errors_fp(stderr);
|
||||
throw std::runtime_error("openssl error");
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
std::string Crypto::SignBody(EVP_PKEY* privateKey, std::string_view body) {
|
||||
EVP_MD_CTX* ctx = ThrowOnOpenssl(EVP_MD_CTX_new());
|
||||
ThrowOnOpenssl(EVP_DigestSignInit(ctx, nullptr, EVP_sha256(), nullptr, privateKey));
|
||||
ThrowOnOpenssl(EVP_DigestSignUpdate(ctx, body.data(), body.length()));
|
||||
|
||||
size_t sigLen = 0;
|
||||
ThrowOnOpenssl(EVP_DigestSignFinal(ctx, nullptr, &sigLen));
|
||||
|
||||
std::string sig;
|
||||
sig.resize(sigLen);
|
||||
ThrowOnOpenssl(EVP_DigestSignFinal(ctx, reinterpret_cast<unsigned char*>(sig.data()), &sigLen));
|
||||
sig.resize(sigLen);
|
||||
|
||||
std::string sig64;
|
||||
sig64.resize(4 * ((sig.size() + 2) / 3));
|
||||
int n = EVP_EncodeBlock(reinterpret_cast<unsigned char*>(sig64.data()), reinterpret_cast<const unsigned char*>(sig.data()), static_cast<int>(sig.size()));
|
||||
sig64.resize(n);
|
||||
|
||||
EVP_MD_CTX_free(ctx);
|
||||
return sig64;
|
||||
}
|
||||
|
||||
std::tuple<EVP_PKEY*, std::string> Crypto::CreateKey() {
|
||||
EVP_PKEY* pkey = ThrowOnOpenssl(EVP_RSA_gen(2048));
|
||||
|
||||
char* data;
|
||||
|
||||
BIO* pubBio = ThrowOnOpenssl(BIO_new(BIO_s_mem()));
|
||||
ThrowOnOpenssl(PEM_write_bio_PUBKEY(pubBio, pkey));
|
||||
const long len = ThrowOnOpenssl(BIO_get_mem_data(pubBio, &data));
|
||||
std::string publicKey(data, len);
|
||||
BIO_free(pubBio);
|
||||
|
||||
return {pkey, publicKey};
|
||||
}
|
||||
|
||||
EVP_PKEY* Crypto::LoadKeyFromPem(std::string_view pem) {
|
||||
BIO* bio = ThrowOnOpenssl(BIO_new_mem_buf(pem.data(), static_cast<int>(pem.size())));
|
||||
EVP_PKEY* pkey = PEM_read_bio_PrivateKey(bio, nullptr, nullptr, nullptr);
|
||||
BIO_free(bio);
|
||||
return ThrowOnOpenssl(pkey);
|
||||
}
|
||||
Loading…
Reference in a new issue