How to use SubtleCrypto in chrome (window.crypto.subtle is undefined)

Viewed 24859

This is really embarassing

on virtually any site on the internet,

window.crypto.subtle

returns

SubtleCrypto {}
  __proto__: SubtleCrypto

in the chrome console (v61 (Official Build) (64-bit))

except for

my webpage, and blank.org

where

window.crypto.subtle

returns

undefined

according to https://developer.mozilla.org/en-US/docs/Web/API/Crypto/subtle it's a read-only property that should always return a SubtleCrypto object.

what could I have done, or what has blank.org done that it could possibly not?

ps: in firefox it seems to work as intended on both my site and blank.org

4 Answers

It would appear you have to use sites with https://...... and not vanilla http://....

From the spec - easy to miss (and linked by Zmart, above):

Access to the WebCrypto API is restricted to secure origins (which is to say https:// pages).

If you don't run your website on SSL with https the answer is: You can't use window.crypto.subtle. You have to configure SSL for your webserver. Look in MDN docs about Crypto.subtle it has a big warning on top op the page saying Secure context which means it is only available on https.

BUT there is an alternative solution if you still need a support for http only. And it does not involve using window.crypto.subtle but other open-source third party library instead. Here is how:

You can use Forge which is a crypto library that has same functionality like window.crypto.sybtle It has all crypto algorithms for your needs.

You can use forge instead of window.crypto when you run your services over http.

Be aware that APIs are very different and you need to write different code for cryptography using forge than using window.crypto. You need to read forge docs to make specific cryptography method work for your use case. You CAN NOT use same code that works in window.crypto.subtle when using forge you need to find your own way how to use forge for encryption.

For your reference to see how forge vs window.crypto.subtle codes are different read below.

Links to original window.crypto.subtle based darkwire.io code and translated darkwire.io code that is using forge instead of window.crypto.subtle:

  • original code using window.crypto.subtle: here

  • code translated to use forge, can run on http without SSL: here

I had translated darkwire.io to use forge for my own project that runs on http and needs encrypted communication method between clients.

Related