Encode/decode in multikey format
npm install @substrate-system/multikey







Encode and decode in multikey format.
Multikey format is a generic, self-describing
multicodec-based
public key encoding.
Contents
- Install
- Example
- API
* encode (rawKeyBytes, keyType?)
* decode (multibaseStr)
* Module formats
* pre-built JS
``sh`
npm i -S @substrate-system/multikey
`js
import { encode, decode } from '@substrate-system/multikey'
const subtle = window.crypto.subtle
// Generate an ed25519 keypair
const keypair = await subtle.generateKey(
{ name: 'Ed25519' },
true,
['sign', 'verify']
)
// Export the public key as raw bytes
const publicKeyBytes = await subtle.exportKey('raw', keypair.publicKey)
const publicKey = new Uint8Array(publicKeyBytes)
// Encode to multikey format (base58btc with 'z' prefix)
// keyType defaults to 'ed25519'
const encoded = encode(publicKey)
console.log(encoded)
// => z6Mk... (a string starting with 'z')
// Decode back to raw key bytes
const decoded = decode(encoded)
console.log(decoded.multicodec) // => 237 (ed25519-pub)
console.log(decoded.type) // => 'ed25519'
console.log(decoded.key) // => Uint8Array(32) [...]
// Round-trip encoding preserves the original key
console.log(decoded.key.toString() === publicKey.toString()) // => true
`
`ts`
function encode (
rawKeyBytes:Uint8Array,
keyType:'ed25519'|'rsa' = 'ed25519'
)
Encode a public key to multikey format.
Parameters:
- rawKeyBytes (Uint8Array) - The raw public key byteskeyType
- ('ed25519' | 'rsa', optional) Default is 'ed25519'
Returns: string - A base58btc-encoded multikey string starting with 'z'
#### Encode Example
`js`
const encoded = encode(publicKey) // Ed25519 by default
const encodedRsa = encode(rsaPublicKey, 'rsa') // RSA key
`ts`
function decode (multibaseStr:string):{
multicodec:number,
key:Uint8Array
type:KeyType|'unknown'
}
Decode a multikey format string back to raw key bytes.
Parameters:
* multibaseStr (string) - A multikey string (with or without 'z' prefix)
Returns: { multicodec: number, key: Uint8Array, type: KeyType|'unknown' }
* multicodec - The multicodec identifier (237 for ed25519-pub, 4613 for rsa-pub)key
* - The raw public key bytestype
* - The key type: 'ed25519', 'rsa', or 'unknown'
#### Decode Example
`js`
const decoded = decode('z6Mk...')
console.log(decoded.multicodec) // 237 or 4613 for ed25519 or rsa
console.log(decoded.type) // 'ed25519', 'rsa', or 'unknown'
console.log(decoded.key) // Uint8Array
This exposes ESM and common JS via
package.json exports field.
Works in browsers and Node.
#### ESM
`js`
import { encode, decode } from '@substrate-system/multikey'
#### Common JS
`js`
const multi = require('@substrate-system/multikey')
#### copy
`sh`
cp ./node_modules/@substrate-system/multikey/dist/index.min.js ./public/multikey.min.js
#### HTML
`html``