BER decode error - c++

I am doing the RSA signature verify, I will always get this error
terminate called after throwing an instance of 'CryptoPP::BERDecodeErr'
what(): BER decode error
Aborted (core dumped)
I don't understand why I get this error, I never call the BERDecode before.
This my code segment, I had tried to trace the error it happens in the second line of the code:
FileSource pubFile(publicKey_file.c_str(), true, new HexDecoder);
RSASS<PSSR, SHA1>::Verifier pub(pubFile);
FileSource signatureFile(sig_file.c_str(), true, new HexDecoder);
if (signatureFile.MaxRetrievable() != pub.SignatureLength()) {
return false;
}
SecByteBlock signature(pub.SignatureLength());
signatureFile.Get(signature, signature.size());
bool result = pub.VerifyMessage((const byte*)messages_file.c_str(),
messages_file.length(), signature, signature.size());
return result;
I could define what's going wrong, hope to get some help. Thank you.

You are trying to load a public key, which needs to be parsed before you can do any verification. For this you give the public key data to the Verifier constructor. This constructor tries to parse the public keys.
Now public keys are generally encoded data structures. These data structures are described by a data description language called ASN.1 or Abstract Syntax Notation 1 and encoded using a scheme called BER, the Basic Encoding Rules for ASN.1.
So what happens is that the constructor tries to read the public key and therefore calls BERDecode so make sense of the input. Unfortunately the input is likely not binary BER encoded at all.
So to resolve this you need to either use additional calls in your application to convert to BER or public key object, or you need to convert your key to BER. If the key is ASCII armored (PEM format) then you can use:
$ openssl rsa -pubin -inform PEM -in <filename of key in PEM format> -outform DER -out <filename of key in DER format>
If this doesn't work please include the public key into your question so we can check why it doesn't parse.

According to:
$ echo "30819D300D06092A864886F70D010101050003818B0030818702818100DD2CED773D6F9A
E4A63F2DAEEF9019C056D4A35F338764FAAE85EDCBFB13FC9E53F13CEFADEF58C65B501C3D2D13DC
DE65282B7781C45259065F991C4184E6E6DEDB3087472B4AC4BDD74FDF4D3C893257D68722326516
53A4882588C61C0F4FB096C5906F2F88E0480513A2B1BA6418869DB01C9D9A2FB4BECADE54658D55
2F020111" | xxd -r -p > key.ber
And then:
$ dumpasn1 key.ber
0 157: SEQUENCE {
3 13: SEQUENCE {
5 9: OBJECT IDENTIFIER rsaEncryption (1 2 840 113549 1 1 1)
16 0: NULL
: }
18 139: BIT STRING, encapsulates {
22 135: SEQUENCE {
25 129: INTEGER
: 00 DD 2C ED 77 3D 6F 9A E4 A6 3F 2D AE EF 90 19
: C0 56 D4 A3 5F 33 87 64 FA AE 85 ED CB FB 13 FC
: 9E 53 F1 3C EF AD EF 58 C6 5B 50 1C 3D 2D 13 DC
: DE 65 28 2B 77 81 C4 52 59 06 5F 99 1C 41 84 E6
: E6 DE DB 30 87 47 2B 4A C4 BD D7 4F DF 4D 3C 89
: 32 57 D6 87 22 32 65 16 53 A4 88 25 88 C6 1C 0F
: 4F B0 96 C5 90 6F 2F 88 E0 48 05 13 A2 B1 BA 64
: 18 86 9D B0 1C 9D 9A 2F B4 BE CA DE 54 65 8D 55
: 2F
157 1: INTEGER 17
: }
: }
: }
You have a subjectPublicKeyInfo. I believe all you need to do is call Load, but it assumes you have a well-formed key:
RSASS<PSSR, SHA1>::Verifier pub;
pub.AccessKey().Load(pubFile);
Here's the whole program:
$ cat test.cxx
#include "cryptlib.h"
#include "filters.h"
#include "pssr.h"
#include "sha.h"
#include "rsa.h"
#include "hex.h"
#include <string>
#include <iostream>
int main()
{
using namespace CryptoPP;
std::string encodedKey = "30819D300D06092A864886F70D010101050003818B00"
"30818702818100DD2CED773D6F9AE4A63F2DAEEF9019C056D4A35F338764FAAE8"
"5EDCBFB13FC9E53F13CEFADEF58C65B501C3D2D13DCDE65282B7781C45259065F"
"991C4184E6E6DEDB3087472B4AC4BDD74FDF4D3C893257D6872232651653A4882"
"588C61C0F4FB096C5906F2F88E0480513A2B1BA6418869DB01C9D9A2FB4BECADE"
"54658D552F020111";
StringSource hexKey(encodedKey, true, new HexDecoder);
RSASS<PSSR, SHA1>::Verifier pub;
pub.AccessKey().Load(hexKey);
std::cout << "n: " << std::hex << pub.AccessKey().GetModulus() << std::endl;
std::cout << "e: " << std::dec << pub.AccessKey().GetPublicExponent() << std::endl;
return 0;
}
And finally:
$ ./test.exe
n: dd2ced773d6f9ae4a63f2daeef9019c056d4a35f338764faae85edcbfb13fc9e53f13cefadef5
8c65b501c3d2d13dcde65282b7781c45259065f991c4184e6e6dedb3087472b4ac4bdd74fdf4d3c8
93257d6872232651653a4882588c61c0f4fb096c5906f2f88e0480513a2b1ba6418869db01c9d9a2
fb4becade54658d552fh
e: 17.
This may a bit too restrictive:
if (signatureFile.MaxRetrievable() != pub.SignatureLength()) {
return false;
}
The actual signature length may be a tad bit shorter then MaxSignatureLength(), depending on how many leading 0's the exponentiation produces.
You might consider following one of the wiki examples. For example, from RSA Signature Schemes:
...
// Signing
RSASS<PSSR, SHA1>::Signer signer(privateKey);
RSASS<PSSR, SHA1>::Verifier verifier(publicKey);
// Setup
byte message[] = "RSA-PSSR Test";
size_t messageLen = sizeof(message);
////////////////////////////////////////////////
// Sign and Encode
SecByteBlock signature(signer.MaxSignatureLength(messageLen));
size_t signatureLen = signer.SignMessageWithRecovery(rng, message, messageLen, NULL, 0, signature);
// Resize now we know the true size of the signature
signature.resize(signatureLen);
////////////////////////////////////////////////
// Verify and Recover
SecByteBlock recovered(
verifier.MaxRecoverableLengthFromSignatureLength(signatureLen)
);
DecodingResult result = verifier.RecoverMessage(recovered, NULL, 0, signature, signatureLen);
if (!result.isValidCoding) {
throw Exception(Exception::OTHER_ERROR, "Invalid Signature");
}
////////////////////////////////////////////////
// Use recovered message
// MaxSignatureLength is likely larger than messageLength
recovered.resize(result.messageLength);
...

