OpenSSL AES_cfb128_encrypt public/private key C++ - c++

I have very basic encrypt/decrypt application that uses constant key. How to make this application to work with public/private key? Is it enough to generate keys with openssl and use them in my code variable ckey?
Can I somehow generate keys with my library?
#include "stdafx.h"
#include <openssl/aes.h>
#include <algorithm>
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
int bytes_read, bytes_written;
unsigned char indata[AES_BLOCK_SIZE + 1];
unsigned char outdata[AES_BLOCK_SIZE + 1];
std::fill(indata, indata + AES_BLOCK_SIZE, 0);
std::fill(outdata, outdata + AES_BLOCK_SIZE, 0);
/* ckey and ivec are the two 128-bits keys necesary to
en- and recrypt your data. Note that ckey can be
192 or 256 bits as well */
unsigned char ckey[] = "thiskeyisverybad";
const char ivecstr[AES_BLOCK_SIZE] = "goodbyworldkey\0";
unsigned char ivec[] = "dontusethisinput";
/* data structure that contains the key itself */
AES_KEY key;
/* set the encryption key */
AES_set_encrypt_key(ckey, 128, &key);
/* set where on the 128 bit encrypted block to begin encryption*/
int num = 0;
FILE* ifp;
FILE* oefp;
FILE* odfp;
ifp = fopen("infile.txt", "r");
if (ifp == NULL) perror("Error opening file");
oefp = fopen("outEncryptfile.txt", "w");
if (oefp == NULL) perror("Error opening file");
odfp = fopen("outDecryptfile.txt", "w");
if (odfp == NULL) perror("Error opening file");
int b = 0;
int w = 0;
memcpy(ivec, ivecstr, AES_BLOCK_SIZE);
while (1)
{
std::fill(indata, indata + AES_BLOCK_SIZE, 0);
bytes_read = fread(indata, 1, AES_BLOCK_SIZE, ifp);
b = b + bytes_read;
indata[AES_BLOCK_SIZE] = 0;
//std::cout << "original data:\t" << indata << std::endl;
std::cout << indata;
AES_cfb128_encrypt(indata, outdata, bytes_read, &key, ivec, &num,AES_ENCRYPT);
bytes_written = fwrite(outdata, 1, bytes_read, oefp);
w = w + bytes_written;
if (bytes_read < AES_BLOCK_SIZE)
break;
}
fclose(oefp);
oefp = fopen("outEncryptfile.txt", "r");
if (oefp == NULL) perror("Error opening file");
b = 0;
memcpy(ivec, ivecstr, AES_BLOCK_SIZE);
while (1)
{
bytes_read = fread(indata, 1, AES_BLOCK_SIZE, oefp);
b = b + bytes_read;
indata[AES_BLOCK_SIZE] = 0;
std::cout << "original data:\t" << indata << std::endl;
AES_cfb128_encrypt(indata, outdata, bytes_read, &key, ivec, &num, AES_DECRYPT);
std::cout << "decrypted data:\t" << outdata << std::endl;
bytes_written = fwrite(outdata, 1, bytes_read, odfp);
if (bytes_read < AES_BLOCK_SIZE)
break;
}
fclose(odfp);
return 0;
}

