Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ECC Public key's Bignum to JWK X, Y Coordinates

I have created public and private keys in OpenSSL using EC_Key and have x, y and d components in BigNum format.

Now I want to convert these Bignum values to Base64URLEncoded values as per JWK standards.

e.g.

{
 "kty":"EC",
 "crv":"P-256",
 "x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
 "y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",
 "use":"enc",
 "kid":"1"
}

Currently x coordinate is 76638B4D8040018F834AE6D6540B20E1CA95F6A8C61BE6118062918904B5C5A7

While using OpenSSL and JSONKit in ObjC as

if (!bigNum) return nil;

/* converting from BIGNUM to binary */
int len = BN_num_bytes(bigNum);
unsigned char *buf = NULL;
buf = (unsigned char *) OPENSSL_malloc (len);
len = BN_bn2bin(bigNum, buf);
NSData *pubData =  [NSData dataWithBytesNoCopy:buf length:len freeWhenDone:YES];


NSString *base64EncodedString = [pubData base64EncodedString];
return [base64EncodedString stringWithBase64URLEncoding];

On converting it, it is giving Base64URL encoded string as

x:dmOLTYBAAY-DSubWVAsg4cqV9qjGG-YRgGKRiQS1xac

But while decoding the same x coordinate on server using Jose4J is returning it as:

53548795424402895049922051400723229099982122334687022963594437126482323424679

which is similar to available on website: http://www.mobilefish.com/services/big_number/big_number.php

From this is is indicated that it is decimal representation of BigInt

i.e.

  1. Convert BigInt to Decimal

  2. Decimal to ASCII String

  3. and then to Base64 url encoding.

But while applying this process, server is not accepting the JWK param in JOSE4J library.

like image 785
Ankit Thakur Avatar asked Jan 21 '26 12:01

Ankit Thakur


1 Answers

I haven't done this myself, but I think it would just be BN_bn2bin() for the x and y values, then convert the resulting data into base64url. RFC 7517 Appendix A says that JWKs need the big-endian values for x and y (and d if a private key), which is what BN_bn2bin is documented to give you.

Note that base64url is slightly different than regular base64; look at RFC 7515 Appendix C for note on how to use regular base64 routines then convert the result to base64URL.

like image 142
Carl Lindberg Avatar answered Jan 23 '26 08:01

Carl Lindberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!