Class: Browser::Crypto

Inherits:
Object show all
Includes:
NativeCachedWrapper
Defined in:
opal/browser/crypto.rb

Overview

Implements (parts of) the web crypto interface

https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API

Defined Under Namespace

Classes: Digest

Instance Method Summary collapse

Methods included from NativeCachedWrapper

#restricted?, #set_native_reference

Instance Method Details

#digest(data, algo = 'SHA-256', &block) ⇒ Object

Compute a cryptographic digest of data (a Buffer). If block is given, it will call a block, otherwise it will return a Promise that will return once a digest is computed.

Allowed values for algo: SHA-1, SHA-256 (default), SHA-368, SHA-512.

The block/promise will be given an argument of type Digest which can be used to format a digest.

Example:

Browser::Blob.new(['test']).buffer.then { |b|
  $window.crypto.digest(b)
}.then { |d|
  puts d.to_hex
}

58
59
60
61
62
63
64
65
66
67
68
# File 'opal/browser/crypto.rb', line 58

def digest data, algo = 'SHA-256', &block
  promise = nil
  unless block_given?
    promise = Promise.new
    block = proc { |i| promise.resolve(i) }
  end
  resblock = proc { |i| block.call(Digest.new(i)) }

  `#@native.subtle.digest(algo, #{Native.convert(data)}).then(#{resblock.to_n})`
  promise
end