Search code examples
javascriptcryptographywebcrypto-api

Curve25519 ECDH in WebCrypto


I have read this document to generate keys pair via ECDH-CURVE25519 algorithom. But JS error(DOMException: Algorithm: Unrecognized name) is thrown when I spcified ECDH-CURVE25519 as algorithom name in window.crypto.subtle.generateKey.

    window.crypto.subtle.generateKey(
    {
        name: "ECDH-CURVE25519"
    },
    true, 
    ["deriveKey", "deriveBits"] 
)
.then(function(key){
    console.log(key);
   pk = key.publicKey;
    vk = key.privateKey;
})
.catch(function(err){
    console.error(err);
});

Solution

  • Curve25519 is not supported by WebCryptographyApi.

    Instead you can use P-256 (secp256r1), P-384(secp386r1) and P-521(secp521r1). See https://www.w3.org/TR/WebCryptoAPI/#dfn-EcKeyGenParams

    The code should be like this

    window.crypto.subtle.generateKey(
        {
            name: "ECDH",
            namedCurve: "P-256", // "P-256", "P-384", or "P-521"
        },
        true, 
        ["deriveKey", "deriveBits"] 
    )
    .then(function(key){
       console.log(key);
       pk = key.publicKey;
       vk = key.privateKey;
    })
    .catch(function(err){
        console.error(err);
    });