I have very basic encrypt/decrypt application that uses constant key. How to make this application to work with public/private key? Is it enough to generate keys with openssl and use them in my code variable ckey?
You can't. Shared key and private key cryptography are sufficiently different to ensure you cannot do it. Or maybe more correctly, you can't do it without a major redesign and rewrite.
OpenSSL provides two (maybe three) high level primitives of interest for your issue. Here's the documentation on them:
EVP Symmetric Encryption and Decryption
EVP Asymmetric Encryption and Decryption
The "maybe three" is:
EVP Authenticated Encryption and Decryption
Here are the common API calls when using (1) EVP Symmetric Encryption and (2) EVP Asymmetric Encryption from above:
EVP Symmetric Encryption
EVP_CIPHER_CTX_new
EVP_EncryptInit_ex
EVP_EncryptUpdate
EVP_EncryptFinal_ex
EVP Asymmetric Encryption
EVP_CIPHER_CTX_new
EVP_SealInit
EVP_SealUpdate
EVP_SealFinal
EVP_CIPHER_CTX_free
With all that said, its not really a design problem in OpenSSL. The APIs are well defined for operation at hand - symmetric encryption, authenticated encryption, asymmetric encryption, signing, verifying, hashing, mac'ing, etc. It would be difficult to shoehorn everything into one set of API calls.
The code you provided, using AES_KEY, AES_set_encrypt_key, and friends, is even harder to work with. Its a specialized software-only AES implementation that you get if you configure with no-asm. It also has some landmines, like being non-portable in some cases. For example, I seem to recall special care has to be taken on some big-endian platforms because you need to byte-swap the key.
Yu might also want to look at how IPsec and TLS do things. They break workflows up into two parts: (1) key exchange (or key transport) and (2) bulk encryption. The key exchange portion happens using public/private key cryptography. and establishes a shared secret. Once the shared secret is established, symmetric ciphers are keyed and bulk encryption takes place.
IPsec has a more defensive security posture. TLS runs a bit fast and loose for my taste. I only use TLS when requirements tell me to do so (like interop'ing with existing systems). Otherwise, I prefer in-app VPNs or IPsec-like schemes.

Related

First 16 bytes of AES-128 CFB-8 decryption are damaged

I've been working on a project recently that should connect to a server with the help of a protocol. So far so good, but when I combed to decrypt the packages, I quickly noticed that something is not working properly.
The first 16 bytes of all packets are decrypted incorrectly. I have tried it with different libraries but that does not work either. I work in the C++ language and have so far used Crypto++ and OpenSSL for decryption, without success.
Under this Link you can find the protocol, here the decryption protocol Link and here is my corresponding code:
OpenSSL:
void init() {
unsigned char* sharedSecret = new unsigned char[AES_BLOCK_SIZE];
std::generate(sharedSecret,
sharedSecret + AES_BLOCK_SIZE,
std::bind(&RandomGenerator::GetInt, &m_RNG, 0, 255));
for (int i = 0; i < 16; i++) {
sharedSecretKey += sharedSecret[i];
}
// Initialize AES encryption and decryption
if (!(m_EncryptCTX = EVP_CIPHER_CTX_new()))
std::cout << "123" << std::endl;
if (!(EVP_EncryptInit_ex(m_EncryptCTX, EVP_aes_128_cfb8(), nullptr, (unsigned char*)sharedSecretKey.c_str(), (unsigned char*)sharedSecretKey.c_str())))
std::cout << "123" << std::endl;
if (!(m_DecryptCTX = EVP_CIPHER_CTX_new()))
std::cout << "123" << std::endl;
if (!(EVP_DecryptInit_ex(m_DecryptCTX, EVP_aes_128_cfb8(), nullptr, (unsigned char*)sharedSecretKey.c_str(), (unsigned char*)sharedSecretKey.c_str())))
std::cout << "123" << std::endl;
m_BlockSize = EVP_CIPHER_block_size(EVP_aes_128_cfb8());
}
std::string result;
int size = 0;
result.resize(1000);
EVP_DecryptUpdate(m_DecryptCTX, &((unsigned char*)result.c_str())[0], &size, &sendString[0], data.size());
Crypto++:
CryptoPP::CFB_Mode<CryptoPP::AES>::Decryption AESDecryptor((byte*)sharedSecret.c_str(), (unsigned int)16, sharedSecret.c_str(), 1);
std::string sTarget("");
CryptoPP::StringSource ss(data, true, new CryptoPP::StreamTransformationFilter(AESDecryptor, new CryptoPP::StringSink(sTarget)));
I think important to mention is that I use one and the same shared secret for the key and the iv (initialization vector). In other posts, this was often labeled as a problem. I do not know how to fix it in this case because the protocol want it.
I would be looking forward to a constructive feedback.
EVP_EncryptInit_ex(m_EncryptCTX, EVP_aes_128_cfb8(), nullptr,
(unsigned char*)sharedSecretKey.c_str(), (unsigned char*)sharedSecretKey.c_str()))
And:
CFB_Mode<AES>::Decryption AESDecryptor((byte*)sharedSecret.c_str(),
(unsigned int)16, sharedSecret.c_str(), 1);
std::string sTarget("");
StringSource ss(data, true, new StreamTransformationFilter(AESDecryptor, new StringSink(sTarget)));
It is not readily apparent, but you need to set feedback size for the mode of operation of the block cipher in Crypto++. The Crypto++ feedback size is 128 by default.
The code to set the feedback size of CFB mode can be found at CFB Mode on the Crypto++ wiki. You want the 3rd or 4th example down the page.
AlgorithmParameters params =
MakeParameters(Name::FeedbackSize(), 1 /*8-bits*/)
(Name::IV(), ConstByteArrayParameter(iv));
That is kind of an awkward way to pass parameters. It is documented in the sources files and on the wiki at NameValuePairs. It allows you to pass arbitrary parameters through consistent interfaces. It is powerful once you acquire a taste for it.
And then use params to key the encryptor and decryptor:
CFB_Mode< AES >::Encryption enc;
enc.SetKey( key, key.size(), params );
// CFB mode must not use padding. Specifying
// a scheme will result in an exception
StringSource ss1( plain, true,
new StreamTransformationFilter( enc,
new StringSink( cipher )
) // StreamTransformationFilter
); // StringSource
I believe your calls would look something like this (if I am parsing the OpenSSL correctly):
const byte* ptr = reinterpret_cast<const byte*>(sharedSecret.c_str());
AlgorithmParameters params =
MakeParameters(Name::FeedbackSize(), 1 /*8-bits*/)
(Name::IV(), ConstByteArrayParameter(ptr, 16));
CFB_Mode< AES >::Encryption enc;
enc.SetKey( ptr, 16, params );
In your production code you should use unique key and iv. So do something like this using HKDF:
std::string seed(AES_BLOCK_SIZE, '0');
std::generate(seed, seed + AES_BLOCK_SIZE,
std::bind(&RandomGenerator::GetInt, &m_RNG, 0, 255));
SecByteBlock sharedSecret(32);
const byte usage[] = "Key and IV v1";
HKDF<SHA256> hkdf;
hkdf.DeriveKey(sharedSecret, 32, &seed[0], 16, usage, COUNTOF(usage), nullptr, 0);
AlgorithmParameters params =
MakeParameters(Name::FeedbackSize(), 1 /*8-bits*/)
(Name::IV(), ConstByteArrayParameter(sharedSecret+16, 16));
CFB_Mode< AES >::Encryption enc;
enc.SetKey(sharedSecret+0, 0, params);
In the code above, sharedSecret is twice as large as it needs to be. You derive the key and iv from the seed using HDKF. sharedSecret+0 is the 16-byte key, and sharedSecret+16 is the 16-byte iv.

