0

I need to convert raw EC key to pkcs8 and vice versa. I am using react-native-quick-crypto as a replacement for node:crypto. sadly, it does not include node's crypto.createPrivateKey(...).export(...) function so I am unable to use it co convert my keys properly.

This is how am I generating the key:

const ecdh = crypto.createECDH(CURVE)
ecdh.generateKeys()

const privateKey = ecdh.getPrivateKey().toString('base64')
const publicKey = ecdh.getPublicKey().toString('base64')

console.log(privateKey, publicKey)

Running following code gives me a key pair. Private key: xLIGpg9Tb5QN/8nP6AuzMoOlEqL7big8Ikiv and public key: BK432IBI+ZQrEUaL2AMI0I7qt5FmOvj6g7Taech4u0C4FHNyuVfx/gG1U1ORSw+B80zHUcFMsTF4.

Now, I am unable to convert them into pkcs8.

I see, that I can use ec-key library to do that, sadly, it does not accept raw key. But it accepts key in JWK format. So I was thinking I can derive coordinates X, Y, and D (for private key) from generated keys and use the library to transform them (and do the opposite when need to convert them back).

But I am unable to find a way, how can I derive coordinates from raw keys.

Also, if there is an easier way how to do that, I will gladly do it.

David Novák
  • 1,455
  • 2
  • 18
  • 30
  • *...how can I derive coordinates from raw keys...* `privateKey` is the Base64 encoding of D, `publicKey` is the Base64 encoding of the concatenation 0x04|X|Y. Note that JWKs apply Base64**url**. – Topaco Feb 04 '23 at 16:30
  • What does 0x04|X|Y mean? 4 bites and then half of remaining bites X and the other half Y? – David Novák Feb 04 '23 at 19:11
  • If you do not Base64 encode the public key, but hex encode, then it is: 04ae37d88048f9942b11468bd80308d08eeab791663af8fa83b4da79c878bb40b8147372b957f1fe01b55353914b0f81f34cc751c14cb13178. The first byte has the value 0x04 and marks an uncompressed key, then follows the X coordinate (28 bytes) and finally the Y coordinate (28 bytes). So you can derive X and Y coordinate. – Topaco Feb 04 '23 at 19:17

0 Answers0