@substrate-system/keys
    Preparing search index...

    @substrate-system/keys

    keys

    tests types module semantic versioning Common Changelog install size license

    Create and store keypairs in the browser with the web crypto API.

    Use indexedDB to store non-extractable keypairs in the browser. "Non-extractable" means that the browser prevents you from ever reading the private key, but the keys can still be persisted and re-used indefinitely.

    Tip

    Use the persist method to request that the browser not delete from indexedDB.

    Each instance of Keys has two keypairs — one for signing, and another for encrypting.

    See also, the API docs generated from typescript.

    Contents

    npm i -S @substrate-system/keys
    

    This exposes ESM and common JS via package.json exports field.

    import { EccKeys, verify } from '@substrate-system/keys/ecc'
    import { RsaKeys, verify } from '@substrate-system/keys/rsa'
    import { AES } from '@substrate-system/keys/aes'
    const { EccKeys, verify } = require('@substrate-system/keys/ecc')
    const { RsaKeys, verify } = require('@substrate-system/keys/rsa')
    const { AES } = require('@substrate-system/keys/aes')

    This package exposes minified JS files too. Copy them to a location that is accessible to your web server, then link to them in HTML.

    cp ./node_modules/@substrate-system/keys/dist/index.min.js ./public/keys.min.js
    
    <script type="module" src="./keys.min.js"></script>
    

    Import everything.

    import * as keys from '@substrate-system/keys'
    

    Import functions for Ed25519 signatures and X25519 encryption.

    import {
    EccKeys,
    exportPublicKey,
    importPublicKey,
    verify
    } from '@substrate-system/keys/ecc'

    Import RSA functions.

    import {
    RsaKeys,
    encryptKeyTo,
    encryptTo,
    verify,
    publicKeyToDid,
    getPublicKeyAsUint8Array
    } from '@substrate-system/keys/rsa'

    Import AES (symmetric) encryption only.

    import {
    AES,
    importAesKey
    } from '@substrate-system/keys/aes'

    Some miscellaneous functions.

    import {
    verify,
    keyTypeFromDid,
    publicKeyToDid
    } from '@substrate-system/keys/crypto'

    The verify function exposed here will work with either RSA or Ed25519 signatures.

    const eccOk = await verify({ message, did: ecc.DID, signature: eccSig })
    const rsaOk = await verify({ message, did: rsa.DID, signature: rsaSig })

    Return a string either 'rsa' or 'ed25519' given a DID.

    const type = keyTypeFromDid(eccKeys.DID)
    // 'ed25519'

    const rsaType = keyTypeFromDid(rsaKeys.DID)
    // 'rsa'

    Can use dbKey in .create or .load to add a prefix to both stored key names:

    const keys = await EccKeys.create(false, false, { dbKey: 'alice' })
    await keys.persist()

    For .create, pass dbKey in the third argument to prefix both IndexedDB key names. For example, dbKey: 'alice' stores ECC keypairs as alice.ecc-exchange and alice.ecc-write, or RSA keypairs as alice.rsa-exchange-key and alice.rsa-write-key.

    const rsaKeys = await RsaKeys.create(false, false, { dbKey: 'alice' })
    await rsaKeys.persist()

    For .load, pass dbKey in the options.

    const keys = await EccKeys.load({ dbKey: 'alice' })
    

    Create a new keypair, then save it in indexedDB.

    ECC is now supported in all major browsers.

    import { EccKeys, verify } from '@substrate-system/keys/ecc'

    // create a keypair, and save it to indexedDB
    const keys = await EccKeys.load()

    // ... sometime in the future ...
    // get the same keys back from indexedDB
    const keysAgain = await EccKeys.load()

    console.assert(keys.DID === keysAgain.DID) // true

    ECC encryption uses the ECIES (Elliptic Curve Integrated Encryption Scheme) pattern. For each encrypted message:

    1. A new ephemeral X25519 keypair is generated
    2. A new AES key is generated with the ephemeral private key and recipient's public key.
    3. The message is encrypted with the AES key.
    4. The ephemeral public key is prepended to the ciphertext

    To decrypt:

    1. The recipient extracts the ephemeral public key, salt, and IV from the ciphertext
    2. The recipient's private key is combined with the ephemeral public key via ECDH to get a shared secret
    3. Recipient uses HKDF with the shared secret and salt to derive the same AES key
    4. Use the AES key and IV to decrypt the message

    Note that this does not provide forward secrecy — if the recipient's long-term private key is compromised, an attacker can decrypt past messages by extracting the ephemeral public key from the ciphertext and deriving the shared secret for each message.

    The good news is that this would provide forward secrecy for the sender's keys. If the sender's long-term private key is compormised, then past messages remain illegible because they were each created with a new keypair, the secret side of which has been discarded.

    For true forward secrecy, you would want both parties to use ephemeral keys, like with Signal's double ratchet protocol.

    Ciphertext format:

    [32-byte ephemeral public key][16-byte salt][12-byte IV][ciphertext]
    
    import { EccKeys } from '@substrate-system/keys/ecc'

    const alice = await EccKeys.create()
    const bob = await EccKeys.create()

    // Alice encrypts a message to Bob's public key
    const message = 'Hello Bob!'
    const encrypted = await alice.encrypt(message, bob.publicExchangeKey)

    // Bob decrypts using his private key + the ephemeral public key from the ciphertext
    const decrypted = await bob.decryptAsString(encrypted)
    console.log(decrypted) // 'Hello Bob!'

    // Encrypt to self (note to self)
    const selfEncrypted = await alice.encrypt('Secret note')
    const selfDecrypted = await alice.decryptAsString(selfEncrypted)

    Multiple devices need to read the same data. Generate a random AES key for the data encryption, then encrypt that AES key to each device's public key with wrap and unwrap methods.

    See asymmetric docs for more about how this works.

    • Use wrap() to encrypt an AES key for a new device's public key
    • Use unwrap() on the new device to recover the AES key
    • Add devices without re-encrypting the entire dataset

    wrap signs its output with the sender's write key, and unwrap always checks that signature against the DID you pass in. Get the sender's DID over a channel an attacker can't tamper with, such as scanning a QR code or comparing it on both screens. A DID that arrives together with the wrapped key proves nothing, because whoever can swap the wrapped key can swap the DID too.

    import { EccKeys } from '@substrate-system/keys/ecc'
    import { AES } from '@substrate-system/keys/aes'

    // Device 1 has a symmetric key for encrypting data
    const device1 = await EccKeys.create()
    const contentKey = await AES.create({ length: 256 })

    // Encrypt some data.
    // (AES.encrypt automatically prepends iv to ciphertext).
    const message = 'secret data for all devices'
    const encrypted = await AES.encrypt(
    new TextEncoder().encode(message),
    contentKey
    )

    // ... device 1 needs to obtain device 2's public exchange key ...

    // wrap the content key for device 2
    const wrapped = await device1.wrap(contentKey, device2.publicExchangeKey)

    console.log(wrapped)
    // {
    // enc: 'base64-encoded-ephemeral-public-key...',
    // wrappedKey: 'base64-encoded-wrapped-content-key...',
    // signature: 'base64-encoded-signature...'
    // }

    // Store encrypted data + wrapped key entries for each device


    // -----------------------------------------
    // device 2
    // -----------------------------------------

    // ... device 2 needs to obtain the wrapped key ...

    const device2 = await EccKeys.create()

    // ... device 2 needs device 1's DID, from a channel it trusts ...

    // Device 2 checks device 1's signature, then unwraps the content key.
    // This throws if the signature is missing, or not from device 1.
    const device2ContentKey = await device2.unwrap(wrapped, device1.DID)

    // Options: `info` must match what was passed to `wrap`, and
    // `extractable` defaults to `true`.
    // await device2.unwrap(wrapped, device1.DID, {
    // info: 'my-app',
    // extractable: false
    // })

    // Device 2 decrypts the data with the unwrapped key
    // (AES.decrypt automatically extracts iv from the encrypted data)
    const decrypted = await AES.decrypt(encrypted, device2ContentKey)


    console.log(new TextDecoder().decode(decrypted))
    // => 'secret data for all devices'

    encrypt/decrypt and wrap/unwrap all do X25519 ECDH key agreement. A maliciously-crafted public key (a "low-order" or "small-subgroup" point) can force the ECDH shared secret to a known, low-entropy value -- an all-zero output is the classic case. This library does not check for that itself; it relies on the platform's WebCrypto implementation rejecting an invalid/all-zero X25519 shared secret, per RFC 7748 and the WebCrypto spec. That's a guarantee provided by the runtime (browsers, Node.js, Deno) -- not something this library implements or verifies on its own.

    'did:key:z13V3Sog2YaUKhdGCmgx9UZuW...'
    

    This is the DID string for the signing key for this instance. The DID looks like this:

    did:key:zStERvoWtx7FQS432smzbGENZHjsN55X8pUZ3np8DXGhZFf3TCorijCPeJoLytwb
    
    did:key:z13V3Sog2YaUKhdGCmgx9UZuW1o1ShFJYc6DvGYe7NTt689NoL2HdpC46K4PjfsUVAopaqmnySjJV8T6K9dMB2FUXhqfKYLUz9o9fA7xkgiNr25sUQq4vJPuPfP1kbSqtYXe5V2CZTUMucF2jfNMrWjHHRUZpEzPwGeZd5prsu9pxnVhPKnVxxKTJAVqQCp3CDRASeYKQmqVRmyPSrdQaYz4AoQxaBd52mNC7dEC4xXKbVw45dhQc52j5chR8YKCeaNANWh8DEZ7U8Dtb89PL5qP8817oxswQhz4e97p8EGtJDVrGbCXN4EucnpYaacRane4YPcmevs1pMYV8iqzJd8UZLWtDcUBNrCkeVTdnzXnM4Rq9sWiFwF3nYk6fxqfUZDfYyfPtxacSoGaSjo38ye
    

    Return a 32 character, DNS friendly hash of the signing public key.

    const name = await keys.getDeviceName()

    // a promise is exposed as property `deviceName`
    const name = await keys.deviceName

    A flag indicating whether these keys are saved in indexedDB. It is true after .persist, and after any .load that did not opt out with { persist: false }.

    A flag indicating whether .delete has been called. A destroyed keypair is terminal -- the key material is gone, and any use of it throws a KeysDeletedError.

    The public encryption CryptoKey. For ECC keys, this is the X25519 exchange key. For RSA keys, this is the RSA encryption key.

    Get the public encryption key as a base64 string. For other formats, see below.

    {
    async publicExchangeKeyAsString (format?:SupportedEncodings):Promise<string>
    }

    The public signing CryptoKey. This is the Ed25519 or RSA signing key.

    Get the public signing key as a string.

    {
    async publicWriteKeyAsString (format?:SupportedEncodings):Promise<string>
    }

    Delete the keypair. This deletes the keys from indexedDB, drops the in-memory key material, and clears the instance cache, so load will not hand these keys out again.

    await keys.delete()
    

    delete is terminal. Afterwards the instance is destroyed, and using it throws a KeysDeletedError. That includes persist, so the common "make sure my keys are saved" guard cannot write a deleted keypair back into indexedDB.

    await keys.delete()

    keys.destroyed // => true

    // all of these throw
    keys.publicExchangeKey
    await keys.sign('hello')
    await keys.encrypt('hello')
    if (!keys.hasPersisted) await keys.persist()

    The names deleted are the ones the instance was loaded with, so keys loaded under custom names delete the custom entries.

    const keys = await EccKeys.load({
    encryptionKeyName: 'my-exchange-key',
    writeKeyName: 'my-write-key'
    })

    // deletes 'my-exchange-key' and 'my-write-key'
    await keys.delete()

    Delete a stored keypair without loading it first. This is the companion to the static exist method. It deletes the given entries from indexedDB, and destroys the cached instance if there is one for those names.

    {
    static async delete (opts?:{
    encryptionKeyName?:string,
    writeKeyName?:string
    }):Promise<void>
    }
    import { EccKeys } from '@substrate-system/keys/ecc'

    await EccKeys.delete()

    // or, if you used custom names
    await EccKeys.delete({
    encryptionKeyName: 'my-exchange-key',
    writeKeyName: 'my-write-key'
    })

    .verify takes the content, the signature, and the DID for the public key used to sign. The DID is exposed as the property .DID on a Keys instance.

    Note


    verify is exposed as a separate function, so you don't have to include all of Keys just to verify a signature.

    import { RsaKeys, verify } from '@substrate-system/keys/rsa'
    // or: import { EccKeys, verify } from '@substrate-system/keys/ecc'

    const keys = await RsaKeys.create()
    // or: const keys = await EccKeys.create()

    // sign something
    const sig = await keys.signAsString('hello string')
    // or string format: const sig = await keys.sign.asString('hello string')

    // verify the signature
    const isOk = await verify('hello string', sig, keys.DID)

    Take the public key we are encrypting to, return encrypted content.

    Encrypt something, return a Uint8Array.

    ECC:

    Note


    recipient is optional. If it is omitted, then this will encrypt to its own public key, a "note to self."

    async encrypt (
    content:string|Uint8Array,
    recipient?:CryptoKey|string, // their public key
    info?:string,
    aesKey?:SymmKey|Uint8Array|string,
    keysize?:SymmKeyLength
    ):Promise<Uint8Array>

    RSA:

    async encrypt (
    content:string|Uint8Array,
    recipient?:CryptoKey|string,
    aesKey?:SymmKey|Uint8Array|string, // For RSA, can pass in AES key
    keysize?:SymmKeyLength,
    ):Promise<Uint8Array>

    Encrypt something, return a string.

    ECC:

    async encryptAsString (
    content:string|Uint8Array,
    recipient?:CryptoKey|string,
    info?:string,
    aesKey?:SymmKey|Uint8Array|string,
    keysize?:SymmKeyLength,
    ):Promise<string>

    RSA:

    async encryptAsString (
    content:string|Uint8Array,
    recipient?:CryptoKey|string,
    aesKey?:SymmKey|Uint8Array|string,
    keysize?:SymmKeyLength,
    ):Promise<string>
    import { encryptTo } from '@substrate-system/keys/rsa'  // RSA version

    // need to know the public key we are encrypting for
    const publicKey = await keys.publicExchangeKeyAsString() // Both ECC and RSA

    const encrypted = await encryptTo({
    content: 'hello public key',
    publicKey
    }) // => ArrayBuffer

    const encrypted = await encryptTo.asString({
    content: 'hello public key',
    publicKey
    }) // => <encrypted text>

    A Keys instance has a method decrypt. The encryptedMessage argument is an ArrayBuffer, as returned from encryptTo, above.

    import { EccKeys } from '@substrate-system/keys/ecc'
    // or: import { RsaKeys } from '@substrate-system/keys/rsa'

    const keys = await EccKeys.create()
    // or: const keys = await RsaKeys.create()

    // This will decrypt the message using our own public key
    const decrypted = await keys.decrypt(encryptedMsg)

    This is exposed as a separate import so that you do not need to bundle all of keys just to verify a signature.

    import { verify } from '@substrate-system/keys/crypto'

    // ed25519
    const isOk = await verify({ message, publicKey: ecc.DID, signature })

    // RSA
    const isOk = await verify({ message, publicKey: rsa.DID, signature })

    Use the factory function EccKeys.create or RsaKeys.create. The optional dbKey parameter prefixes the names used to save both keypairs in indexedDB.

    ECC:

    class EccKeys {
    static EXCHANGE_KEY_NAME:string = 'ecc-exchange'
    static WRITE_KEY_NAME:string = 'ecc-write'

    static async create (
    session?:boolean, // default false
    extractable?:boolean,
    keys?:{
    dbKey?:string,
    exchangeKeys?:CryptoKeyPair|null,
    writeKeys?:CryptoKeyPair|null,
    }
    ):Promise<EccKeys>

    RSA:

    class RsaKeys {
    static EXCHANGE_KEY_NAME:string = 'rsa-exchange'
    static WRITE_KEY_NAME:string = 'rsa-write'

    static async create (
    session?:boolean, // defaut false
    extractable?:boolean,
    keys?:{
    dbKey?:string,
    exchangeKeys?:CryptoKeyPair|null,
    writeKeys?:CryptoKeyPair|null,
    }
    ):Promise<RsaKeys> {
    }
    • session (optional, boolean): If true, keys are created in memory only and won't be saved to indexedDB even if persist() is called.
    • extractable (optional, boolean): If true, creates extractable keys that can be exported/read. Defaults to false for security.
    • keys.dbKey (optional, string): Prefix for both IndexedDB key names.
    • keys.exchangeKeys (optional): Existing exchange keypair to use.
    • keys.writeKeys (optional): Existing signing keypair to use.
    Warning


    Set extractable: true only when you need to export private keys. Non-extractable keys (default) are better for security.

    Use the factory function b/c async.

    import { EccKeys } from '@substrate-system/keys/ecc'
    // or: import { RsaKeys } from '@substrate-system/keys/rsa'

    // Create non-extractable keys (recommended)
    const keys = await EccKeys.create()

    // Create extractable keys (only when export is needed)
    const extractableKeys = await EccKeys.create(false, true)

    // Create session-only, extractable keys
    const sessionKeys = await EccKeys.create(true, true)

    // Session-only keys are not persisted.

    Get a 32-character, DNS-friendly string of the hash of the given DID. Available as static or instance method. If called as an instance method, this will use the DID assigned to the given Keys instance.

    The static method requires a DID string to be passed in.

    class EccKeys {  // or RsaKeys
    static async deviceName (did:DID):Promise<string>
    }

    If used as an instance method, this will use the DID assigned to the instance.

    class EccKeys {  // or RsaKeys
    async getDeviceName ():Promise<string>
    }

    Save the keys to indexedDB. This depends on the values of the static class properties EXCHANGE_KEY_NAME and WRITE_KEY_NAME. Set them if you want to change the indexes under which the keys are saved to indexedDB.

    Defaults for indexedDB:

    • ECC: 'ecc-exchange' and 'ecc-write'
    • RSA: 'rsa-exchange-key' and 'rsa-write-key'
    class EccKeys {  // or RsaKeys
    async persist ():Promise<void>
    }

    You only need this for keys made with .create, or for a .load that opted out with { persist: false }. Otherwise .load has already saved them.

    import { EccKeys } from '@substrate-system/keys/ecc'

    const keys = await EccKeys.create()
    EccKeys.EXCHANGE_KEY_NAME = 'encryption-key-custom-name'
    EccKeys.WRITE_KEY_NAME = 'signing-key-custom-name'
    await keys.persist()

    Create a Keys instance from data saved to indexedDB. Pass in different indexedDB key names for the keys if you need to.

    If there is nothing saved yet, .load creates a new keypair and saves it, so the keys you get back are durable -- reload the page, call .load again, and you get the same identity. There is no separate .persist step to remember. Pass { persist: false } if you want the old two-step behavior.

    class EccKeys {  // or RsaKeys
    static async load (opts?:{
    dbKey?:string,
    encryptionKeyName?:string,
    writeKeyName?:string,
    session?:boolean,
    extractable?:boolean,
    persist?:boolean,
    }):Promise<EccKeys>
    }
    • encryptionKeyName (optional, string): Custom name for the encryption key in indexedDB
    • writeKeyName (optional, string): Custom name for the signing key in indexedDB
    • dbKey (optional, string): Prefix for both default IndexedDB key names.
    • session (optional, boolean): If true, creates session-only keys if no keys exist in indexedDB
    • extractable (optional, boolean): If true and keys don't exist in indexedDB, new keys will be created as extractable. Defaults to false.
    • persist (optional, boolean): Save the keys to indexedDB before returning. Defaults to true. Session keys are never written, so session: true wins over this.
    import { EccKeys } from '@substrate-system/keys/ecc'
    // or: import { RsaKeys } from '@substrate-system/keys/rsa'

    // Load existing keys from indexedDB, or create and save new
    // non-extractable ones
    const newKeys = await EccKeys.load()
    console.log(newKeys.hasPersisted) // true

    // Load with custom options
    const customKeys = await EccKeys.load({
    encryptionKeyName: 'my-custom-encryption-key',
    writeKeyName: 'my-custom-signing-key',
    extractable: true // If keys don't exist, create them as extractable
    })

    // Opt out of saving -- you are responsible for calling `.persist`
    const unsaved = await EccKeys.load({ persist: false })
    console.log(unsaved.hasPersisted) // false
    await unsaved.persist()

    Create a new signature for the given input.

    ECC:

    async sign (msg:Msg, _charsize?:CharSize):Promise<Uint8Array>
    

    RSA:

    async sign (
    msg:Msg,
    charsize:CharSize = DEFAULT_CHAR_SIZE
    ):Promise<Uint8Array>
    const sig = await keys.sign('hello signatures')
    

    Sign a message and return the signature as a base64 encoded string.

    {
    async signAsString (msg:string, charsize?:CharSize):Promise<string>
    }
    const sig = await keys.signAsString('hello string')
    // => ubW9PIjb360v...

    For backward compatibility, the .asString method is still available:

    const sig = await keys.sign.asString('hello string')
    // => ubW9PIjb360v...

    Check if a given signature is valid. This is exposed as a stateless function so that it can be used independently from any keypairs. You need to pass in the data that was signed, the signature, and the DID string of the public key used to create the signature.

    This works the same for either RSA or ECC keys.

    async function verify (
    msg:string|Uint8Array,
    sig:string|Uint8Array,
    signingDid:DID
    ):Promise<boolean>

    RSA verification uses RSA-PSS with SHA-256:

    import { verify } from '@substrate-system/keys/rsa'

    const isOk = await verify('hello string', sig, keys.DID)

    ECC verification uses Ed25519:

    import { verify } from '@substrate-system/keys/ecc'

    const isOk = await verify('hello string', sig, keys.DID)

    Use asymmetric (RSA) encryption to encrypt an AES key to the given public key.

    async function encryptKeyTo ({ key, publicKey }:{
    key:string|Uint8Array|CryptoKey;
    publicKey:CryptoKey|Uint8Array|string;
    }, format?:'uint8array'|'arraybuffer'):Promise<Uint8Array|ArrayBuffer>
    import { encryptKeyTo } from '@substrate-system/keys/rsa'

    // pass in a CryptoKey
    const encrypted = await encryptKeyTo({
    key: myAesKey,
    publicKey: keys.publicExchangeKey
    })

    // pass in a base64 string
    const encryptedTwo = await encryptKeyTo({
    key: aesKey,
    publicKey: await keys.publicExchangeKeyAsString()
    }) // => Uint8Array

    Encrypt the given key to the public key, and return the result as a base64 string.

    !NOTE This is only relevant for RSA keys

    import { encryptKeyTo } from '@substrate-system/keys/rsa'

    encryptKeyTo.asString = async function ({ key, publicKey }:{
    key:string|Uint8Array|CryptoKey;
    publicKey:CryptoKey|string|Uint8Array;
    }, format?:SupportedEncodings):Promise<string> {

    encryptKeyTo.asString takes an optional second argument for the format of the returned string. Format is anything supported by uint8arrays. By default, if omitted, it is base64.

    Encrypt the given message to the given public key. If an AES key is not provided, one will be created. Use the AES key to encrypt the given content, then encrypt the AES key to the given public key.

    !NOTE This is only relevant for RSA keys. If using ECC keys, a symmetric key is automatically generated via diffie-hellman.

    The return value is an ArrayBuffer containing the encrypted AES key + the iv + the encrypted content if using RSA. It is salt + iv + cipher text if using ECC.

    To decrypt, pass the returned value to keys.decrypt, where keys is an instance with the corresponding private key.

    async function encryptTo (
    opts:{
    content:string|Uint8Array;
    publicKey:CryptoKey|string;
    },
    aesKey?:SymmKey|Uint8Array|string,
    ):Promise<ArrayBuffer>
    import { encryptTo } from '@substrate-system/keys/rsa'

    const encrypted = await encryptTo({
    content: 'hello encryption',
    publicKey: keys.publicExchangeKey
    })

    // => ArrayBuffer

    Encrypt the given string, and return a new string that is the (encrypted) AES key concatenated with the iv and cipher text. The corresponding method keys.decryptAsString will know how to parse and decrypt the resulting text.

    Use the functions encryptTo.asString and keys.decryptAsString.

    ECC:

    async decryptAsString (
    msg:string|Uint8Array|ArrayBuffer,
    publicKey?:CryptoKey|string,
    aesAlgorithm?:string,
    info?:string,
    ):Promise<string>

    RSA:

    async decryptAsString (
    msg:string|Uint8Array|ArrayBuffer,
    keysize?:CryptoKey|string|SymmKeyLength,
    _aesAlgorithm?:string,
    ):Promise<string>
    import { RsaKeys, encryptTo } from '@substrate-system/keys/rsa'  // RSA example
    // or: import { EccKeys } from '@substrate-system/keys/ecc'

    const keys = await RsaKeys.create()
    // or: const keys = await EccKeys.create()
    const pubKey = await keys.publicExchangeKeyAsString() // Both ECC and RSA
    const msg = { type: 'test', content: 'hello' }
    const cipherText = await encryptTo.asString({
    content: JSON.stringify(msg),
    // pass in a string public key or crypto key or Uint8Array
    publicKey: pubKey
    }) // => string

    const text = await keys.decryptAsString(cipherText)
    const data = JSON.parse(text)
    // => { type: 'test', content: 'hello' }

    ECC:

    async decrypt (
    msg:string|Uint8Array|ArrayBuffer,
    publicKey?:CryptoKey|string,
    aesAlgorithm?:string,
    info?:string,
    ):Promise<ArrayBuffer>

    !NOTE ECC keys will use our own public key if it is not passed in.

    RSA:

    async decrypt (
    msg:string|Uint8Array|ArrayBuffer,
    keysize?:CryptoKey|string|SymmKeyLength,
    _aesAlgorithm?:string,
    ):Promise<Uint8Array>
    const decrypted = await keys.decrypt(encrypted)
    // => ArrayBuffer (ECC) or Uint8Array (RSA)

    Create a keypair, but do not save it in indexedDB, even if you call persist. Pass true as the session parameter to .create or pass { session: true } to .load. Session keys are never written to indexedDB, so session: true beats the persist default in .load.

    import { EccKeys } from '@substrate-system/keys/ecc'
    // or: import { RsaKeys } from '@substrate-system/keys/rsa'

    const keys = await EccKeys.create(true)
    // or: const keys = await RsaKeys.create(true)

    // or pass it to `.load`
    const keysTwo = await EccKeys.load({ session: true })
    // or: const keysTwo = await RsaKeys.load({ session: true })

    Expose several AES functions, use nice defaults.

    import { AES } from '@substrate-system/keys/aes'

    const key = await AES.create(/* ... optional arguments ... */)

    Create a new AES key. By default uses 256 bits & GCM algorithm.

    import {
    DEFAULT_SYMM_ALGORITHM,
    DEFAULT_SYMM_LENGTH
    } from '@substrate-system/keys/constants'

    function create (opts:{ alg:string, length:number } = {
    alg: DEFAULT_SYMM_ALGORITHM, // AES-GCM
    length: DEFAULT_SYMM_LENGTH // 256
    }):Promise<CryptoKey>
    import { AES } from '@substrate-system/keys/aes'
    const aesKey = await AES.create()

    Get the AES key as a Uint8Array.

    export const AES = {
    async export (key:CryptoKey):Promise<Uint8Array>
    }
    import { AES } from '@substrate-system/keys/aes'

    const exported = await AES.export(myAesKey)

    Get the key as a string, base64 encoded by default.

    async function asString (
    key:CryptoKey,
    format?:SupportedEncoding
    ):Promise<string>
    import { AES } from '@substrate-system/keys/aes'

    const exported = await AES.export.asString(myAesKey)
    // => QlfjZKzzgtNMVC4fPY7S537r/PFstifTyYqcsbsCjHQ=

    const base32 = await AES.export.asString(myAesKey, 'base32')
    // => ijl6gzfm6obngtcufypt3dws457ox7hrns3cpu6jrkoldoycrr2a

    Take a Uint8Array, return an encrypted Uint8Array.

    async function encrypt (
    data:Uint8Array,
    cryptoKey:CryptoKey|Uint8Array,
    iv?:Uint8Array
    ):Promise<Uint8Array>
    import { AES } from '@substrate-system/keys/aes'
    import { fromString } from 'uint8arrays'

    const encryptedText = await AES.encrypt(fromString('hello AES'), aesKey)
    async function decrypt (
    encryptedData:Uint8Array|string,
    cryptoKey:CryptoKey|Uint8Array|ArrayBuffer,
    iv?:Uint8Array
    ):Promise<Uint8Array>
    import { toString } from 'uint8arrays'
    import { AES } from '@substrate-system/keys/aes'

    const decryped = await AES.decrypt(encryptedText, aesKey)
    const decryptedText = toString(decrypted)
    // => 'hello AES'