Not getting same session key after decoding payload under RSA

I am not getting same session key after encoding and decoding it using below functions which uses crypto++ library:
CryptoPP::RSA::PrivateKey RSA_master_privKey;
CryptoPP::RSA::PublicKey RSA_master_pubKey;
std::string generate_Master_Keys()
{
std::string rsaParams;
try {
CryptoPP::InvertibleRSAFunction parameters;
RSA_master_privKey = CryptoPP::RSA::PrivateKey(parameters);
RSA_master_pubKey = CryptoPP::RSA::PublicKey(parameters);
}
catch (const CryptoPP::Exception& e)
{
std::cerr << e.what() << std::endl;
b_success = false;
}
return rsaParams;
}
PAES_KEY_WITH_IV create_session_key(void)
{
CryptoPP::AutoSeededX917RNG<CryptoPP::AES> rng;
PAES_KEY_WITH_IV aes_info = new AES_KEY_WITH_IV;
try {
aes_info->key.resize(CryptoPP::AES::DEFAULT_KEYLENGTH);
rng.GenerateBlock(aes_info->key, aes_info->key.size());
aes_info->iv.resize(CryptoPP::AES::BLOCKSIZE);
rng.GenerateBlock(&aes_info->iv[0], aes_info->iv.size());
}
catch (const CryptoPP::Exception& e)
{
std::cerr << e.what() << std::endl;
b_success = false;
}
return (aes_info);
}
std::string encrypt_session_key(PAES_KEY_WITH_IV pKey)
{
std::string ciphered;
CryptoPP::SecByteBlock block(pKey->key.size());
try {
CryptoPP::RSAES< CryptoPP::OAEP<CryptoPP::SHA> >::Encryptor enc(RSA_master_pubKey);
enc.Encrypt(rng, pKey->key, pKey->key.size(), block);
ciphered.assign((char *)block.BytePtr(), 192);
}
catch (const CryptoPP::Exception& e)
{
std::cerr << e.what() << std::endl;
b_success = false;
}
return ciphered;
}
PAES_KEY_WITH_IV decrypt_session_key(std::string & ciphered)
{
CryptoPP::SecByteBlock rec(ciphered.size());
CryptoPP::SecByteBlock block((const byte *)ciphered.data(), ciphered.size());
PAES_KEY_WITH_IV pKey = new AES_KEY_WITH_IV;
try {
CryptoPP::RSAES< CryptoPP::OAEP<CryptoPP::SHA> >::Decryptor dec(RSA_master_privKey);
dec.Decrypt(rng, block, block.size(), rec);
pKey->key = rec;
}
catch (const CryptoPP::Exception& e)
{
std::cerr << e.what() << std::endl;
b_success = false;
}
return pKey;
}
Tailing of 192 bytes are not getting matched with original session key's bytes.
Can some one help me on this ?
Thanks in advance.
I am not getting same session key after encoding and decoding it using below functions
I think you are close to what you need. There's also an opportunity for improvement in the way you are doing it. I'll show you the improved way, and you can apply it to the existing method as well.
The improved way simply uses FixedMaxPlaintextLength, CiphertextLength and some friends to determine sizes. It also uses a technique from Integrated Encryption Schemes (IES).
First, transport the raw seed bytes, and not the {key, iv} pair. Then, when you need the {key, iv} pair, you derive the bytes you need from the seed bytes. Your derivation should include a usage label and a version number.
Second, the open question: how many bytes do you transport as seed bytes. That answer is FixedMaxPlaintextLength() or MaxPreimage() (I don't recall which). That's the size of the plaintext that can be encrypted under the scheme, and it depends on things like the modulus size and the padding scheme.
A lot of the code below is discussed at RSA Encryption Schemes and other places on the Crypto++ wiki. But its not readily apparent you need to visit them because you are still learning some of the techniques.
The following generates a random seed and encrypts it under the public key.
RSA_master_pubKey = RSA::PublicKey(parameters);
RSAES< OAEP<SHA> >::Encryptor enc(RSA_master_pubKey);
SecByteBlock seed(enc.FixedMaxPlaintextLength());
AutoSeededX917RNG<AES> rng;
rng.GenerateBlock(seed, seed.size());
SecByteBlock block(enc.CiphertextLength(seed.size())));
size_t req = enc.Encrypt(rng, seed, seed.size(), block);
block.resize(req);
// Transport block to peer as session seed
When the peer receives the encrypted seed block, they must decrypt it. Here's how to do it.
// Received from peer
SecByteBlock block(...);
RSAES< OAEP<SHA> >::Decryptor dec(RSA_master_privKey);
size_t req = dec.MaxPlaintextLength(block.size());
SecByteBlock seed(req);
DecodingResult result = dec.Decrypt(rng, block, block.size(), seed);
seed.resize(result.isValidCoding ? result.messageLength : 0);
You could even thrown an exception if result.isValidCoding returns false:
DecodingResult result = dec.Decrypt(rng, block, block.size(), seed);
if (!result.isValidCoding)
throw Exception(OTHER_ERROR, "Failed to decrypt seed bytes");
seed.resize(result.messageLength);
When you want to encrypt or decrypt with AES, you need to derive a key, iv and possibly an hmac key (are you authenticating the data?).
// Random seed from above
SecByteBlock seed;
HKDF<SHA256> kdf;
SecByteBlock aesKey(AES::DEFAULT_KEYLENGTH);
SecByteBlock aesIV(AES::BLOCKSIZE);
const byte aesLabel[] = "AES encryption key, version 1";
kdf.Derive(aesKey, aesKey.size(), seed, seed.size(), NULL, 0, aesLabel, COUNTOF(aesLabel));
const byte ivLabel[] = "AES initialization vector, version 1";
kdf.Derive(aesIV, aesIV.size(), seed, seed.size(), NULL, 0, ivLabel, COUNTOF(ivLabel));
IF you authenticate your data, then you can derive an HMAC key with the following. But generally speaking, you should probably use an Authenticated Encryption mode of operation:
const byte hmacLabel[] = "HMAC authentication key, version 1";
kdf.Derive(hmacKey, hmacKey.size(), seed, seed.size(), NULL, 0, hmacLabel, COUNTOF(hmacLabel));
HKDF was added at 5.6.3 or 5.6.4. If you don't have it, then grab hkdf.h from Wei Dai's GitHub (its header-only). By deriving from a base seed with unique labels, you are using a technique called independent derivation.
You add the labels and the version information to avoid gaps like discussed in Attacking and Repairing the WinZip Encryption Scheme. Also, using the entire FixedMaxPlaintextLength side steps some cryptographic attacks related to message length.
You might also want to look at Integrated Encryption Schemes (IES). We basically lifted the Key Encapsulation Mechanism (KEM) from IES. There's a Data Encapsulation Mechanism (DEM) that could be lifted, too.
If you are going to borrow the KEM and the DEM, then you may as well use the scheme. For that, see the following on the Crypto++ wiki:
Elliptic Curve Integrated Encryption Scheme
Discrete Logarithm Integrated Encryption Scheme
If you use one of the Integrated Encryption Schemes, then you are changing the underlying mathematical problem. RSA is Integer Factorization (IF), while IES is Diffie-Hellman and Discrete Logs (FF).
Using an Integrated Encryption Scheme is a good choice. Its IND-CCA2, which is a very strong notion of security. I believe it has better security properties than your original scheme.

