Created
September 15, 2023 03:29
-
-
Save MarlikAlmighty/0d028553096006c4ec14d659890120e1 to your computer and use it in GitHub Desktop.
Encrypt/Decrypt with OpenSSL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <openssl/rsa.h> | |
#include <openssl/pem.h> | |
int encryptData(const unsigned char *plaintext, int plaintextLength, unsigned char *ciphertext, EVP_PKEY *publicKey) | |
{ | |
EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(publicKey, NULL); | |
if (!ctx) | |
{ | |
// Handle error | |
return -1; | |
} | |
if (EVP_PKEY_encrypt_init(ctx) <= 0) | |
{ | |
// Handle error | |
EVP_PKEY_CTX_free(ctx); | |
return -1; | |
} | |
if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING) <= 0) | |
{ | |
// Handle error | |
EVP_PKEY_CTX_free(ctx); | |
return -1; | |
} | |
size_t ciphertextLength; | |
if (EVP_PKEY_encrypt(ctx, ciphertext, &ciphertextLength, plaintext, plaintextLength) <= 0) | |
{ | |
// Handle error | |
EVP_PKEY_CTX_free(ctx); | |
return -1; | |
} | |
EVP_PKEY_CTX_free(ctx); | |
return ciphertextLength; | |
} | |
int decryptData(const unsigned char *ciphertext, int ciphertextLength, unsigned char *plaintext, EVP_PKEY *privateKey) | |
{ | |
EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new(privateKey, NULL); | |
if (!ctx) | |
{ | |
// Handle error | |
return -1; | |
} | |
if (EVP_PKEY_decrypt_init(ctx) <= 0) | |
{ | |
// Handle error | |
EVP_PKEY_CTX_free(ctx); | |
return -1; | |
} | |
if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING) <= 0) | |
{ | |
// Handle error | |
EVP_PKEY_CTX_free(ctx); | |
return -1; | |
} | |
size_t plaintextLength; | |
if (EVP_PKEY_decrypt(ctx, plaintext, &plaintextLength, ciphertext, ciphertextLength) <= 0) | |
{ | |
// Handle error | |
EVP_PKEY_CTX_free(ctx); | |
return -1; | |
} | |
EVP_PKEY_CTX_free(ctx); | |
return plaintextLength; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment