Patrick Hansell
Patrick Hansell

Reputation: 75

Why does 65537 not base64URL encode to "AQAB" using CryptoPP?

I'm using CryptoPP to generate an RSA key pair to allow authentication for a game server. I need to base64URL encode my public exponent and modulus to include in a JWK but am having some problems. The code shows how I generate the RSA keys, extract the exponent and encode it:

typedef InvertibleRSAFunction RSAPrivateKey;
typedef RSAFunction RSAPublicKey;

RSAPrivateKey privateKey;
privateKey.Initialize( rng, 1024);

RSAPublicKey publicKey( privateKey );

const Integer& e = privateKey.GetPublicExponent();

Base64Encoder exponentSink(new StringSink(exponentString));
e.DEREncode(exponentSink);
exponentSink.MessageEnd();
base64URL(exponentString);

cout << "exponentString: " << exponentString << endl;

The base64URL function just filters the string for the =,+,\n and / characters to make it base64URL.

I know that CryptoPP uses an exponent of 17, and the code above encodes this as "AgER". I've read from numerous sources that 65537 encodes as "AQAB" and I tried this as a test by manually setting e to this. When I do this the output is "AgMBAAE", not "AQAB".

When I use an online converter such as https://www.base64encode.org/ the output is instead "NjU1Mzc".

Can someone explain where all these differences come from and what the correct encoding of 17 is? Thanks!

Upvotes: 7

Views: 4477

Answers (1)

Maarten Bodewes
Maarten Bodewes

Reputation: 94058

The output of CryptoPP seems to include the ASN.1 DER encoded representation. In hexadecimals the string AgMBAAE translates to 0203010001.

Now in ASN.1 / DER this reads as:

    02 a signed INTEGER
    03 the length of the value
010001 the value, a big endian signed integer (i.e. 65537)

The value of the base64encode.org seems to output the base 64 encoding of the ASCII string "65537" : 3635353337 in hexadecimals.


There is no single correct encoding of the value 17, it depends what you use it for.

  • As single byte value it would be EQ==
  • As ASN.1 / DER encoded integer it would be AgER
  • As string it would be MTc=

you can of course use the same strings without = padding characters as well (to comply with the base64url encoding instead of the more common base 64 encoding).

Upvotes: 6

Related Questions