Related

Convert string to byte in crypto++

I am using the AES cipher with Crypto++. I have a key that recorded in the file during encryption. I extract key from file to string and try to use for decrypt.
Is there any way i can convert the string that contains the key string s1 to CryptoPP::byte? There fragment of code.
encoded.clear();
StringSource(key, sizeof(key), true,
new HexEncoder(
new StringSink(encoded)
));
ofstream fout1("key.txt");
fout1 << encoded;
fout1.close();
string s1;
ifstream TextFile1("key.txt");
while (!TextFile1.eof())
{
if (TextFile1.eof())
break;
TextFile1 >> s1;
}
I have a key that recorded in the file during encryption. I extract key from file to string and try to use for decrypt.
It sounds like you have a file structured similar to below:
[...key...][...iv...][...encrypted data...]
It is a bit unusual to store a key like that, but here is how it goes... Below I assume you are using AES-128 in CTR mode. That means [...key...] is 16 bytes, and [...iv...] is 16 bytes. The remainder is encrypted data.
I generate the sample file with:
$ head -c 128 < /dev/urandom > message.enc
$ hexdump -C message.enc
00000000 17 44 79 6b e6 96 ff d0 9e 3e 8c c4 fe 57 56 a2 |.Dyk.....>...WV.|
00000010 bb 59 9c a6 fb ab 73 de a7 a9 4a 22 14 6e c4 af |.Y....s...J".n..|
00000020 31 13 04 4d f2 79 f8 7c 7a 0b 16 2c bd be 6e 4c |1..M.y.|z..,..nL|
00000030 b6 61 0a 6c 33 d3 f0 73 25 44 ec f5 cd f5 cd da |.a.l3..s%D......|
00000040 3d 13 72 98 65 19 e1 c5 f8 49 1e 07 c7 dc ac b7 |=.r.e....I......|
00000050 ce 03 d1 90 94 08 aa 9d a0 8b b0 cd ff 9c b9 67 |...............g|
00000060 8a 2c 6f d9 7e fa d2 07 0f a0 48 99 57 77 2b d1 |.,o.~.....H.Ww+.|
00000070 c7 28 2a bc 80 22 21 fb 4a ba cb b2 0e b6 2c ff |.(*.."!.J.....,.|
The key is 17 44 ... 56 a2. The iv is bb 59 ... c4 af. The encrypted data starts at 31 13 04 4d....
And the program:
$ cat test.cxx
#include "filters.h"
#include "files.h"
#include "modes.h"
#include "aes.h"
#include "hex.h"
#include <iostream>
int main()
{
using namespace CryptoPP;
// Key and iv are stored at the head of the file
SecByteBlock key(16), iv(16);
FileSource fs("message.enc", false /* DO NOT Pump All */);
// Attach new filter
ArraySink ak(key, key.size());
fs.Detach(new Redirector(ak));
fs.Pump(16); // Pump first 16 bytes
// Attach new filter
ArraySink av(iv, iv.size());
fs.Detach(new Redirector(av));
fs.Pump(16); // Pump next 16 bytes
CTR_Mode<AES>::Decryption decryptor;
decryptor.SetKeyWithIV(key, key.size(), iv, iv.size());
// Detach previously attached filter, attach new filter
ByteQueue queue;
fs.Detach(new StreamTransformationFilter(decryptor, new Redirector(queue)));
fs.PumpAll(); // Pump remainder of bytes
std::cout << "Key: ";
StringSource(key, key.size(), true, new HexEncoder(new FileSink(std::cout)));
std::cout << std::endl;
std::cout << "IV: ";
StringSource(iv, iv.size(), true, new HexEncoder(new FileSink(std::cout)));
std::cout << std::endl;
std::cout << "Message: ";
HexEncoder hex(new FileSink(std::cout));
queue.TransferTo(hex);
std::cout << std::endl;
return 0;
}
You can call either Attach or Detach to attach a new filter. Both attach a new filter. The difference is, Attach returns the old filter and you have to free it. Detach deletes the old filter for you.
Finally:
$ g++ -Wall -I . test.cxx ./libcryptopp.a -o test.exe
$ ./test.exe
Key: 1744796BE696FFD09E3E8CC4FE5756A2
IV: BB599CA6FBAB73DEA7A94A22146EC4AF
Message: 84F6DC079CA04BDFACB645CB11CC2F828573F1841B1B9267CB296B6A977BE19D68B05FA
AF41AB73498F45629EE050B132174A2798C12C29A7033ADD1999BECD00B101F2616112D7E6968EA0
A1BE159CD0EE43549BA6534C8D4AB8F5E7D9E3E44
Unrelated to Crypto++, you usually want to avoid this:
while (!TextFile1.eof())
{
if (TextFile1.eof())
break;
TextFile1 >> s1;
}
I believe it is usually better to follow Why is iostream::eof inside a loop condition considered wrong? (I even think TextFile1 >> s1; should be in between the TextFile1.eof() checks. You don't reach eof() until you try to perform a read).

Sending PublicKey within packet payload

For an academic network application, I'd like to set up an RSA key exchange between 2 virtual machines. I am using Crypto++ to generate the RSA::PublicKey, and I must now send it within a custom layer-2 frame (the packet will be crafted with libcrafter).
The thing is, I have no idea of how write the key in the network, such as the receiver, sniffing the packet, is able to re-build, somehow, the RSA::PublicKey.
I tried to save it raw in a string, but as they say here, the PublicKey class contains other data, then simply the raw key (data that I don't need). nevertheless, I manage to success that, but at the reception I can't simply rebuild the PublicKey...
Could it be possible, somehow, to concatenate the modulus, the primes and the public exponent, in order to rebuild the publicKey at the reception?
Sender
Here is the code I use at the sender. It's the essential lines, but my program has other functionality, and it would be too long to post it entirely here).
AutoSeededRandomPool rng;
RSA::PrivateKey privateKey;
privateKey.GenerateRandomWithKeySize(rng, 3072);
RSA::PublicKey publicKey(privateKey);
cout << ">> Key generated" <<endl;
/* Convert key to string then to const char* */
std::string publicKeyString;
publicKey.BEREncode( StringSink(publicKeyString).Ref() );
const char * publicKeyChar = publicKeyString.c_str();
cout <<"key size : "<<publicKeyString.size()<< endl;
/* Send Packet */
Crafter::RawLayer type1("K");
Crafter::RawLayer key_send(publicKeyChar);
//Crafter::RawLayer key_send(publicKeyString.c_str(), publicKeyString.length());
Crafter::Packet packet_key (ether_header / type1 / key_send);
packet_key.Send(iface);
Receiver
And here is my attempt to recover the key.
/* Extract Payload */
PayloadLayer *payload_rcv = pack_recu.getLayerOfType<PayloadLayer>();
size_t payload_size = payload_rcv->getPayloadLen() ;
Crafter::byte *payload = payload_rcv->getPayload();
cout << ">> Public Key recieved"<<endl;
// Convert into RSA::PublicKey
stringstream ss;
for (int i=0; i< payload_size; i++)
ss << payload[i];
string payload_string = ss.str();
cout << "Payload Size: "<<payload_size<<endl;
cin.get();
StringSource stringSource(payload_string, true);
RSA::PublicKey publicKey2;
publicKey2.BERDecode(stringSource);
data->publicKey = publicKey2;
And here is the result of running the program:
terminate called after throwing an instance of 'CryptoPP::BERDecodeErr'
what(): BER decode error
I'm sure the error comes from the conversion from string to publicKey... The BERDecode function war originally thought to recover the key from a file...
Does anyone has a solution ? I think that sending apart all the elements to rebuild the key could be better, but I can't figure how to do it...
publicKey.BEREncode( StringSink(publicKeyString).Ref() );
const char * publicKeyChar = publicKeyString.c_str();
A BER encoding likely has an embedded NULL, so you cannot use customary C-string operations on it:
const char * publicKeyChar = publicKeyString.c_str();
...
Crafter::RawLayer key_send(publicKeyChar);
When writing the encoded public key, the following looks correct. You should uncomment it and use it (I use data and size because it logically separates from C-strings and length).
Crafter::RawLayer key_send(publicKeyString.data(), publicKeyString.size());
So the whole Crypto++ thing might look like the following:
// Host's private key, generate or Load() it...
RSA::PrivateKey privKey;
...
// Create a public key from the private key
RSA::PublicKey pubKey(privKey);
// Temporaries
string spki;
StringSink ss(spki);
// Use Save to DER encode the Subject Public Key Info (SPKI)
pubKey.Save(ss);
Crafter::RawLayer key_send(spki.data(), spki.size());
Then, to reconstruct it:
// Key payload
const PayloadLayer& payload_rcv = *pack_recu.getLayerOfType<PayloadLayer>();
// Get a contiguous array (I don't know what this is called in Crafter)
payload_rcv.PullUp();
// Use the array directly to avoid the copy
ArraySource as(payload_rcv.data(), payload_rcv.size(), true /*pumpAll*/);
RSA::PublicKey pubKey;
// Use Load to BER decode the Subject Public Key Info (SPKI)
pubKey.Load(as);
// Validate it before using it
AutoSeededRandomPool prng;
pubKey.ThrowIfInvalid(prng);
I think its important to use the Subject Public Key Info (SPKI) rather than just the Public Key. The SPKI includes an algorithm identifier by way of an OID. It will make algorithm agility a little easier later on. Later, you can switch to a ECDSA key or an ed25519 key, and they key type will be part of the key payload.
terminate called after throwing an instance of 'CryptoPP::BERDecodeErr'
what(): BER decode error
Obviously, you should set up a try/catch, and catch a BERDecodeErr:
try
{
// Use Load to BER decode the Subject Public Key Info (SPKI)
pubKey.Load(as);
// Validate it before using it
AutoSeededRandomPool prng;
pubKey.ThrowIfInvalid(prng);
}
catch(const BERDecodeErr& ex)
{
cerr << ex.what() << endl;
}
catch(const InvalidMaterial& ex)
{
cerr << ex.what() << endl;
}
And here's what the Subject Public Key Info looks like:
$ cat cryptopp-test.cpp
...
int main(int argc, char* argv[])
{
AutoSeededRandomPool prng;
RSA::PrivateKey rsaPrivate;
rsaPrivate.GenerateRandomWithKeySize(prng, 3072);
RSA::PublicKey rsaPublic(rsaPrivate);
FileSink sink("rsa-public.der");
rsaPublic.Save(sink);
return 0;
}
And then use something like Peter Gutmann's dumpasn1:
$ dumpasn1 rsa-public.der
0 416: SEQUENCE {
4 13: SEQUENCE {
6 9: OBJECT IDENTIFIER rsaEncryption (1 2 840 113549 1 1 1)
17 0: NULL
: }
19 397: BIT STRING, encapsulates {
24 392: SEQUENCE {
28 385: INTEGER
: 00 CE B0 19 0D 0C EB 87 BD 6B 51 6C BB 00 9C EE
: 1D 75 9C 28 DC 0E 8E 88 9A 95 8A 3B 6C BD 1F 3F
: 03 05 22 8E 3D 19 33 D7 C5 A3 28 4F 13 3D 9E BF
: 5A 54 51 AE D6 DA C3 AC 1D 9C 4C A3 47 C0 04 8F
: 9D 0A DD 38 60 56 E3 9C DB 7C EA A8 3F 52 93 99
: 40 90 14 41 0A 3B 58 F2 13 9F 38 64 18 DD 62 55
: D2 32 53 A0 D5 1A 54 E7 8D 23 01 E0 97 ED F9 C7
: 68 9F E2 00 48 99 53 40 6E 7E 5C DA 47 39 4A 41
: [ Another 257 bytes skipped ]
417 1: INTEGER 17
: }
: }
: }
0 warnings, 0 errors.

Use OpenSSL RSA key with .Net

I am using openssl 0.9.6g and I have created public/private keypair using RSA_generate_key(). When I save the key with PEM_write_bio_RSAPublicKey, it gives me keys like:
-----BEGIN RSA PUBLIC KEY-----
...
-----END RSA PUBLIC KEY-----
I have another module in .NET which throws an exception when passed in this key due to its format. It takes format like:
-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----
How to convert my keys to this format. I am using C++.
In .NET, I am using openssl.net, the code is as follows:
string publicKey = #"-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBAKGtqUVBBqcGCRYa7Sb6JVQirOX3hggWP2k7CzEtbF/soOONK510Kefm
omXBrGn2t79ES+hAcCvGSiiVZGuEb3UPiznzbiY150SME5nRC+zU0vvdX64ni0Mu
DeUlGcxM1eWSpozO71at6mxLloEMUg0oSWHfAlS5a4LVaURrJqXfAgMBAAE=
-----END RSA PUBLIC KEY-----";
Encoding enc = Encoding.ASCII;
string text = "hello world";
byte[] msg = enc.GetBytes(text);
CryptoKey key = CryptoKey.FromPublicKey(publicKey, "");
RSA rsa = key.GetRSA();
byte[] res = rsa.PublicEncrypt(msg, RSA.Padding.PKCS1);
The exception comes in line:
CryptoKey key = CryptoKey.FromPublicKey(publicKey, "");
If I use the key:
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCbhcU+fhYmYLESZQAj1hKBXsNY
si0kYHNkxpP7ftxZiTFowWUVXHzQgkcYiCNnp3pt1eG6Vt0WDzyFYXqUUqugvX41
gkaIrKQw/sRiWEx49krcz7Vxr3dufL6Mg3eK7NyWDGsqwFrx/qVNqdhsHg12PGNx
IMY4UBtxin2A8pd4OwIDAQAB
-----END PUBLIC KEY-----
It works fine.
I was looking around for this issue. I think what I am looking for is "how to convert rsa public key from pkcs#1 to x509 format.
I am using openssl 0.9.6g and I have created public/private keypair
using RSA_generate_key(). It gives me keys like:
-----BEGIN RSA PUBLIC KEY-----
...
-----END RSA PUBLIC KEY-----
I think what I am looking for is "how to convert rsa public key from pkcs#1 to x509 format.
Yeah, .Net can consume some ASN.1/DER encoded keys, and some PEM encoded keys. The difference is PKCS encoding versus Traditional encoding (OpenSSL calls it "Traditional"). The traditional encoding is the SubjectPublicKeyInfo and it includes the OID and the public key.
So you are looking for either an ASN.1/DER encoding or a PEM encoding that writes SubjectPublicKeyInfo, and not just the public key.
I have another module in .NET which throws an exception when passed in
this key due to its format. It takes format like:
-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----
In this case, use PEM_write_bio_PUBKEY rather than PEM_write_bio_RSAPublicKey.
PEM_write_bio_PUBKEY writes the SubjectPublicKeyInfo; while PEM_write_bio_RSAPublicKey writes only the public key.
You will need an EVP_PKEY, so use EVP_PKEY_set1_RSA to convert it.
This is a PKCS key in OpenSSL. Its just the public key. You would use PEM_write_RSAPublicKey to write it:
-----BEGIN RSA PUBLIC KEY-----
And this is a Traditional key in OpenSSL. Its the SubjectPublicKeyInfo, and it includes an OID for the algorithm (rsaEncryption) and the public key. You would use PEM_write_bio_PUBKEY to write it:
-----BEGIN PUBLIC KEY-----
Instead of saving the key with PEM_write_RSAPublicKey, you should write out the SubjectPublicKeyInfo structure in ASN.1/DER format with i2d_RSA_PUBKEY_bio; or write it out in PEM format with PEM_write_bio_PUBKEY.
The program below creates a RSA key pair, and then writes out the public key in all the formats. Be sure to save the private key, too.
(And I'm glad you have the C++ tag. unique_ptr makes this exercise so much easier).
#include <memory>
using std::unique_ptr;
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/bio.h>
#include <openssl/x509.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)>;
using EVP_KEY_ptr = std::unique_ptr<EVP_PKEY, decltype(&::EVP_PKEY_free)>;
using BIO_FILE_ptr = std::unique_ptr<BIO, decltype(&::BIO_free)>;
int main(int argc, char* argv[])
{
int rc;
RSA_ptr rsa(RSA_new(), ::RSA_free);
BN_ptr bn(BN_new(), ::BN_free);
BIO_FILE_ptr pem1(BIO_new_file("rsa-public-1.pem", "w"), ::BIO_free);
BIO_FILE_ptr pem2(BIO_new_file("rsa-public-2.pem", "w"), ::BIO_free);
BIO_FILE_ptr der1(BIO_new_file("rsa-public-1.der", "w"), ::BIO_free);
BIO_FILE_ptr der2(BIO_new_file("rsa-public-2.der", "w"), ::BIO_free);
rc = BN_set_word(bn.get(), RSA_F4);
ASSERT(rc == 1);
// Generate key
rc = RSA_generate_key_ex(rsa.get(), 2048, bn.get(), NULL);
ASSERT(rc == 1);
// Convert RSA key to PKEY
EVP_KEY_ptr pkey(EVP_PKEY_new(), ::EVP_PKEY_free);
rc = EVP_PKEY_set1_RSA(pkey.get(), rsa.get());
ASSERT(rc == 1);
//////////
// Write just the public key in ASN.1/DER
// Load with d2i_RSAPublicKey_bio
rc = i2d_RSAPublicKey_bio(der1.get(), rsa.get());
ASSERT(rc == 1);
// Write just the public key in PEM
// Load with PEM_read_bio_RSAPublicKey
rc = PEM_write_bio_RSAPublicKey(pem1.get(), rsa.get());
ASSERT(rc == 1);
// Write SubjectPublicKeyInfo with OID and public key in ASN.1/DER
// Load with d2i_RSA_PUBKEY_bio
rc = i2d_RSA_PUBKEY_bio(der2.get(), rsa.get());
ASSERT(rc == 1);
// Write SubjectPublicKeyInfo with OID and public key in PEM
// Load with PEM_read_bio_PUBKEY
rc = PEM_write_bio_PUBKEY(pem2.get(), pkey.get());
ASSERT(rc == 1);
return 0;
}
The set1 in EVP_PKEY_set1_RSA bumps the reference count, so you don't get a segfault on a double free.
After executing the program, you get the expected PEM and ASN.1/DER:
$ cat rsa-public-1.pem
-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEA0cgFv6wEcqoOhPtHdVmX4YFlCwodnSqooeCxFF1XadTS4sZkVJTC
kszHmRqXiXL2NmqnuDQsq6nLd+sNoU5yJJ+W1hwo7UToCyJ/81tS4n6mXvF8oilP
8YudD5QnBdW9LhqttBIN4Gk+Cxun+HG1rSJLGP9yiPPFd7DPiFz0Gd+juyWznWnP
gapDIWEKqANKma3j6b9eopBDWB0XAgU0HQ71MSNbcsPvDd23Ftx0re/7jG53V7Bn
eBy7fQsPmxcn4c74Lz4CvhOr7VdQpeBzNeG2CtkefKWyTk7Vu4FZnAgNd/202XAr
c6GmEQqD2M2zXH/nVZg5oLznECDVQ1x/pwIDAQAB
-----END RSA PUBLIC KEY-----
$ cat rsa-public-2.pem
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0cgFv6wEcqoOhPtHdVmX
4YFlCwodnSqooeCxFF1XadTS4sZkVJTCkszHmRqXiXL2NmqnuDQsq6nLd+sNoU5y
JJ+W1hwo7UToCyJ/81tS4n6mXvF8oilP8YudD5QnBdW9LhqttBIN4Gk+Cxun+HG1
rSJLGP9yiPPFd7DPiFz0Gd+juyWznWnPgapDIWEKqANKma3j6b9eopBDWB0XAgU0
HQ71MSNbcsPvDd23Ftx0re/7jG53V7BneBy7fQsPmxcn4c74Lz4CvhOr7VdQpeBz
NeG2CtkefKWyTk7Vu4FZnAgNd/202XArc6GmEQqD2M2zXH/nVZg5oLznECDVQ1x/
pwIDAQAB
-----END PUBLIC KEY-----
$ dumpasn1 rsa-public-1.der
0 266: SEQUENCE {
4 257: INTEGER
: 00 D1 C8 05 BF AC 04 72 AA 0E 84 FB 47 75 59 97
: E1 81 65 0B 0A 1D 9D 2A A8 A1 E0 B1 14 5D 57 69
: D4 D2 E2 C6 64 54 94 C2 92 CC C7 99 1A 97 89 72
: F6 36 6A A7 B8 34 2C AB A9 CB 77 EB 0D A1 4E 72
: 24 9F 96 D6 1C 28 ED 44 E8 0B 22 7F F3 5B 52 E2
: 7E A6 5E F1 7C A2 29 4F F1 8B 9D 0F 94 27 05 D5
: BD 2E 1A AD B4 12 0D E0 69 3E 0B 1B A7 F8 71 B5
: AD 22 4B 18 FF 72 88 F3 C5 77 B0 CF 88 5C F4 19
: [ Another 129 bytes skipped ]
265 3: INTEGER 65537
: }
0 warnings, 0 errors.
$ dumpasn1 rsa-public-2.der
0 290: SEQUENCE {
4 13: SEQUENCE {
6 9: OBJECT IDENTIFIER rsaEncryption (1 2 840 113549 1 1 1)
17 0: NULL
: }
19 271: BIT STRING, encapsulates {
24 266: SEQUENCE {
28 257: INTEGER
: 00 D1 C8 05 BF AC 04 72 AA 0E 84 FB 47 75 59 97
: E1 81 65 0B 0A 1D 9D 2A A8 A1 E0 B1 14 5D 57 69
: D4 D2 E2 C6 64 54 94 C2 92 CC C7 99 1A 97 89 72
: F6 36 6A A7 B8 34 2C AB A9 CB 77 EB 0D A1 4E 72
: 24 9F 96 D6 1C 28 ED 44 E8 0B 22 7F F3 5B 52 E2
: 7E A6 5E F1 7C A2 29 4F F1 8B 9D 0F 94 27 05 D5
: BD 2E 1A AD B4 12 0D E0 69 3E 0B 1B A7 F8 71 B5
: AD 22 4B 18 FF 72 88 F3 C5 77 B0 CF 88 5C F4 19
: [ Another 129 bytes skipped ]
289 3: INTEGER 65537
: }
: }
: }
0 warnings, 0 errors.
Related, see How to generate RSA private key using openssl?. It shows you how to write a RSA public and private key in a number of formats.

Load RSA private key from a PEM encoded private key

I'm trying to load an RSA private key from a std::string that contains the private key in PEM format, like this:
-----BEGIN RSA PRIVATE KEY-----
MIIBOgIBAAJBAK8Q+ToR4tWGshaKYRHKJ3ZmMUF6jjwCS/u1A8v1tFbQiVpBlxYB
paNcT2ENEXBGdmWqr8VwSl0NBIKyq4p0rhsCAQMCQHS1+3wL7I5ZzA8G62Exb6RE
INZRtCgBh/0jV91OeDnfQUc07SE6vs31J8m7qw/rxeB3E9h6oGi9IVRebVO+9zsC
IQDWb//KAzrSOo0P0yktnY57UF9Q3Y26rulWI6LqpsxZDwIhAND/cmlg7rUz34Pf
SmM61lJEmMEjKp8RB/xgghzmCeI1AiEAjvVVMVd8jCcItTdwyRO0UjWU4JOz0cnw
5BfB8cSIO18CIQCLVPbw60nOIpUClNxCJzmMLbsrbMcUtgVS6wFomVvsIwIhAK+A
YqT6WwsMW2On5l9di+RPzhDT1QdGyTI5eFNS+GxY
-----END RSA PRIVATE KEY-----
And I wonder if anyone can help me to use this key instead of generating a random with the following statement.
CryptoPP::RSA::PrivateKey rsaPrivate;
rsaPrivate.GenerateRandomWithKeySize (rnd, 512);
The key is PEM encoded. You need to strip the PEM header and footer, then convert from Base64 back to DER/BER, and finally use Crypto++'s BERDecodePrivateKey.
There's some reading on the subject at the Crypto++ wiki under Keys and Formats. Below is the code to perform the conversion (I don't believe Stack Overflow has a working example of it in Crypto++).
string RSA_PRIV_KEY =
"-----BEGIN RSA PRIVATE KEY-----\n"
"MIIBOgIBAAJBAK8Q+ToR4tWGshaKYRHKJ3ZmMUF6jjwCS/u1A8v1tFbQiVpBlxYB\n"
"paNcT2ENEXBGdmWqr8VwSl0NBIKyq4p0rhsCAQMCQHS1+3wL7I5ZzA8G62Exb6RE\n"
"INZRtCgBh/0jV91OeDnfQUc07SE6vs31J8m7qw/rxeB3E9h6oGi9IVRebVO+9zsC\n"
"IQDWb//KAzrSOo0P0yktnY57UF9Q3Y26rulWI6LqpsxZDwIhAND/cmlg7rUz34Pf\n"
"SmM61lJEmMEjKp8RB/xgghzmCeI1AiEAjvVVMVd8jCcItTdwyRO0UjWU4JOz0cnw\n"
"5BfB8cSIO18CIQCLVPbw60nOIpUClNxCJzmMLbsrbMcUtgVS6wFomVvsIwIhAK+A\n"
"YqT6WwsMW2On5l9di+RPzhDT1QdGyTI5eFNS+GxY\n"
"-----END RSA PRIVATE KEY-----";
static string HEADER = "-----BEGIN RSA PRIVATE KEY-----";
static string FOOTER = "-----END RSA PRIVATE KEY-----";
size_t pos1, pos2;
pos1 = RSA_PRIV_KEY.find(HEADER);
if(pos1 == string::npos)
throw runtime_error("PEM header not found");
pos2 = RSA_PRIV_KEY.find(FOOTER, pos1+1);
if(pos2 == string::npos)
throw runtime_error("PEM footer not found");
// Start position and length
pos1 = pos1 + HEADER.length();
pos2 = pos2 - pos1;
string keystr = RSA_PRIV_KEY.substr(pos1, pos2);
// Base64 decode, place in a ByteQueue
ByteQueue queue;
Base64Decoder decoder;
decoder.Attach(new Redirector(queue));
decoder.Put((const byte*)keystr.data(), keystr.length());
decoder.MessageEnd();
// Write to file for inspection
FileSink fs("decoded-key.der");
queue.CopyTo(fs);
fs.MessageEnd();
try
{
CryptoPP::RSA::PrivateKey rsaPrivate;
rsaPrivate.BERDecodePrivateKey(queue, false /*paramsPresent*/, queue.MaxRetrievable());
// BERDecodePrivateKey is a void function. Here's the only check
// we have regarding the DER bytes consumed.
ASSERT(queue.IsEmpty());
}
catch (const Exception& ex)
{
cerr << ex.what() << endl;
exit (1);
}
After loading the key, you can validate it with:
AutoSeededRandomPool prng;
bool valid = rsaPrivate.Validate(prng, 3);
if(!valid)
cerr << "RSA private key is not valid" << endl;
And print it with:
cout << "N: " << rsaPrivate.GetModulus() << endl << endl;
cout << "E: " << rsaPrivate.GetPublicExponent() << endl << endl;
cout << "D: " << rsaPrivate.GetPrivateExponent() << endl << endl;
If the key is password protected, then Crypto++ cannot decode it. The library lacks the support to perform the decryption. In this case, you can convert it to BER/DER using the following OpenSSL command. Then you can use the key material with Crypto++.
openssl pkcs8 -nocrypt -in rsa-key.pem -inform PEM -topk8 -outform DER -out rsa-key.der
The sample program wrote the key to file with this:
FileSink fs("decoded-key.der");
queue.CopyTo(fs);
fs.MessageEnd();
The CopyTo leaves the bytes in the queue for use later. You can dump the file with an ASN.1 tool, like Gutmann's dumpasn1:
$ dumpasn1 decoded-key.der
0 314: SEQUENCE {
4 1: INTEGER 0
7 65: INTEGER
: 00 AF 10 F9 3A 11 E2 D5 86 B2 16 8A 61 11 CA 27
: 76 66 31 41 7A 8E 3C 02 4B FB B5 03 CB F5 B4 56
: D0 89 5A 41 97 16 01 A5 A3 5C 4F 61 0D 11 70 46
: 76 65 AA AF C5 70 4A 5D 0D 04 82 B2 AB 8A 74 AE
: 1B
74 1: INTEGER 3
77 64: INTEGER
: 74 B5 FB 7C 0B EC 8E 59 CC 0F 06 EB 61 31 6F A4
: 44 20 D6 51 B4 28 01 87 FD 23 57 DD 4E 78 39 DF
: 41 47 34 ED 21 3A BE CD F5 27 C9 BB AB 0F EB C5
: E0 77 13 D8 7A A0 68 BD 21 54 5E 6D 53 BE F7 3B
143 33: INTEGER
: 00 D6 6F FF CA 03 3A D2 3A 8D 0F D3 29 2D 9D 8E
: 7B 50 5F 50 DD 8D BA AE E9 56 23 A2 EA A6 CC 59
: 0F
178 33: INTEGER
: 00 D0 FF 72 69 60 EE B5 33 DF 83 DF 4A 63 3A D6
: 52 44 98 C1 23 2A 9F 11 07 FC 60 82 1C E6 09 E2
: 35
213 33: INTEGER
: 00 8E F5 55 31 57 7C 8C 27 08 B5 37 70 C9 13 B4
: 52 35 94 E0 93 B3 D1 C9 F0 E4 17 C1 F1 C4 88 3B
: 5F
248 33: INTEGER
: 00 8B 54 F6 F0 EB 49 CE 22 95 02 94 DC 42 27 39
: 8C 2D BB 2B 6C C7 14 B6 05 52 EB 01 68 99 5B EC
: 23
283 33: INTEGER
: 00 AF 80 62 A4 FA 5B 0B 0C 5B 63 A7 E6 5F 5D 8B
: E4 4F CE 10 D3 D5 07 46 C9 32 39 78 53 52 F8 6C
: 58
: }
0 warnings, 0 errors.

ElGamal encryption example?

I apologise in advance for the n00bishness of asking this question, but I've been stuck for ages and I'm struggling to figure out what to do next. Essentially, I am trying to perform ElGamal encryption on some data. I have been given the public part of an ephemeral key pair and a second static key, as well as some data. If my understanding is correct, this is all I need to perform the encryption, but I'm struggling to figure out how using Crypto++.
I've looked endlessly for examples, but I can find literally zero on Google. Ohloh is less than helpful as I just get back endless pages of the cryptopp ElGamal source files, which I can't seem to be able to figure out (I'm relatively new to using Crypto++ and until about 3 days ago hadn't even heard of ElGamal).
The closest I've been able to find as an example comes from the CryptoPP package itself, which is as follows:
bool ValidateElGamal()
{
cout << "\nElGamal validation suite running...\n\n";
bool pass = true;
{
FileSource fc("TestData/elgc1024.dat", true, new HexDecoder);
ElGamalDecryptor privC(fc);
ElGamalEncryptor pubC(privC);
privC.AccessKey().Precompute();
ByteQueue queue;
privC.AccessKey().SavePrecomputation(queue);
privC.AccessKey().LoadPrecomputation(queue);
pass = CryptoSystemValidate(privC, pubC) && pass;
}
return pass;
}
However, this doesn't really seem to help me much as I'm unaware of how to plug in my already computed values. I am not sure if I'm struggling with my understanding of how Elgamal works (entirely possible) or if I'm just being an idiot when it comes to using what I've got with CryptoPP. Can anyone help point me in the right direction?
I have been given the public part of an ephemeral key pair and a second static key, as well as some data.
We can't really help you here because we know nothing about what is supposed to be done.
The ephemeral key pair is probably for simulating key exchange, and the static key is long term for signing the ephemeral exchange. Other than that, its anybody's guess as to what's going on.
Would you happen to know what the keys are? is the ephemeral key a Diffie-Hellman key and the static key an ElGamal signing key?
If my understanding is correct, this is all I need to perform the encryption, but I'm struggling to figure out how using Crypto++.
For the encryption example, I'm going to cheat a bit and use an RSA encryption example and port it to ElGamal. This is about as difficult as copy and paste because both RSA encryption and ElGamal encryption adhere to the the PK_Encryptor and PK_Decryptor interfaces. See the PK_Encryptor and PK_Decryptor classes for details. (And keep in mind, you might need an ElGamal or Nyberg-Rueppel (NR) signing example).
Crypto++ has a cryptosystem built on ElGamal. The cryptosystem will encrypt a large block of plain text under a symmetric key, and then encrypt the symmetric key under the ElGamal key. I'm not sure what standard it follows, though (likely IEEE's P1363). See SymmetricEncrypt and SymmetricDecrypt in elgamal.h.
The key size is artificially small so the program runs quickly. ElGamal is a discrete log problem, so its key size should be 2048-bits or higher in practice. 2048-bits is blessed by ECRYPT (Asia), ISO/IEC (Worldwide), NESSIE (Europe), and NIST (US).
If you need to save/persist/load the keys you generate, then see Keys and Formats on the Crypto++ wiki. The short answer is to call decryptor.Save() and decryptor.Load(); and stay away from the {BER|DER} encodings.
If you want, you can use a standard string rather than a SecByteBlock. The string will be easier if you are interested in printing stuff to the terminal via cout and friends.
Finally, there's now a page on the Crypto++ Wiki covering the topic with the source code for the program below. See Crypto++'s ElGamal Encryption.
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;
#include <cryptopp/osrng.h>
using CryptoPP::AutoSeededRandomPool;
#include <cryptopp/secblock.h>
using CryptoPP::SecByteBlock;
#include <cryptopp/elgamal.h>
using CryptoPP::ElGamal;
using CryptoPP::ElGamalKeys;
#include <cryptopp/cryptlib.h>
using CryptoPP::DecodingResult;
int main(int argc, char* argv[])
{
////////////////////////////////////////////////
// Generate keys
AutoSeededRandomPool rng;
cout << "Generating private key. This may take some time..." << endl;
ElGamal::Decryptor decryptor;
decryptor.AccessKey().GenerateRandomWithKeySize(rng, 512);
const ElGamalKeys::PrivateKey& privateKey = decryptor.AccessKey();
ElGamal::Encryptor encryptor(decryptor);
const PublicKey& publicKey = encryptor.AccessKey();
////////////////////////////////////////////////
// Secret to protect
static const int SECRET_SIZE = 16;
SecByteBlock plaintext( SECRET_SIZE );
memset( plaintext, 'A', SECRET_SIZE );
////////////////////////////////////////////////
// Encrypt
// Now that there is a concrete object, we can validate
assert( 0 != encryptor.FixedMaxPlaintextLength() );
assert( plaintext.size() <= encryptor.FixedMaxPlaintextLength() );
// Create cipher text space
size_t ecl = encryptor.CiphertextLength( plaintext.size() );
assert( 0 != ecl );
SecByteBlock ciphertext( ecl );
encryptor.Encrypt( rng, plaintext, plaintext.size(), ciphertext );
////////////////////////////////////////////////
// Decrypt
// Now that there is a concrete object, we can check sizes
assert( 0 != decryptor.FixedCiphertextLength() );
assert( ciphertext.size() <= decryptor.FixedCiphertextLength() );
// Create recovered text space
size_t dpl = decryptor.MaxPlaintextLength( ciphertext.size() );
assert( 0 != dpl );
SecByteBlock recovered( dpl );
DecodingResult result = decryptor.Decrypt( rng, ciphertext, ciphertext.size(), recovered );
// More sanity checks
assert( result.isValidCoding );
assert( result.messageLength <= decryptor.MaxPlaintextLength( ciphertext.size() ) );
// At this point, we can set the size of the recovered
// data. Until decryption occurs (successfully), we
// only know its maximum size
recovered.resize( result.messageLength );
// SecByteBlock is overloaded for proper results below
assert( plaintext == recovered );
// If the assert fires, we won't get this far.
if(plaintext == recovered)
cout << "Recovered plain text" << endl;
else
cout << "Failed to recover plain text" << endl;
return !(plaintext == recovered);
}
You can also create the Decryptor from a PrivateKey like so:
ElGamalKeys::PrivateKey k;
k.GenerateRandomWithKeySize(rng, 512);
ElGamal::Decryptor d(k);
...
And an Encryptor from a PublicKey:
ElGamalKeys::PublicKey pk;
privateKey.MakePublicKey(pk);
ElGamal::Encryptor e(pk);
You can save and load keys to and from disk as follows:
ElGamalKeys::PrivateKey privateKey1;
privateKey1.GenerateRandomWithKeySize(prng, 2048);
privateKey1.Save(FileSink("elgamal.der", true /*binary*/).Ref());
ElGamalKeys::PrivateKey privateKey2;
privateKey2.Load(FileSource("elgamal.der", true /*pump*/).Ref());
privateKey2.Validate(prng, 3);
ElGamal::Decryptor decryptor(privateKey2);
// ...
The keys are ASN.1 encoded, so you can dump them with something like Peter Gutmann's dumpasn1:
$ ./cryptopp-elgamal-keys.exe
Generating private key. This may take some time...
$ dumpasn1 elgamal.der
0 556: SEQUENCE {
4 257: INTEGER
: 00 C0 8F 5A 29 88 82 8C 88 7D 00 AE 08 F0 37 AC
: FA F3 6B FC 4D B2 EF 5D 65 92 FD 39 98 04 C7 6D
: 6D 74 F5 FA 84 8F 56 0C DD B4 96 B2 51 81 E3 A1
: 75 F6 BE 82 46 67 92 F2 B3 EC 41 00 70 5C 45 BF
: 40 A0 2C EC 15 49 AD 92 F1 3E 4D 06 E2 89 C6 5F
: 0A 5A 88 32 3D BD 66 59 12 A1 CB 15 B1 72 FE F3
: 2D 19 DD 07 DF A8 D6 4C B8 D0 AB 22 7C F2 79 4B
: 6D 23 CE 40 EC FB DF B8 68 A4 8E 52 A9 9B 22 F1
: [ Another 129 bytes skipped ]
265 1: INTEGER 3
268 257: INTEGER
: 00 BA 4D ED 20 E8 36 AC 01 F6 5C 9C DA 62 11 BB
: E9 71 D0 AB B7 E2 D3 61 37 E2 7B 5C B3 77 2C C9
: FC DE 43 70 AE AA 5A 3C 80 0A 2E B0 FA C9 18 E5
: 1C 72 86 46 96 E9 9A 44 08 FF 43 62 95 BE D7 37
: F8 99 16 59 7D FA 3A 73 DD 0D C8 CA 19 B8 6D CA
: 8D 8E 89 52 50 4E 3A 84 B3 17 BD 71 1A 1D 38 9E
: 4A C4 04 F3 A2 1A F7 1F 34 F0 5A B9 CD B4 E2 7F
: 8C 40 18 22 58 85 14 40 E0 BF 01 2D 52 B7 69 7B
: [ Another 129 bytes skipped ]
529 29: INTEGER
: 01 61 40 24 1F 48 00 4C 35 86 0B 9D 02 8C B8 90
: B1 56 CF BD A4 75 FE E2 8E 0B B3 66 08
: }
0 warnings, 0 errors.