How do you create an EVP_KEY for a peer key given the Base64 encoding?

Using OpenSSL, I've created my Diffie-Hellman Private/Public keys and received my peer's public key. I can decode my peer's key from Base64 string to byte array, but how do I poke that into my original Public/Private Key EVP_KEY structure so it can be used with the EVP_PKEY_derive() to produce the shared key?
It's very unclear exactly what one should do to create the "peerkey" EVP_PKEY, but here's my code that takes a shot at it.
void CreateSharedKey(string &peerKey64)
{
EVP_PKEY *publicKey; // Created earlier
EVP_PKEY *peerKey;
// Decode peer key
unsigned char *pBuff;
int buffLen = base64Decode(peerKey64, &pBuff);
const unsigned char *pConst = pBuff;
// Create peer key
peerKey = d2i_PUBKEY(NULL, &pConst, buffLen);
if (peerKey == NULL)
return;
// Create shared key context
EVP_PKEY_CTX *ctxShared;
ctxShared = EVP_PKEY_CTX_new(publicKey, NULL);
if (ctxShared == NULL)
return;
// Initialize for deriving shared key
if (EVP_PKEY_derive_init(ctxShared) <= 0)
return;
// Add peer key to context
if (int rc = EVP_PKEY_derive_set_peer(ctxShared, peerKey) <= 0)
return;
// Determine buffer length for shared key
size_t sharedKeyBufferSize;
if (EVP_PKEY_derive(ctxShared, NULL, &sharedKeyBufferSize) <= 0)
return;
// Allocate buffer for shared key
unsigned char *sharedKeyBuffer = new unsigned char[sharedKeyBufferSize];
if (sharedKeyBuffer == NULL)
return;
// Derive the shared key
if (EVP_PKEY_derive(ctxShared, sharedKeyBuffer, &sharedKeyBufferSize) <= 0)
{
unsigned long error = ERR_get_error();
cout << "Failed to derive shared key. Error code = " << error << std::endl;
cout << ERR_reason_error_string(error) << std::endl;
return;
}
// Free shared key context
EVP_PKEY_CTX_free(ctxShared);
// Create Base64 shared key string
base64Encode(sharedKeyStr, sharedKeyBuffer, sharedKeyBufferSize);
}
The OpenSSL error output is as follows:
Failed to add peer to shared key context. Error code = 101298329
different parameters
How can it have different parameters when it was derived from a Context that was BASED on the parameters already existing in the original publicKey?

OpenSSL RSA_private_decrypt() fails with "oaep decoding error"

