mikemaccana
mikemaccana

Reputation: 123610

WebCrypto: Safari cannot exportKey() and promise seems to never resolve/fail

I am creating a keyPair, then exporting a key from the keyPair, using the Web Crypto API:

var log = console.log.bind(console);

var subtleCrypto = null;
if ( window.crypto ) {
    subtleCrypto = window.crypto.subtle || window.crypto.webkitSubtle;
}
if ( window.msCrypto ) {
    subtleCrypto = window.msCrypto.subtle
}

subtleCrypto.generateKey(
    {
        name: "RSASSA-PKCS1-v1_5",
        modulusLength: 2048,
        publicExponent: new Uint8Array([1, 0, 1]),  // 24 bit representation of 65537
        hash: {name: "SHA-256"}
    },
    true, // can extract it later if we want
    ["sign", "verify"]
).then(function(keyPair){
    log('Exporting from keyPair', keyPair)
    subtleCrypto.exportKey('pkcs8', keyPair.privateKey).then(function(pkcs8) {
        log('Exported keypair!', pkcs8)
    }, function(reason) {
        log('Couldnt export keypair', reason)
    })
}, function(reason){
    log('could not generate key', reason)
})

On Chrome and Firefox, the code works fine, printing:

 "Exporting from keyPair" Object { privateKey: CryptoKey, publicKey: CryptoKey }
 "Exported keypair!" ArrayBuffer { byteLength: 1218 }

However on Safari it fails, printing only:

 Exporting from keyPair KeyPair 

And then not doing anything. How can I export the key on Safari?

Upvotes: 1

Views: 1765

Answers (2)

rmhrisk
rmhrisk

Reputation: 1856

There are currently a number of problems with the Safari implementation of WebCrypto as well as the Edge implementation.

For this reason we implemented this library that masks those differences, you you can find it here : https://github.com/PeculiarVentures/webcrypto-liner/blob/master/BrowserSupport.md

In this particular case as the earlier response said Safari does not implement PKCS8 formating.

If you need the PKCS8 format take a look at this function : https://github.com/PeculiarVentures/pkijs-es6/blob/62bbedea4cd3b60debbdc309bc48b5c188f4504e/src/CryptoEngine.js#L438-L532

Upvotes: 0

felix
felix

Reputation: 81

Webkit is currently not able to export keys as either 'pkcs8' or 'spki' (as found personally and confirmed by https://bugs.webkit.org/show_bug.cgi?id=129978).

The way to get around this is to export it as 'jwk' and then convert the resulting key by extracting the various parts and encoding them in ASN.1. An example of how this can be done can be found in the webcrypto-shim project, which you could just use and not have to do it yourself, though it will not work for RSA-OAEP + SHA-256 or AES-GCM on Webkit.

Upvotes: 3

Related Questions