I've generated a public key using openssl
BIGNUM* e = BN_new();
BN_set_word(e, 17);
RSA* rsa = RSA_new();
if(!RSA_generate_key_ex(rsa, 2048, e, NULL)) {
LOG(security, debug) << "failed to generate private key";
}
And these are written to files:
FILE* pubwriter = fopen("key.pub", "wb");
int err = PEM_write_RSAPublicKey(pubwriter, key);
if(!err) {
throw new std::runtime_error("Failed to store public key");
}
FILE* privwriter = fopen("key.priv", "wb");
std::string password = "password";
err = PEM_write_RSAPrivateKey(privwriter, key, EVP_des_ede3_cbc(),
(unsigned char*)password.c_str(),
password.size(), NULL, NULL);
And they seem to be stored correctly, key.pub then contains something like
-----BEGIN RSA PUBLIC KEY-----
MIIBCAKCAQEA0rG1b0g3NIsDT8HkzgTx8BUI9LhueWbH1NuAvIh9qTF57GzEXuTu
jxBcuSzWXlR83ci4oITp7VqV6KLVoJryf8orGXBVi9A73JYOQVB6FEzARKym/g8E
fSEwSmdQ4NfiTESwOCtIextdu3x8pANSYDyyqdiWsSHy0SiZmkbvdVYomIBJZOV9
jhb3mkmD0WUYie9AXziTbli97YqDiN168kMI+7ePpbNJFSVSIUkPPocSgvgcAux/
HuDqftzBgyAF3NGb3AAra1A8T7yPOqLyYyXdIJmF+/Svk5PdMbZVE/U76cjBThch
Q9AiLo25hOjkmtuEQubCuwrUDleblr93aQIBEQ==
-----END RSA PUBLIC KEY-----
Now I want to try these to make sure I haven't got anything wrong but it wont' load:
$ openssl rsautl -encrypt -inkey key.pub -pubin -in data.txt -out enc.txt
unable to load Public Key
What am I missing?
int err = PEM_write_RSAPublicKey(pubwriter, key);
PEM_write_RSAPublicKey writes just the public key. You can make the command work using PEM_write_PUBKEY. The various *_PUBKEY routines write the SubjectPublicKeyInfo, which includes the algorithm OID and public key.
When you write the SubjectPublicKeyInfo, OpenSSL calls it "traditional" format. It will also have the header -----BEGIN PUBLIC KEY----- (and not -----BEGIN RSA PUBLIC KEY-----).
Below, I used PEM_write_PUBKEY to save the public key rsa-public.pem:
$ openssl rsautl -encrypt -inkey rsa-public.pem -pubin -in data.txt -out enc.bin
$ hexdump enc.bin
0000000 45 53 31 ad 9d 6a c4 37 1e 22 4b 83 c6 27 c8 3c
0000010 df cb 87 a4 60 d8 63 9a 83 9f ee ca e5 8f 8e dd
0000020 d4 d0 98 97 1c b3 36 55 f1 84 ea 7f fe bf 22 b6
0000030 93 20 a2 d5 b2 bd 20 cc 52 8e c7 1b 33 e6 40 40
0000040 cb 7d 6f 17 f1 eb f1 d4 9d 66 fb 67 eb 67 ba 2a
0000050 44 c2 52 15 54 8d 79 76 ad 26 61 35 27 9c bb 6c
0000060 5b 0e 79 b3 d3 27 0b a9 72 17 0d 2d 19 d7 60 19
0000070 16 46 80 4b c0 ae 75 53 9e 6f f5 24 d9 1a a3 6a
0000080 2f 38 13 f6 72 19 20 94 de 40 75 20 51 f4 08 f4
0000090 74 b8 ac 49 01 d6 f8 f4 e5 79 38 88 2d 02 b7 bd
00000a0 f7 63 c1 e1 e5 ec 39 a1 fa 7c ce 0f 83 16 70 7e
00000b0 cd 7e f5 6b 51 c2 db d7 f6 c4 46 5d e5 93 d3 3d
00000c0 ab e6 3b 1a 97 d4 c9 54 e7 aa 90 2d 0a b9 c2 4b
00000d0 3c 58 fd 26 58 5a 63 c0 8c ae b9 72 24 a1 68 5d
00000e0 83 d7 5b ae 56 2a 78 46 8c f4 21 96 bd d3 0c 93
00000f0 8e 35 61 9c b8 56 2e 3a 4e 05 d9 1e 0b 59 14 11
0000100
PEM_write_PUBKEY requires a EVP_PKEY. Just use something like:
EVP_PKEY* pkey = EVP_PKEY_new();
ASSERT(pkey != NULL);
int rc = EVP_PKEY_set1_RSA(pkey, rsa);
ASSERT(rc == 1);
...
EVP_PKEY_free(pkey);
The set1 bumps the reference count on the RSA key, so you have to free it through EVP_PKEY_free.
The difference between PEM_write_RSAPublicKey and PEM_write_PUBKEY is very obvious when you save in ASN.1/DER. But it gets lost in the PEM encoding.
Here's the non-traditional key in ASN.1/DER and dumped. Its the ASN.1 equivalent of PEM_write_RSAPublicKey. Its just {n,e}:
$ 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.
Here's the traditional public key in ASN.1/DER and dumped. Its the ASN.1 equivalent of PEM_write_PUBKEY. Its the one that writes the SubjectPublicKeyInfo, and it includes an algorithm OID and public key:
$ 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.
err = PEM_write_RSAPrivateKey(privwriter, key, EVP_des_ede3_cbc(),
(unsigned char*)password.c_str(),
password.size(), NULL, NULL);
I believe the OpenSSL folks recommend you use PEM_write_PKCS8PrivateKey. See PEM(3) and pkcs8(1).
Now I want to try these to make sure I haven't got anything wrong but it wont' load:
$ openssl rsautl -encrypt -inkey key.pub -pubin -in data.txt -out enc.txt
You can understand the behavior by looking at <openssl src>/apps/rsautl.c. Here are the relevant lines:
else if (!strcmp(*argv, "-pubin")) {
key_type = KEY_PUBKEY;
}
...
case KEY_PUBKEY:
pkey = load_pubkey(bio_err, keyfile, keyform, 0, NULL, e, "Public Key");
break;
...
Then, in apps.c:
if (format == FORMAT_ASN1) {
pkey = d2i_PUBKEY_bio(key, NULL);
}
...
else if (format == FORMAT_PEM) {
pkey = PEM_read_bio_PUBKEY(key, NULL, ...);
}
...
The observation above is the routines are using *_PUBKEY.
There's also a code path based on format == FORMAT_PEMRSA that calls PEM_read_bio_RSAPublicKey, but I don't know how to trigger it. Looking at rsautl(1), I don't think you can because there's no switch that exposes it.
If it was going to trigger, it would be based on a combination of the -keyform option combined with format == FORMAT_PEMRSA. But apps.c's str2fmt does not return a FORMAT_PEMRSA.
I think that means your only option is to use a SubjectPublicKeyInfo. And that means using PEM_write_PUBKEY (or convert the key after the fact).
Now related: OpenSSL Bug Report, Issue 3887: rsautl and intelligent retry for Public Key parse after Traditional/Subject Public Key Info parse fails.
I faced the same problem and managed to debug by following #jww answer above. In the process I discover a simple command that does not require a EVP_PKEY.
Just use PEM_write_bio_RSA_PUBKEY(BIO * bp, RSA * x) directly. Read PEM_write documentation for details.
Related
How to generate RSA public key with no any API. Just using modulus and public exponent.
In our project we are implementing RSA PKCS#8 public key by modulus and public exponent.
However we don't know meaning of ASN.1 binary of PKCS#8 public key.
For understanding PKCS#8 public key ASN.1, we did blow.
1. openssl genrsa -out hoge.key 2048
2. openssl rsa -pubout -in hoge.key
Here we get below infomation.
> -----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7z2oyePt5vNbH7Pbieiw
BOgRnCUyyUvUo6Wi+uqUWvMxrji1vH21ViTZYLjg40RrulSCGFwjzwnI4AMtEdIZ
7uOol12E3xOZYNgwTBaDNCT9p0IYYuFVGfQyxlavr7oSIaaNmlSRy+0os1xi7IiI
PCHE/7nfifDQiqGtb6b6TBOwP3QXg5IdrXiqQJAlk+8S0XPhbnwwzWOhlrR3Wftq
jylBPSGSDJQoF0fJ5h2cA2yJiGqTV37YRTThPWmQEuz8Njx4bTaEaTul5/UNhSel
s7khd/IvHV9oN6T2o4V//fAsyjRZlYKEUHldb3ML/QHxWs7+hqWSa9NCwwXZGhEl
wwIDAQAB
-----END PUBLIC KEY-----
> 0000000 30 82 01 22 30 0d 06 09 2a 86 48 86 f7 0d 01 01
0000010 01 05 00 03 82 01 0f 00 30 82 01 0a 02 82 01 01
0000020 00 ef 3d a8 c9 e3 ed e6 f3 5b 1f b3 db 89 e8 b0
0000030 04 e8 11 9c 25 32 c9 4b d4 a3 a5 a2 fa ea 94 5a
0000040 f3 31 ae 38 b5 bc 7d b5 56 24 d9 60 b8 e0 e3 44
0000050 6b ba 54 82 18 5c 23 cf 09 c8 e0 03 2d 11 d2 19
0000060 ee e3 a8 97 5d 84 df 13 99 60 d8 30 4c 16 83 34
0000070 24 fd a7 42 18 62 e1 55 19 f4 32 c6 56 af af ba
0000080 12 21 a6 8d 9a 54 91 cb ed 28 b3 5c 62 ec 88 88
0000090 3c 21 c4 ff b9 df 89 f0 d0 8a a1 ad 6f a6 fa 4c
00000a0 13 b0 3f 74 17 83 92 1d ad 78 aa 40 90 25 93 ef
00000b0 12 d1 73 e1 6e 7c 30 cd 63 a1 96 b4 77 59 fb 6a
00000c0 8f 29 41 3d 21 92 0c 94 28 17 47 c9 e6 1d 9c 03
00000d0 6c 89 88 6a 93 57 7e d8 45 34 e1 3d 69 90 12 ec
00000e0 fc 36 3c 78 6d 36 84 69 3b a5 e7 f5 0d 85 27 a5
00000f0 b3 b9 21 77 f2 2f 1d 5f 68 37 a4 f6 a3 85 7f fd
0000100 f0 2c ca 34 59 95 82 84 50 79 5d 6f 73 0b fd 01
0000110 f1 5a ce fe 86 a5 92 6b d3 42 c3 05 d9 1a 11 25
0000120 c3 02 03 01 00 01
0000126
we understand above binary as below. However we don't understand some binary.So We would like to know meaning of ASN.1 binary of PKCS#8 public key.
By the way, We have already refer below information. However this does not mention about public key.
https://datatracker.ietf.org/doc/html/rfc5208
30: SEQUEENCE
82: next 2byte is sequence length
01 22: 0x122byte
30: SEWUENCE
0d:?
06:?
09:?
2a 86.. 01 01 01: PKCS#1 rsa Encryption
05: ?
00: ?
03: ?
82: next 2byte is length of bit string
01 0f: length of bit string
00: ?
30 82....: PKCS#1 public key
Taking a huge gamble that what you're really asking is how to obtain the modulus and public exponent from a RSA public key PEM encoding, I invite you on this tryst. If your looking to build this encoding given only the modulus and public exponent, this dissection should show you how it's laid out, and this a somewhat reverse roadmap to get there. Either way, read on.
First of all: "next 2byte is length of bit string" - that's rather assumptive of you. ASN.1 is all about type-length-value (TLV for short) and does not waver from that model. The only reason the "next 2 byte is length of bit string" is because the ASN.1 said it is. (more on that later).
ASN.1 in incredibly flexible. I recently had a colleague jokingly tell me "ASN.1 is just JSON for boomers". Yeah, I took that personally. Since JSON followed ASN.1 by decades, I like to think "JSON is just ASN.1 for millennials".
Anyway, funny thing about ASN.1 (and JSON, for that matter): sometimes there are TLV encodings within TLV encodings, and that is the case here. Specifically an RSAPublicKey sequence will be encoded in an ASN.1 bit-string provided the setup is correct (i.e. the OID matches), and that seems to be the part you're struggling with: how to find it.
I'm going to leave the actual code to do this (which will be tedious, no-doubt fraught with hackery, and ultimately leave you wishing you had just used a crypto-library) as a task. That said, on to the act ripping apart your public key. First, your PEM:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7z2oyePt5vNbH7Pbieiw
BOgRnCUyyUvUo6Wi+uqUWvMxrji1vH21ViTZYLjg40RrulSCGFwjzwnI4AMtEdIZ
7uOol12E3xOZYNgwTBaDNCT9p0IYYuFVGfQyxlavr7oSIaaNmlSRy+0os1xi7IiI
PCHE/7nfifDQiqGtb6b6TBOwP3QXg5IdrXiqQJAlk+8S0XPhbnwwzWOhlrR3Wftq
jylBPSGSDJQoF0fJ5h2cA2yJiGqTV37YRTThPWmQEuz8Njx4bTaEaTul5/UNhSel
s7khd/IvHV9oN6T2o4V//fAsyjRZlYKEUHldb3ML/QHxWs7+hqWSa9NCwwXZGhEl
wwIDAQAB
-----END PUBLIC KEY-----
Decoding the base64 to DER, then displayed through xxd, it looks like this:
00000000: 30 82 01 22 30 0d 06 09 2a 86 48 86 f7 0d 01 01 0.."0...*.H.....
00000010: 01 05 00 03 82 01 0f 00 30 82 01 0a 02 82 01 01 ........0.......
00000020: 00 ef 3d a8 c9 e3 ed e6 f3 5b 1f b3 db 89 e8 b0 ..=......[......
00000030: 04 e8 11 9c 25 32 c9 4b d4 a3 a5 a2 fa ea 94 5a ....%2.K.......Z
00000040: f3 31 ae 38 b5 bc 7d b5 56 24 d9 60 b8 e0 e3 44 .1.8..}.V$.`...D
00000050: 6b ba 54 82 18 5c 23 cf 09 c8 e0 03 2d 11 d2 19 k.T..\#.....-...
00000060: ee e3 a8 97 5d 84 df 13 99 60 d8 30 4c 16 83 34 ....]....`.0L..4
00000070: 24 fd a7 42 18 62 e1 55 19 f4 32 c6 56 af af ba $..B.b.U..2.V...
00000080: 12 21 a6 8d 9a 54 91 cb ed 28 b3 5c 62 ec 88 88 .!...T...(.\b...
00000090: 3c 21 c4 ff b9 df 89 f0 d0 8a a1 ad 6f a6 fa 4c <!..........o..L
000000a0: 13 b0 3f 74 17 83 92 1d ad 78 aa 40 90 25 93 ef ..?t.....x.#.%..
000000b0: 12 d1 73 e1 6e 7c 30 cd 63 a1 96 b4 77 59 fb 6a ..s.n|0.c...wY.j
000000c0: 8f 29 41 3d 21 92 0c 94 28 17 47 c9 e6 1d 9c 03 .)A=!...(.G.....
000000d0: 6c 89 88 6a 93 57 7e d8 45 34 e1 3d 69 90 12 ec l..j.W~.E4.=i...
000000e0: fc 36 3c 78 6d 36 84 69 3b a5 e7 f5 0d 85 27 a5 .6<xm6.i;.....'.
000000f0: b3 b9 21 77 f2 2f 1d 5f 68 37 a4 f6 a3 85 7f fd ..!w./._h7......
00000100: f0 2c ca 34 59 95 82 84 50 79 5d 6f 73 0b fd 01 .,.4Y...Py]os...
00000110: f1 5a ce fe 86 a5 92 6b d3 42 c3 05 d9 1a 11 25 .Z.....k.B.....%
00000120: c3 02 03 01 00 01 ......
Regular ASN.1 encoding, as expected. For a PKCS8 encoded key, it should look like this:
PublicKeyInfo ::= SEQUENCE {
algorithm AlgorithmIdentifier,
PublicKey BIT STRING
}
Sending our base64-decoded DER data through ASN.1 decoding, we see::
openssl asn1parse -in pubkey.der -inform DER
0:d=0 hl=4 l= 290 cons: SEQUENCE
4:d=1 hl=2 l= 13 cons: SEQUENCE
6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
17:d=2 hl=2 l= 0 prim: NULL
19:d=1 hl=4 l= 271 prim: BIT STRING
That looks about right. For an RSA public key, the OID is 1.2.840.113549.1.1.1, the NULL, then what should be a RSAPublicKey as the PublicKey key data bit-string, which will look like this:
RSAPublicKey ::= SEQUENCE {
modulus INTEGER, -- n
publicExponent INTEGER -- e
}
From the aforementioned decoding, we know at offset 19 is the actual bit string, which should contain the RSAPublicKey ASN.1 structure. Great, but how? Well, the original parse has the following at offset-19 of the file:
00000010: 01 05 00 03 82 01 0f 00 30 82 01 0a 02 82 01 01 ........0.......
^^^^^^^^^^^^^^
From this we get:
The ASN.1 tag byte, 03, says its a bit-string. Good. We expected that. then...
The length is calculated. Per ASN.1 rules, if the length octet has the high bit lit, it means the remaining bits of that octet tell how many subsequent octets make up the actual length (i.e it can be a multi-byte length). 82 means two octets follow, indicating
the bit-string overall object length: 010f, e.g. 271 bytes.
Immediately following the length description will be a single octet stating the number of padding bits of the bit-string. I can honestly say in a quarter century of staring at these I have never seen this any value other than zero (00) in any RSA encoded public key, but still worth mentioning.
Thereafter is the actual RSAPublicKey ASN.1 structure itself. Past the bit-string type-length-padding description, we can parse the actual RSAPublicKey (finally!). The bit-string content after the type-length and padding bits indicator should be just that. Well, that's at offset 24 of our DER-encoding, so:
openssl asn1parse -in pubkey.der -inform DER -offset 24
0:d=0 hl=4 l= 266 cons: SEQUENCE
4:d=1 hl=4 l= 257 prim: INTEGER :EF3DA8C9E3EDE6F35B1FB3DB89E8B004E8119C2532C94BD4A3A5A2FAEA945AF331AE38B5BC7DB55624D960B8E0E3446BBA5482185C23CF09C8E0032D11D219EEE3A8975D84DF139960D8304C16833424FDA7421862E15519F432C656AFAFBA1221A68D9A5491CBED28B35C62EC88883C21C4FFB9DF89F0D08AA1AD6FA6FA4C13B03F741783921DAD78AA40902593EF12D173E16E7C30CD63A196B47759FB6A8F29413D21920C94281747C9E61D9C036C89886A93577ED84534E13D699012ECFC363C786D3684693BA5E7F50D8527A5B3B92177F22F1D5F6837A4F6A3857FFDF02CCA345995828450795D6F730BFD01F15ACEFE86A5926BD342C305D91A1125C3
265:d=1 hl=2 l= 3 prim: INTEGER :010001
Sure enough, there it is, the modulus and the exponent as expected. Extracting and decoding from there is just a matter of code, but at least now it is code based on decoding by calculation and not guessing.
Fair Warning
The only reason why this worked is because we knew the RSAPublicKey was in the bit string, and the only reason we knew that was because the OID says it was. The form stored in the bit-string is dependent on that OID, so make sure to check it first before assuming the bit-string is RSAPublicKey material.
You are asking how to generate a public key, but I don't understand why you show some binary data you are trying to decode. You can not learn how to generate a public or private key from looking at binary data which i assume is already encrypted.
Why not use a library to generate a key pair and be done with it? Trying to code something yourself, from scratch, is likely (very likely in fact) to have errors which lead to really insecure conditions.
In any event, you can download the source code to ssl libraries like openssl if you want to see what you can learn from them.
I'm trying to sign a file with my private key using the following function:
void Signer::SignFile(const std::string& file)
{
RSASS<PSSR, Whirlpool>::Signer signer(rsaPrivate);
// Encrypt and write
FileSource ss1(file.c_str(), true,
new SignerFilter(rng, signer,
new FileSink(file.c_str(), true)
, true));
}
As an outcome my target file gets overwritten with the signature. Why does that happen? Obviously I'd like to append it to the file, that's why I also added an extra "true" parameter for the "putMessage".
FileSource ss1(file.c_str(), true,
new SignerFilter(rng, signer,
new FileSink(file.c_str(), true), true));
I [personally] have never seen someone use the same file as a source and sink. Usually the file data and signature are separate like with a detached signature.
It looks like one file/two streams is implementation defined: C++ read and write to same file using different streams. I guess you should expect seemingly random results on different platforms.
As an outcome my target file gets overwritten with the signature. Why does that happen?
The FileSink opens with std::ios_base::tunc. Also see FileSink on the Crypto++ wiki.
You should probably do something like this. It saves the signature to an intermediate ByteQueue, and then writes the queue to the file once the file is closed.
#include "cryptlib.h"
#include "filters.h"
#include "osrng.h"
#include "files.h"
#include "pssr.h"
#include "rsa.h"
#include "whrlpool.h"
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char* argv[])
{
using namespace CryptoPP;
AutoSeededRandomPool prng;
std::string fname("test.bin");
///// Create test message /////
{
std::string msg("Yoda said, Do or do not. There is no try.");
std::ofstream out(fname.c_str());
out.write(msg.data(), msg.size());
}
///// Generate a key /////
RSASS<PSSR, Whirlpool>::Signer signer;
signer.AccessKey().GenerateRandomWithKeySize(prng, 2048);
///// Sign the message /////
ByteQueue queue;
{
FileSource source(fname.c_str(), true,
new SignerFilter(prng, signer,
new Redirector(queue)));
}
///// Append the signature /////
{
std::ofstream out(fname.c_str(), std::ios_base::out | std::ios_base::binary | std::ios_base::app);
queue.TransferTo(FileSink(out).Ref());
}
///// Create a verifier /////
RSASS<PSSR, Whirlpool>::Verifier verifier(signer);
///// Verify the message /////
{
FileSource source(fname.c_str(), true,
new SignatureVerificationFilter(verifier, NULLPTR,
SignatureVerificationFilter::THROW_EXCEPTION));
}
std::cout << "Verified signature on message" << std::endl;
return 0;
}
It does not crash and it appends the message as expected:
$ ./test.exe
Verified signature on message
$ hexdump -C test.bin
00000000 59 6f 64 61 20 73 61 69 64 2c 20 44 6f 20 6f 72 |Yoda said, Do or|
00000010 20 64 6f 20 6e 6f 74 2e 20 54 68 65 72 65 20 69 | do not. There i|
00000020 73 20 6e 6f 20 74 72 79 2e 19 f2 1c 8f f9 cb 2f |s no try......./|
00000030 f2 38 9f a8 3b a9 0b 8b 62 25 56 a8 ea 81 7e 60 |.8..;...b%V...~`|
00000040 22 55 38 ce 79 7f 32 95 a5 1a 75 c1 80 ad b2 c2 |"U8.y.2...u.....|
00000050 6f ce a5 f7 bd 4b d3 3f e4 b3 69 00 21 60 d7 09 |o....K.?..i.!`..|
00000060 a8 71 9b 5f 41 d6 66 b1 80 f1 de 00 26 19 34 01 |.q._A.f.....&.4.|
00000070 b3 65 1b 78 e2 32 71 be bc 07 25 78 36 6b 56 4e |.e.x.2q...%x6kVN|
00000080 26 4e 12 9e a8 bb 72 86 ee 0d 70 b2 f1 bd a3 2c |&N....r...p....,|
00000090 14 fd 12 61 35 98 4a 80 9f ee 3c 31 d3 70 26 0f |...a5.J...<1.p&.|
000000a0 73 a0 5d 36 ef 96 56 65 f8 ac 3a fb 44 c3 04 76 |s.]6..Ve..:.D..v|
000000b0 e5 2f ae 92 84 be 40 34 f6 4b b8 84 aa bd 67 74 |./....#4.K....gt|
000000c0 05 43 91 d2 e6 b1 50 dd 6d 64 47 cc 3e 3c 3a 9d |.C....P.mdG.><:.|
000000d0 67 ff 4f 38 c1 a5 a6 d5 92 45 bc 2d ff 96 30 3a |g.O8.....E.-..0:|
000000e0 1d 3a 42 4f 8c 13 2d 4c 3f e9 ad 08 a6 b3 5e fa |.:BO..-L?.....^.|
000000f0 46 08 24 17 43 ce ed ec f7 1a 38 62 e7 bf 42 93 |F.$.C.....8b..B.|
00000100 84 44 b6 05 22 9e e3 bd 80 a6 08 b0 34 d0 a4 89 |.D..".......4...|
00000110 78 48 20 7f 7b 33 1c 51 9d 48 b5 b7 f7 de 2f dd |xH .{3.Q.H..../.|
00000120 d7 74 7b af 04 cd 92 fc 1c |.t{......|
I was not able to get this to work. I'm pretty sure it is a dead end.
std::fstream inout(fname.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::binary | std::ios_base::app);
FileSource fs(inout, true,
new SignerFilter(prng, signer,
new FileSink(inout), true));
Obviously I'd like to append it to the file, that's why ...
Also, because you are using PSSR, you don't need the original message. PSSR is "probabilistic signature scheme with recovery". The message is include in the signature with a mask function.
You would need the original message with a SSA scheme. SSA is "signature scheme with appendix". In a SSA scheme you need to provide both the original message and the signature.
(From the comments) Here is an example that uses a Signature Scheme with Appendix (SSA). It also uses std::iftream and std::ofstream directly so FileSource and FileSink work as you expect. std::ofstream includes std::ios_base::app so the signature is appended.
#include "cryptlib.h"
#include "filters.h"
#include "osrng.h"
#include "files.h"
#include "oaep.h"
#include "rsa.h"
#include "sha.h"
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char* argv[])
{
using namespace CryptoPP;
AutoSeededRandomPool prng;
std::string fname("test.bin");
///// Create test message /////
{
std::string msg("Yoda said, Do or do not. There is no try.");
std::ofstream out(fname.c_str());
out.write(msg.data(), msg.size());
}
///// Generate a key /////
RSASS<PKCS1v15, SHA256>::Signer signer;
signer.AccessKey().GenerateRandomWithKeySize(prng, 2048);
{
///// Create fstreams for input and output /////
std::ifstream fin(fname.c_str(), std::ios_base::in | std::ios_base::binary);
std::ofstream fout(fname.c_str(), std::ios_base::out | std::ios_base::binary | std::ios_base::app);
///// Sign the message /////
FileSource source(fin, true,
new SignerFilter(prng, signer,
new FileSink(fout)));
}
///// Create a verifier /////
RSASS<PKCS1v15, SHA256>::Verifier verifier(signer);
///// Verify the message /////
{
FileSource source(fname.c_str(), true,
new SignatureVerificationFilter(verifier, NULLPTR,
SignatureVerificationFilter::THROW_EXCEPTION));
}
std::cout << "Verified signature on message" << std::endl;
return 0;
}
And then:
$ ./test.exe
Verified signature on message
$ hexdump -C test.bin
00000000 59 6f 64 61 20 73 61 69 64 2c 20 44 6f 20 6f 72 |Yoda said, Do or|
00000010 20 64 6f 20 6e 6f 74 2e 20 54 68 65 72 65 20 69 | do not. There i|
00000020 73 20 6e 6f 20 74 72 79 2e c7 b3 6f 84 1d fd bf |s no try...o....|
00000030 c7 c8 38 7c 89 b1 f3 42 ee 5e f8 10 de a8 01 7f |..8|...B.^......|
00000040 7f a5 24 3d 27 7e 55 16 bc 80 8b 21 21 75 3d ed |..$='~U....!!u=.|
00000050 41 05 84 b1 3d bf d3 ae 3a 2f a8 81 7a e7 e4 ae |A...=...:/..z...|
00000060 50 d7 9b 25 04 17 a6 a3 1d 12 e2 8e cd 7a 02 42 |P..%.........z.B|
00000070 91 c0 d7 fc 43 09 94 a2 66 d9 67 95 55 5e dc 8c |....C...f.g.U^..|
00000080 eb bc 20 af e8 5c d4 63 05 d4 2c 48 57 6d f1 fe |.. ..\.c..,HWm..|
00000090 26 16 80 c3 41 11 58 8e 8d b0 cb 48 95 b9 ed 94 |&...A.X....H....|
000000a0 84 cc 86 0f a4 7e a3 6a ff 0d 0d 24 17 82 13 94 |.....~.j...$....|
000000b0 54 cb 8a ca 04 1e 65 18 c3 ab a2 3f 4d 44 de 42 |T.....e....?MD.B|
000000c0 32 07 29 e4 95 83 cc ff 39 85 08 bf d5 61 46 db |2.).....9....aF.|
000000d0 e0 96 d6 69 25 b9 ce 1e 3e bc 63 81 e5 16 bd 12 |...i%...>.c.....|
000000e0 a0 78 02 19 60 96 80 36 7d a5 79 be 0f 45 54 f4 |.x..`..6}.y..ET.|
000000f0 92 af f0 d8 74 65 7d 45 98 c7 bb 7f 6e 9b e3 cd |....te}E....n...|
00000100 c0 60 91 0f 78 aa 7c 77 a7 f5 4e 7d 6e ed e1 4c |.`..x.|w..N}n..L|
00000110 8e 5e 96 ac cd 30 16 e0 2d be 9e 2d 68 d4 25 46 |.^...0..-..-h.%F|
00000120 86 77 87 be 68 ef 06 26 55 |.w..h..&U|
I have a 1024-bit RSA public key :
FF A4 32 23 FF A2 0D 53 26 36 70 1B 74 DA 9D A7
73 45 A8 38 26 94 1E C8 A1 81 53 F4 DD 37 FF B2
7F B0 DB 31 D6 74 DD 1C 43 F1 C9 93 F5 68 D0 87
CB C6 B5 A6 2D F5 46 80 C9 1A D4 0A 84 18 07 7E
7A F1 05 EC 95 9A C2 0A 3E 4A 1E 8B CC 4E 3F 1C
99 E7 76 25 AE 6E A5 26 99 EA 44 AA 2C 23 DA DA
3B C1 2D E2 A3 D2 6D 51 5C AD 29 1A 72 3B D0 C7
A9 F2 FC 92 0E F8 F3 67 BD 92 DB FC 53 CE 55 B5
How can I get the public exponent and modulus to encrypt my message from it?
I am looking for an example of LUC algorithm, but I can't find anything. I know that it is in Crypto++, but I don't know C++ too well to use it.
I look for an example of algorithm of LUC...
It kind of depends on what you want to do. You might want to browse luc.h to see some of the things Crypto++ offers for LUC. There's a LUCES, a LUCSS and a LUC_IES. The *ES is encryption scheme, the *SS is a signature scheme, and the *IES is an integrated encryption scheme (which includes a key agreement algorithm and mask function).
Generally speaking, LUC is a public key encryption system. Using it is like using any other public key encryption system offered by Crypto++. That's because all the public key encryption systems inherit from the same classes (more correctly, base interfaces). You can see the design in the comments for file pubkey.h.
$ grep -R LUCES *
...
typedef LUCES<OAEP<SHA> >::Decryptor LUCES_OAEP_SHA_Decryptor;
typedef LUCES<OAEP<SHA> >::Encryptor LUCES_OAEP_SHA_Encryptor;
And that's pretty much all you need, though you may not know it.
Here's the easier problem to solve. How do you perform RSA encryption in Crypto++?
$ grep -R RSAES *
...
typedef RSAES<PKCS1v15>::Decryptor RSAES_PKCS1v15_Decryptor;
typedef RSAES<PKCS1v15>::Encryptor RSAES_PKCS1v15_Encryptor;
typedef RSAES<OAEP<SHA> >::Decryptor RSAES_OAEP_SHA_Decryptor;
typedef RSAES<OAEP<SHA> >::Encryptor RSAES_OAEP_SHA_Encryptor;
If you find an RSAES_PKCS1v15_Decryptor or RSAES_OAEP_SHA_Decryptor example, you just copy/replace with LUCES_OAEP_SHA_Decryptor and it will work just fine. And if you find an RSAES_PKCS1v15_Encryptor or RSAES_OAEP_SHA_Encryptor example, you just copy/replace with LUCES_OAEP_SHA_Encryptor and it will work just fine.
You can find the examples of using RSAES_OAEP_SHA_Encryptor and RSAES_OAEP_SHA_Decryptor on the Crypto++ wiki page for RSA Encryption Schemes. Or you can use the ECIES examples at Elliptic Curve Integrated Encryption Scheme (remember, all the public key systems inherit from the same base interfaces, so they all have the same methods and you use them the same way).
This should get you started. It creates a private key, saves it, then creates a public key, and saves it.
try
{
AutoSeededRandomPool prng;
FileSink fs1("lucs-private.der", true);
FileSink fs2("lucs-public.der", true);
InvertibleLUCFunction params;
params.GenerateRandomWithKeySize(prng, 2048);
LUC::PrivateKey privateKey(params);
privateKey.DEREncode(fs1);
LUCES_OAEP_SHA_Decryptor decryptor(privateKey);
// ...
LUC::PublicKey publicKey(params);
publicKey.DEREncode(fs2);
LUCES_OAEP_SHA_Encryptor encryptor(publicKey);
// ...
}
catch(CryptoPP::Exception& ex)
{
cerr << ex.what() << endl;
}
If you don't want to use InvertibleLUCFunction, the do something like this to generate the key. Note: RSA has an InvertibleRSAFunction.
LUC::PrivateKey privateKey;
privateKey.Initialize(prng, 2048);
...
LUC::PublicKey publicKey(privateKey);
...
An here's yet another way to do it:
FileSink fs1("lucs-private.der", true);
FileSink fs2("lucs-public.der", true);
LUCES_OAEP_SHA_Decryptor decryptor;
decryptor.AccessKey().Initialize(prng, 2048);
decryptor.AccessKey().DEREncode(fs1);
...
LUCES_OAEP_SHA_Encryptor encryptor(decryptor);
encryptor.AccessKey().DEREncode(fs2);
...
And here's a dump of the private key created by the test program:
$ dumpasn1 lucs-private.der
0 662: SEQUENCE {
4 1: INTEGER 0
7 257: INTEGER
: 00 B8 7A CA 6A 61 D9 CF 2F D8 89 5C A4 7D 74 7B
: AC F5 10 4C 3D 95 BF DD 2E F5 4E E5 F4 20 CF CD
: 44 7F C7 27 41 48 6B 83 E0 7C D9 66 16 8D 54 36
: 97 B9 CE 2D 80 A6 F6 E5 25 87 83 6E B9 41 45 DC
: 2A EB EC 4E EC D9 C0 17 B4 E0 04 F0 58 61 60 F8
: 87 18 27 16 58 BA 56 4E DD 9B C8 CD 18 46 28 38
: A2 6A A6 14 36 D0 A6 FF 9C B8 A8 B5 0F 3A 11 B5
: 00 08 44 B3 31 58 AF 01 F8 57 17 E8 FC 68 B2 5F
: [ Another 129 bytes skipped ]
268 1: INTEGER 17
271 129: INTEGER
: 00 C8 DF 47 D0 B2 6F C2 1A E4 B7 E8 3D 12 BB FF
: 04 F7 34 40 A0 0E ED DC F7 24 7B D9 46 EE 10 C4
: D5 E2 9C 93 05 CF 13 53 40 F4 50 EC 1F 6D D7 33
: FF FF 46 42 88 8D FC F4 EE 7F 0C 8B 71 71 51 D2
: 3C 32 E3 9A 11 B7 D8 CF EA 10 B2 07 49 3F 93 CD
: A0 3F 71 A9 23 27 35 1F 6A C9 1D FE CE 24 75 33
: 8F 53 71 B9 0B DE BC 05 93 98 A3 EA 94 8E 04 B1
: 29 A1 4F 4C 82 34 7A 08 3A 0E 07 98 8B 00 30 D7
: 5B
403 129: INTEGER
: 00 EB 1B D0 EF 5C 0F FC FC B7 56 A7 70 8C AA B7
: A6 90 C8 1F AA AD A0 0B 66 E5 33 75 F2 BE 68 35
: 29 2E 57 AC E0 E0 C8 04 A7 C4 13 1D 10 30 8B 50
: 20 17 0C 83 A7 14 4A 7D 25 31 77 50 66 08 36 13
: BE 9D C0 4E F4 44 74 7A BB D2 92 D0 F7 AE 7C EB
: 8E 84 5C 27 61 2C C9 7A D1 D0 C5 A0 13 98 96 E3
: 76 CD B0 E7 E8 7E 4E 0A 2D 00 86 07 57 DB 8A 51
: 1E 59 76 EA 88 44 4D DA F3 D6 AB 75 CB A6 45 F3
: F3
535 128: INTEGER
: 2E 6A AA BA B4 E8 DD 11 2D 31 A4 D5 F7 08 AB E3
: 1A 9A 15 58 AE C8 59 BE C4 75 85 90 6D 5D A4 18
: 39 27 8F FF 1C 9A FD 0F 0C 29 05 98 9C 16 FE 84
: A4 5C 85 15 F7 98 E6 D5 5B 23 CA 2F A2 27 8A 00
: 6E B1 BB 02 6E 93 53 85 30 30 61 F5 1C 49 5D 19
: EF DF CD 6F 11 7C 6D DC AE F6 A2 06 53 BB 7E 03
: C3 E5 4E E9 59 E0 D8 5F C3 28 0E E0 17 5C 63 6E
: 8E A6 18 FC AD A5 9B 08 D1 8B 7B 28 9D E2 CF E2
: }
0 warnings, 0 errors.
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.