I’m generating the Public and Private key by using the Native Browser crypto API as below:
export const generateKeyPair = async (): Promise<CryptoKeyPair> => { return await window.crypto.subtle.generateKey( { name: "ECDH", namedCurve: "P-384", }, true, ["deriveKey", "deriveBits"], ); };
Then I’ll export the publicKey
by using the exportKey
function under the window.crypto.subtle
as below:
const keyPair: CryptoKeyPair = yield generateKeyPair(); const publicKeyArrayBuffer: ArrayBuffer = yield window.crypto.subtle.exportKey("raw", keyPair.publicKey); const publicKeyAsBase64 = arrayBufferToBase64(publicKeyArrayBuffer);
If you have any suggestions, please let me know and help me to fix this issue.
Advertisement
Answer
Both codes use different curves, the Java code secp256r1 (aka P-256), the JavaScript code P-384. To make both codes compatible, the JavaScript code must apply the same curve as the Java code, i.e. P-256 (s. also here).
The Java code exports a public EC key in X.509/SPKI format, which is Base64 encoded. The JavaScript code exports the public key in uncompressed format 0x04|<x>|<y>
. The export in X.509/SPKI format is possible with spki
as 1st parameter, s. here and here.