v1.0.0
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
#include <openssl/rsa.h>
|
||||
#include <openssl/evp.h>
|
||||
#include <include/cpp/define.hpp>
|
||||
#include <cstring>
|
||||
#include <openssl/crypto.h>
|
||||
#include <openssl/err.h>
|
||||
|
||||
int text_encrypt(EVP_PKEY* key,char *_i,char *_o){
|
||||
EVP_PKEY_CTX* key_ctx = EVP_PKEY_CTX_new(key, nullptr);
|
||||
EVP_PKEY_encrypt_init(key_ctx);
|
||||
EVP_PKEY_CTX_set_rsa_padding(key_ctx, PADDING_METHOD);
|
||||
size_t enc;
|
||||
int stat = EVP_PKEY_encrypt(key_ctx,nullptr,&enc,(const unsigned char *)_i,strlen(_i));
|
||||
if(stat!=1){
|
||||
return -1;
|
||||
}
|
||||
stat = EVP_PKEY_encrypt(key_ctx,(unsigned char *)_o,&enc,(const unsigned char *)_i,strlen(_i));
|
||||
if(stat!=1){
|
||||
return -1;
|
||||
}
|
||||
return enc;
|
||||
}
|
||||
|
||||
int text_decrypt(EVP_PKEY* key,char *_i,char *_o){
|
||||
EVP_PKEY_CTX* key_ctx = EVP_PKEY_CTX_new(key, nullptr);
|
||||
EVP_PKEY_decrypt_init(key_ctx);
|
||||
EVP_PKEY_CTX_set_rsa_padding(key_ctx, PADDING_METHOD);
|
||||
size_t dec;
|
||||
int stat = EVP_PKEY_decrypt(key_ctx,nullptr,&dec,(const unsigned char *)_i,BUFFER_SIZE);
|
||||
if(stat!=1){
|
||||
return -1;
|
||||
}
|
||||
stat = EVP_PKEY_decrypt(key_ctx,(unsigned char *)_o,&dec,(const unsigned char *)_i,dec);
|
||||
if(stat!=1){
|
||||
return -1;
|
||||
}
|
||||
return dec;
|
||||
}
|
||||
|
||||
char* base64_encode(const unsigned char* input, size_t length) {
|
||||
BIO* b64 = BIO_new(BIO_f_base64());
|
||||
BIO* mem = BIO_new(BIO_s_mem());
|
||||
BIO_push(b64, mem);
|
||||
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
|
||||
BIO_write(b64, input, length);
|
||||
BIO_flush(b64);
|
||||
char* bio_data = nullptr;
|
||||
long bio_len = BIO_get_mem_data(mem, &bio_data);
|
||||
if (bio_len <= 0 || !bio_data) {
|
||||
BIO_free_all(b64);
|
||||
return nullptr;
|
||||
}
|
||||
char* output = static_cast<char*>(malloc(bio_len + 1));
|
||||
if (!output) {
|
||||
BIO_free_all(b64);
|
||||
return nullptr;
|
||||
}
|
||||
memcpy(output, bio_data, bio_len);
|
||||
output[bio_len] = '\0';
|
||||
BIO_free_all(b64);
|
||||
return output;
|
||||
}
|
||||
|
||||
char* base64_decode(const char* input, size_t length, size_t* output_len) {
|
||||
BIO* b64 = BIO_new(BIO_f_base64());
|
||||
BIO* mem = BIO_new_mem_buf(input, static_cast<int>(length));
|
||||
BIO_push(b64, mem);
|
||||
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
|
||||
const size_t max_len = (length * 3) / 4 + 1;
|
||||
char* output = static_cast<char*>(malloc(max_len));
|
||||
if (!output) {
|
||||
BIO_free_all(b64);
|
||||
return nullptr;
|
||||
}
|
||||
*output_len = BIO_read(b64, output, static_cast<int>(max_len));
|
||||
if (*output_len <= 0) {
|
||||
free(output);
|
||||
BIO_free_all(b64);
|
||||
return nullptr;
|
||||
}
|
||||
output[*output_len] = '\0';
|
||||
BIO_free_all(b64);
|
||||
return output;
|
||||
}
|
||||
Reference in New Issue
Block a user