Skip to content

Instantly share code, notes, and snippets.

@MarlikAlmighty
Created September 15, 2023 03:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarlikAlmighty/0d028553096006c4ec14d659890120e1 to your computer and use it in GitHub Desktop.
Save MarlikAlmighty/0d028553096006c4ec14d659890120e1 to your computer and use it in GitHub Desktop.
Encrypt/Decrypt with OpenSSL
#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