I'm trying to implement RSA encryption/decryption using OpenSSL. Unfortunately my code fails during decryption.
I'm using Qt. So here is my code:
QByteArray CryptRSA::rsaEncrypt(QByteArray input)
{
QByteArray result(RSA_size(rsaKey), '\0');
int encryptedBytes = RSA_public_encrypt(RSA_size(rsaKey) - 42, (unsigned char *)input.data(), (unsigned char *) result.data(), rsaKey, RSA_PKCS1_OAEP_PADDING);
if (encryptedBytes== -1)
{
qDebug() << "Error encrypting RSA Key:";
handleErrors();
return QByteArray();
}
else
{
return result;
}
}
QByteArray CryptRSA::rsaDecrypt(QByteArray input)
{
QByteArray result(RSA_size(rsaKey), '\0');
int decryptedBytes = RSA_private_decrypt(RSA_size(rsaKey) - 42, (unsigned char *)input.data(), (unsigned char *)result.data(), rsaKey, RSA_PKCS1_OAEP_PADDING);
if (decryptedBytes == -1)
{
qDebug() << "Error decrypting RSA Key.";
handleErrors();
return QByteArray();
}
else
{
result.resize(decryptedBytes);
return result;
}
}
Here is the error:
error:0407A079:rsa routines:RSA_padding_check_PKCS1_OAEP:oaep decoding error
error:04065072:rsa routines:RSA_EAY_PRIVATE_DECRYPT:padding check failed
It fails in:
RSA_private_decrypt(RSA_size(rsaKey) - 42, (unsigned char *)input.data(),
(unsigned char *)result.data(), rsaKey, RSA_PKCS1_OAEP_PADDING);
I have tried several things, but i can't find my mistakes.
error:0407A079:rsa routines:RSA_padding_check_PKCS1_OAEP:oaep decoding error
error:04065072:rsa routines:RSA_EAY_PRIVATE_DECRYPT:padding check failed
If RSA_public_encrypt succeeds, then set the size of the result array to encryptedBytes. Do similar for RSA_private_decrypt.
Also, its not clear what you are trying to do with RSA_size(rsaKey) - 42. That looks very odd to me. I would expect it to be input.size(). But I'm guessing you know what you are doing with you array.
There could be other problems (like the public and private keys don't match), but we'd need to see more code and parameters to tell.
Also, you should use the EVP_* interfaces. See EVP Asymmetric Encryption and Decryption of an Envelope on the OpenSSL wiki.

Separating public and private keys from RSA keypair variable

As the title says, I have some code that generates a pair of RSA keys. I want to split them apart and use them individually to encrypt/decrypt, rather than use the variable "keypair" to encrypt, and decrypt.
I am working to transfer data across a network, and want to encrypt it using simple RSA encryption. Therefore i want to send the public key over to a different user, so he can use it to encrypt some data, and then send it back to me.
Here is the code that generates the keys:
//Generate key pair
RSA *keypair = RSA_generate_key(KEY_LENGTH, PUB_EXP, NULL, NULL);
I now want to separate the public from the private key, so i can use them independently to encrypt and decrypt data. How can i do that?
I've got some code that takes the "keypair" and extracts some information into some "BIO" variables, although i am not sure how that would help me:
// To get the C-string PEM form:
BIO *pri = BIO_new(BIO_s_mem());
BIO *pub = BIO_new(BIO_s_mem());
PEM_write_bio_RSAPrivateKey(pri, keypair, NULL, NULL, 0, NULL, NULL);
PEM_write_bio_RSAPublicKey(pub, keypair);
pri_len = BIO_pending(pri);
pub_len = BIO_pending(pub);
pri_key = (char*)malloc(pri_len + 1);
pub_key = (char*)malloc(pub_len + 1);
BIO_read(pri, pri_key, pri_len);
BIO_read(pub, pub_key, pub_len);
pri_key[pri_len] = '\0';
pub_key[pub_len] = '\0';
#ifdef PRINT_KEYS
printf("\n%s\n%s\n", pri_key, pub_key);
#endif
printf("done.\n");
This code works, since i've tested it in visual studio 2012.
Any ideas on how to separate the keys, then maybe put them back together in a "keypair" or maybe how to use them separately to encrypt/decrypt some string variables?
Thank you
(FULL CODE)
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <stdio.h>
#include <string.h>
#define KEY_LENGTH 2048
#define PUB_EXP 3
#define PRINT_KEYS
#define WRITE_TO_FILE
int main() {
size_t pri_len; // Length of private key
size_t pub_len; // Length of public key
char *pri_key; // Private key
char *pub_key; // Public key
char msg[KEY_LENGTH/8]; // Message to encrypt
char *encrypt = NULL; // Encrypted message
char *decrypt = NULL; // Decrypted message
char *err; // Buffer for any error messages
//Generate key pair
RSA *keypair = RSA_generate_key(KEY_LENGTH, PUB_EXP, NULL, NULL);
// To get the C-string PEM form:
BIO *pri = BIO_new(BIO_s_mem());
BIO *pub = BIO_new(BIO_s_mem());
PEM_write_bio_RSAPrivateKey(pri, keypair, NULL, NULL, 0, NULL, NULL);
PEM_write_bio_RSAPublicKey(pub, keypair);
pri_len = BIO_pending(pri);
pub_len = BIO_pending(pub);
pri_key = (char*)malloc(pri_len + 1);
pub_key = (char*)malloc(pub_len + 1);
BIO_read(pri, pri_key, pri_len);
BIO_read(pub, pub_key, pub_len);
pri_key[pri_len] = '\0';
pub_key[pub_len] = '\0';
#ifdef PRINT_KEYS
printf("\n%s\n%s\n", pri_key, pub_key);
#endif
printf("done.\n");
// Get the message to encrypt
printf("Message to encrypt: ");
fgets(msg, KEY_LENGTH-1, stdin);
msg[strlen(msg)-1] = '\0';
// Encrypt the message
encrypt = (char*)malloc(RSA_size(keypair));
int encrypt_len;
err = (char*)malloc(130);
if((encrypt_len = RSA_public_encrypt(strlen(msg)+1, (unsigned char*)msg, (unsigned char*)encrypt, keypair, RSA_PKCS1_OAEP_PADDING)) == -1) {
ERR_load_crypto_strings();
ERR_error_string(ERR_get_error(), err);
fprintf(stderr, "Error encrypting message: %s\n", err);
goto free_stuff;
}
// Decrypt it
decrypt = (char*)malloc(encrypt_len);
if(RSA_private_decrypt(encrypt_len, (unsigned char*)encrypt, (unsigned char*)decrypt, keypair, RSA_PKCS1_OAEP_PADDING) == -1) {
ERR_load_crypto_strings();
ERR_error_string(ERR_get_error(), err);
fprintf(stderr, "Error decrypting message: %s\n", err);
goto free_stuff;
}
printf("Decrypted message: %s\n", decrypt);
getchar();
//printf("%s", pub_key);
free_stuff:
RSA_free(keypair);
BIO_free_all(pub);
BIO_free_all(pri);
free(pri_key);
free(pub_key);
free(encrypt);
free(decrypt);
free(err);
}
Found this code here : https://shanetully.com/2012/04/simple-public-key-encryption-with-rsa-and-openssl/
I want to split [the keypair] apart and use them individually to encrypt/decrypt
... Any ideas on how to separate the keys, then maybe put them back together in a "keypair" or maybe how to use them separately to encrypt/decrypt some string variables?
You can use RSAPublicKey_dup and RSAPrivateKey_dup, without the need to round trip them by ASN.1/DER or PEM encoding them. Here, round tripping consist of using a functions like PEM_write_bio_RSAPublicKey and PEM_read_bio_RSAPublicKey.
Below is a sample program that uses them. Its written in C++ (thanks for adding that tag).
While you can separate them, they both use the RSA structure. The public key has some members set to NULL, like the private exponent.
You can also print the keys with RSA_print, RSA_print_fp and friends. See RSA_print (3) or its use below.
// g++ -Wall -Wextra -std=c++11 -stdlib=libc++ -I/usr/local/ssl/macosx-x64/include \
// t.cpp -o t.exe /usr/local/ssl/macosx-x64/lib/libcrypto.a
#include <memory>
using std::unique_ptr;
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <cassert>
#define ASSERT assert
using BN_ptr = std::unique_ptr<BIGNUM, decltype(&::BN_free)>;
using RSA_ptr = std::unique_ptr<RSA, decltype(&::RSA_free)>;
int main(int argc, char* argv[])
{
int rc;
RSA_ptr rsa(RSA_new(), ::RSA_free);
BN_ptr bn(BN_new(), ::BN_free);
rc = BN_set_word(bn.get(), RSA_F4);
ASSERT(rc == 1);
rc = RSA_generate_key_ex(rsa.get(), 2048, bn.get(), NULL);
ASSERT(rc == 1);
RSA_ptr rsa_pub(RSAPublicKey_dup(rsa.get()), ::RSA_free);
RSA_ptr rsa_priv(RSAPrivateKey_dup(rsa.get()), ::RSA_free);
fprintf(stdout, "\n");
RSA_print_fp(stdout, rsa_pub.get(), 0);
fprintf(stdout, "\n");
RSA_print_fp(stdout, rsa_priv.get(), 0);
return 0;
}
Here is the output:
$ ./t.exe
Public-Key: (2048 bit)
Modulus:
00:aa:5a:cc:30:52:f1:e9:49:3d:a6:25:00:33:29:
a6:fa:f7:53:e0:3c:73:4c:91:41:66:20:ec:62:1f:
27:2a:2a:6c:0f:90:f8:d9:7e:d5:ec:72:7b:38:8c:
ca:12:60:f8:d1:fb:f2:65:7c:b1:3a:b6:4e:26:ba:
5b:86:cc:30:f2:fc:be:c3:a2:00:b9:ea:81:fa:1c:
22:4e:f7:be:a1:1a:66:90:13:b6:12:66:26:23:6d:
22:15:7d:3b:a4:99:44:38:fa:1c:70:63:4e:50:6f:
66:38:6c:f6:1a:13:e1:c7:dc:a6:a1:eb:6f:f9:c9:
59:c8:30:dc:c2:1b:dc:6c:9d:ea:0c:3d:52:5a:00:
ea:c9:c9:85:51:21:9f:ec:95:b3:dc:c2:50:21:29:
c2:64:6c:1e:34:36:d8:61:59:ab:3c:a2:cc:e8:ef:
57:c3:7f:49:86:be:e3:42:88:1b:39:10:b8:2f:fa:
81:ef:a0:94:99:0c:71:ae:1e:82:7f:e3:6e:00:6e:
02:13:66:bb:a9:31:58:ec:90:39:9c:bc:9c:8c:90:
e9:20:f7:20:8e:d6:a3:a3:df:a2:4a:0f:0f:39:b5:
57:b9:ef:6a:27:e0:1a:ed:f6:ce:0d:87:cd:43:03:
bf:67:ef:ff:fd:da:98:cc:22:ab:5e:8d:7b:43:d3:
90:4d
Exponent: 65537 (0x10001)
Private-Key: (2048 bit)
modulus:
00:aa:5a:cc:30:52:f1:e9:49:3d:a6:25:00:33:29:
a6:fa:f7:53:e0:3c:73:4c:91:41:66:20:ec:62:1f:
27:2a:2a:6c:0f:90:f8:d9:7e:d5:ec:72:7b:38:8c:
ca:12:60:f8:d1:fb:f2:65:7c:b1:3a:b6:4e:26:ba:
5b:86:cc:30:f2:fc:be:c3:a2:00:b9:ea:81:fa:1c:
22:4e:f7:be:a1:1a:66:90:13:b6:12:66:26:23:6d:
22:15:7d:3b:a4:99:44:38:fa:1c:70:63:4e:50:6f:
66:38:6c:f6:1a:13:e1:c7:dc:a6:a1:eb:6f:f9:c9:
59:c8:30:dc:c2:1b:dc:6c:9d:ea:0c:3d:52:5a:00:
ea:c9:c9:85:51:21:9f:ec:95:b3:dc:c2:50:21:29:
c2:64:6c:1e:34:36:d8:61:59:ab:3c:a2:cc:e8:ef:
57:c3:7f:49:86:be:e3:42:88:1b:39:10:b8:2f:fa:
81:ef:a0:94:99:0c:71:ae:1e:82:7f:e3:6e:00:6e:
02:13:66:bb:a9:31:58:ec:90:39:9c:bc:9c:8c:90:
e9:20:f7:20:8e:d6:a3:a3:df:a2:4a:0f:0f:39:b5:
57:b9:ef:6a:27:e0:1a:ed:f6:ce:0d:87:cd:43:03:
bf:67:ef:ff:fd:da:98:cc:22:ab:5e:8d:7b:43:d3:
90:4d
publicExponent: 65537 (0x10001)
privateExponent:
66:a4:ce:e3:4f:16:f3:b9:6d:ab:ee:1f:70:b4:68:
28:4f:5d:fa:7e:71:fa:70:8b:37:3e:1f:30:00:15:
59:12:b6:89:aa:90:46:7c:65:e9:52:11:6c:c1:68:
00:2a:ed:c1:98:4d:35:59:2c:70:73:e8:22:ed:a6:
b8:51:d0:2c:98:9d:58:c3:04:2d:01:5f:cf:93:a4:
18:70:ae:2b:e3:fc:68:53:78:21:1d:eb:5c:ed:24:
dc:4d:d8:e2:14:77:46:dd:6c:c5:4b:10:a4:e6:7a:
71:05:36:44:00:36:ca:75:e8:f1:27:2b:11:16:81:
42:5e:2e:a5:c6:a3:c9:cd:60:59:ce:72:71:76:c8:
ca:ba:f0:45:c3:86:07:7b:22:20:c4:74:c6:a8:ab:
7c:2c:f8:de:ea:25:95:81:79:33:54:67:7b:61:91:
80:a8:1f:4c:38:32:d4:4d:2e:a8:7d:9b:d4:1a:3e:
6b:ca:50:3c:a0:61:0e:00:ad:f4:5c:0f:26:1a:59:
00:3c:bd:ee:c3:e8:d0:b8:9b:0e:44:89:49:d1:24:
a4:39:15:dc:0e:c5:d5:41:a2:4a:f4:e5:e3:23:c7:
98:8a:87:f7:18:a6:e2:7b:27:83:f6:fb:62:42:46:
ae:de:ba:48:ad:07:39:40:da:65:17:d1:d2:ed:df:
01
prime1:
00:dd:dc:70:b5:70:ea:10:20:28:40:a0:c3:b8:70:
6d:3d:84:c0:57:2d:69:fc:e9:d4:55:ed:4f:ac:3d:
c2:e9:19:49:f0:ab:c6:bd:99:9e:0f:e5:a4:61:d4:
b3:c5:c2:b1:e4:3a:10:ff:e6:cd:ce:6e:2d:93:bc:
87:12:92:87:7c:d3:dd:bc:32:54:9e:fa:67:b1:9d:
e2:27:53:e6:03:a7:22:17:45:63:0d:42:f3:96:5d:
a3:e0:9c:93:f0:42:8b:bb:95:34:e6:f6:0b:f7:b6:
c5:59:a0:b5:2a:71:59:c0:f2:7e:bf:95:2d:dd:6d:
94:23:2a:95:4a:4f:f1:d0:93
prime2:
00:c4:91:6a:33:1b:db:24:eb:fd:d3:69:e9:3c:e2:
a2:2d:23:7a:92:65:a8:a0:50:1d:0a:2b:b4:f0:64:
e4:40:57:f3:dc:f7:65:18:7d:51:75:73:b9:d6:67:
9b:0e:94:5f:37:02:6c:7f:eb:b9:13:4b:bf:8e:65:
22:0b:2c:c6:8d:2a:a2:88:ec:21:e3:f9:0b:78:b4:
1d:d0:44:e6:36:0d:ec:3c:8f:0a:c7:3b:0d:91:65:
b7:de:a3:c9:a3:2a:8c:7f:1f:a1:d2:6e:9b:ee:23:
78:c1:30:76:87:af:a8:11:a4:15:b4:54:16:d8:94:
71:5c:64:30:43:58:b5:07:9f
exponent1:
2f:91:e8:88:be:e1:30:fb:f4:25:87:52:ef:e5:0b:
47:39:83:94:2d:a4:a0:19:f2:f1:49:a4:df:a5:8e:
79:34:76:ea:27:aa:c1:54:82:d3:9d:c5:95:44:6a:
17:69:1b:83:77:ff:d5:1e:c3:da:13:3d:aa:83:ad:
e2:89:90:8b:6f:52:07:dc:32:d0:b3:98:30:39:4e:
18:68:a0:d4:ff:ad:0b:98:51:18:b2:d6:4f:d3:5c:
23:f8:ee:af:81:55:3c:af:4d:5c:88:3d:20:ac:0b:
bc:9f:fc:b8:50:fd:91:a5:6d:0f:df:08:aa:85:a8:
51:b1:fb:b8:a7:53:8e:09
exponent2:
7d:46:0b:7f:ad:06:19:de:c8:b2:7e:f2:25:5a:6e:
6f:04:08:6e:da:99:00:2a:6e:87:77:d9:65:c7:76:
ec:46:e1:64:f6:ca:18:34:6d:c0:c3:d3:31:00:70:
82:77:2e:c3:59:29:1a:d1:78:ef:02:3c:7f:9c:96:
78:b6:bd:87:64:1f:97:d1:9d:bb:b3:91:8b:08:87:
63:9f:35:74:47:a5:41:e7:0b:c0:73:33:2f:71:bb:
20:0a:14:4c:87:a6:68:b2:19:28:8a:53:98:0e:45:
3c:22:0d:b8:65:cb:60:0a:c9:c6:56:3d:05:24:7d:
a6:9b:37:63:04:5a:c3:13
coefficient:
00:cc:d7:5c:e6:0e:7b:79:d4:cb:4f:6d:82:a7:45:
90:67:90:dc:d3:83:62:f1:4b:17:43:5c:4a:ea:bf:
38:25:c3:6f:34:e2:05:91:5e:60:d6:de:6d:07:1a:
73:71:b3:1d:73:f2:3c:60:ed:ec:42:d4:39:f8:a4:
ae:d5:aa:40:1e:90:b1:eb:b1:05:a3:2f:03:5f:c6:
b7:07:4c:df:0f:c4:a9:80:8c:31:f5:e2:01:00:73:
8a:25:03:84:4e:48:7a:31:8e:e6:b8:04:4c:44:61:
7d:e4:87:1c:57:4f:45:44:33:bb:f3:ae:1c:d2:e1:
99:ed:78:29:76:4d:8c:6d:91
Related, you never ask how to encrypt or decrypt with a RSA key, yet you claim the answer to the encryption and decryption problems is shown in the code in your answer.
You seem to have made the question a moving target :) You should probably avoid that on Stack Overflow (I think its OK to do in those user thread forums). On Stack Overflow, you should ask a separate question.
You can extract the RSA public key from RSA keypair using d2i_RSAPublicKey and i2d_RSAPublicKey (link). Use i2d_RSAPublicKey to encode your keypair to PKCS#1 RSAPublicKey stucture, store it in a bytestring, then use d2i_RSAPublicKey to decode it back to RSA key struct.
I've found a solution to my question among other Stack-Overflow posts and namely Reading Public/Private Key from Memory with OpenSSL
The answer i was looking for is answered by #SquareRootOfTwentyThree is his last line of code,
After extracting the Public key into a BIO variable called pub:
PEM_write_bio_RSAPublicKey(pub, keypair);
i can send the variable pub across the network, and after it reaches the other side create a RSA variable and put pub inside it:
SOLUTION:
RSA *keypair2 = NULL;
PEM_read_bio_RSAPublicKey( pub, &keypair2, NULL, NULL);
After i've done this i can successfully encrypt the message as usual, using keypair2:
ENCRYPTION:
encrypt = (char*)malloc(RSA_size(keypair));
int encrypt_len;
err = (char*)malloc(130);
if((encrypt_len = RSA_public_encrypt(strlen(msg)+1, (unsigned char*)msg,
(unsigned char*)encrypt, keypair2 ,RSA_PKCS1_OAEP_PADDING)) == -1) {
ERR_load_crypto_strings();
ERR_error_string(ERR_get_error(), err);
fprintf(stderr, "Error encrypting message: %s\n", err);
}
I can then send this encrypt variable back to the first machine, and decrypt it as usual, using my original keypair, without having to send it over the network.
DECRYPTION:
decrypt = (char*)malloc(encrypt_len);
if(RSA_private_decrypt(encrypt_len, (unsigned char*)encrypt, (unsigned char*)decrypt,
keypair, RSA_PKCS1_OAEP_PADDING) == -1) {
ERR_load_crypto_strings();
ERR_error_string(ERR_get_error(), err);
fprintf(stderr, "Error decrypting message: %s\n", err);
}
Thank you everyone for contributing to this post!!!
Reviewing your code, it appears that you successfully separated the public and private keys into the strings pub_key and pri_key, but then used printf to output them which pasted them back together. To just print the public key change the printf statement to:
printf("\n%s\n", pub_key);