vetkeys

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

vetKeys (Verifiable Encrypted Threshold Keys)

vetKeys(可验证加密阈值密钥)

vetKeys bring on-chain privacy to the IC via the vetKD protocol: a canister requests a key derived by the subnet's threshold key-derivation infrastructure, receives it encrypted under a client-supplied transport key, and only the client decrypts it locally. No subnet node ever sees the raw key, and in this standard client-delivery pattern neither does the canister — it relays the still-encrypted key to the client. (Some flows deliberately have the canister obtain key material itself: threshold BLS signing and in-canister timelock decryption — see those sections.) Derivation is deterministic: the same
(canister, context, input)
always yields the same key.
Build on the maintained libraries — do not hand-roll the cryptography or the Candid interface:
LayerRustMotokoFrontend
Package
ic-vetkeys
0.9 (crates.io)
ic-vetkeys
0.6 (mops)
@icp-sdk/vetkeys
0.7 (npm)
Management API
ic-cdk-management-canister
,
ic_vetkeys::management_canister
mo:ic-vetkeys/ManagementCanister
—
Low-level primitivescrate root (
ic_vetkeys::…
)
— (not available, see below)package root (
@icp-sdk/vetkeys
)
@dfinity/vetkeys
is legacy
(frozen at 0.4.0). The package was renamed to
@icp-sdk/vetkeys
at 0.5.0. Frontend agent/identity types come from
@icp-sdk/core
(
@icp-sdk/core/agent
,
@icp-sdk/core/principal
), not
@dfinity/agent
/
@dfinity/principal
.
Use 0.7 or later. 0.5 and 0.6 declared
@icp-sdk/core
as a plain dependency, so they could nest a second copy of core beside the one the app installs instead of failing; 0.7 peers it as
^5 || ^6
. The API is identical across all three.
Also required: Rust
ic-cdk = "0.20"
+
ic-cdk-management-canister = "0.1"
(and
ic-dummy-getrandom-for-wasm
for IBE); Motoko
ic-vetkeys
0.6 needs
moc ≥ 1.13.0
/
core ≥ 2.6.1
; frontend
@icp-sdk/core@^6
— vetKeys itself accepts
^5 || ^6
, but the rest of the SDK peers
^6
.
vetKeys 通过 vetKD 协议为 IC 带来链上隐私:canister 请求由子网的阈值密钥派生基础设施生成的密钥,该密钥以客户端提供的传输密钥加密后返回,并且只有客户端能在本地解密。任何子网节点都不会看到原始密钥;在这种标准的客户端交付模式中,canister 也不会看到——它只会将仍处于加密状态的密钥转发给客户端。(某些流程会刻意让 canister 自行获取密钥材料:阈值 BLS 签名和 canister 内的时间锁解密——参见相应章节。)派生过程是确定性的:相同的
(canister, context, input)
始终会产生相同的密钥。
请基于持续维护的库进行构建——不要自行实现密码学或 Candid 接口:
层级RustMotokoFrontend
包
ic-vetkeys
0.9 (crates.io)
ic-vetkeys
0.6 (mops)
@icp-sdk/vetkeys
0.7 (npm)
管理 API
ic-cdk-management-canister
、
ic_vetkeys::management_canister
mo:ic-vetkeys/ManagementCanister
—
底层原语crate 根(
ic_vetkeys::…
)
—(不可用,见下文)包根(
@icp-sdk/vetkeys
)
@dfinity/vetkeys
已过时
(冻结在 0.4.0)。该包从 0.5.0 起更名为
@icp-sdk/vetkeys
。前端 agent/identity 类型来自
@icp-sdk/core
(
@icp-sdk/core/agent
、
@icp-sdk/core/principal
),而不是
@dfinity/agent
/
@dfinity/principal
。
使用 0.7 或更高版本。0.5 和 0.6 将
@icp-sdk/core
声明为普通依赖,因此它们可能会在应用安装的 core 旁再嵌套一份 core,而不是直接失败;0.7 将其声明为 peer dependency
^5 || ^6
。三个库的 API 完全相同。
还需要:Rust
ic-cdk = "0.20"
+
ic-cdk-management-canister = "0.1"
(IBE 还需要
ic-dummy-getrandom-for-wasm
);Motoko
ic-vetkeys
0.6 需要
moc ≥ 1.13.0
/
core ≥ 2.6.1
;前端需要
@icp-sdk/core@^6
——vetKeys 本身接受
^5 || ^6
,但 SDK 的其余部分要求 peer dependency 为
^6
。

Which skill / which feature

选择哪个 skill / 功能

You want to…Use
Store & share encrypted key-value data (password manager, notes, vault)
encrypted-maps
skill
(higher-level, start there)
Encrypt to a principal so only they can decrypt (messaging)IBE →
references/ibe.md
Reveal data only after a deadline (sealed-bid auction, timelock)Timelock IBE →
references/ibe.md
Have the canister produce a signature verifiable by anyoneThreshold BLS →
references/bls-signing.md
Derive a per-user/per-resource symmetric (AES) keySymmetric derivation → this file
Encrypt to a principal without any canister callOffline public-key derivation → this file
Produce on-chain verifiable randomnessVerifiable randomness (VRF) → this file
Authenticate users / loginsnot vetKeys — use the
user-sign-in
skill
你想做什么……使用
存储和共享加密键值数据(密码管理器、笔记、vault)
encrypted-maps
skill
(更上层,请从此开始)
加密给某个 principal,使其成为唯一能够解密的人(消息传递)IBE →
references/ibe.md
仅在截止时间后公开数据(密封竞价、时间锁)时间锁 IBE →
references/ibe.md
让 canister 生成任何人都能验证的签名阈值 BLS →
references/bls-signing.md
派生按用户或资源划分的对称(AES)密钥对称派生 → 本文件
不进行任何 canister 调用,即可加密给某个 principal离线公钥派生 → 本文件
生成链上可验证随机性可验证随机性(VRF) → 本文件
认证用户 / 登录不属于 vetKeys——请使用
user-sign-in
skill

Core concepts

核心概念

  • context — a domain-separator blob that namespaces derived keys within a canister (e.g.
    "my_app"
    , or a per-purpose value like
    "symmetric_key"
    ). It must be identical between the public-key call, the derive call, and any client-side verify/decrypt, or the keys will not match —
    decryptAndVerify
    then throws (the Rust APIs return an error), so handle that failure rather than assuming success.
  • input — application data identifying which key to derive (e.g. a caller principal, a document ID). It is sent to the management canister in plaintext — use it as an identifier, never for secret data.
  • transport key — an ephemeral key pair the client generates per request. The public half is sent so the subnet can encrypt the derived key for delivery; only the holder of the secret half can decrypt. Generate a fresh one each request (
    TransportSecretKey.random()
    ).
  • encrypted vs unencrypted vetKeys — IBE and symmetric derivation use the encrypted delivery flow (transport key →
    decryptAndVerify
    →
    VetKey
    ). Threshold BLS uses the unencrypted vetKey directly; the library's
    sign_with_bls
    /
    signWithBls
    handles that — never feed an encrypted vetKey into BLS.
  • Motoko asymmetry — the Motoko
    ic-vetkeys
    library exposes only the management API +
    KeyManager
    /
    EncryptedMaps
    . It has no IBE, transport keys,
    MasterPublicKey
    /
    DerivedPublicKey
    , or vetKey decryption. In a Motoko app the canister returns the encrypted vetKey and the frontend (
    @icp-sdk/vetkeys
    ) does transport-key generation,
    decryptAndVerify
    , IBE, and symmetric derivation. Those primitives exist in Rust and TypeScript only.
  • context — 用于在 canister 内对派生密钥进行命名空间隔离的域分隔 blob(例如
    "my_app"
    ,或
    "symmetric_key"
    之类的用途标识)。它在公钥调用、派生调用以及任何客户端验证/解密操作中必须完全一致,否则密钥将无法匹配——随后
    decryptAndVerify
    会抛出异常(Rust API 会返回错误)。应正确处理此失败情况,而不是假定操作一定成功。
  • input — 用于标识要派生哪个密钥的应用数据(例如调用方 principal 或文档 ID)。它会以明文形式发送给管理 canister——请将其用作标识符,绝不能用于机密数据。
  • transport key — 客户端为每次请求生成的临时密钥对。其公钥部分会被发送出去,使子网能够加密派生密钥并交付;只有持有私钥部分的人才能解密。每次请求都要生成一个全新的密钥对(
    TransportSecretKey.random()
    )。
  • 加密与未加密的 vetKeys — IBE 和对称派生使用加密交付流程(transport key →
    decryptAndVerify
    →
    VetKey
    )。阈值 BLS 直接使用未加密的 vetKey;库的
    sign_with_bls
    /
    signWithBls
    会处理这一过程——绝不要将加密的 vetKey 传入 BLS。
  • Motoko 的不对称性 — Motoko
    ic-vetkeys
    库仅公开管理 API 以及
    KeyManager
    /
    EncryptedMaps
    。它不提供 IBE、transport key、
    MasterPublicKey
    /
    DerivedPublicKey
    或 vetKey 解密功能。在 Motoko 应用中,canister 返回已加密的 vetKey,由前端(
    @icp-sdk/vetkeys
    )完成 transport key 生成、
    decryptAndVerify
    、IBE 和对称派生。这些原语仅在 Rust 和 TypeScript 中可用。

Key names & cycles

密钥名称与 cycles

Key nameWhere
vetkd_derive_key
cost
test_key_1
local + mainnet (testing)10_000_000_000
key_1
local + mainnet (production)26_153_846_153
vetkd_public_key
is free;
vetkd_derive_key
costs cycles.
test_key_1
and
key_1
behave the same locally and on mainnet. Let the helpers handle the amount: the Rust binding computes the exact cost, and the Motoko
ManagementCanister
attaches
26_153_846_153
with any excess refunded — you only need to keep the canister funded. The management canister is
aaaaa-aa
; calls are routed to the subnet holding the master key.
  • Rust reads the key name from an
    #[init]
    argument (passed via
    init_args
    in
    icp.yaml
    ).
  • Motoko reads it from the
    VETKD_KEY_NAME
    canister environment variable, defaulting to
    test_key_1
    . The name is captured into stable state at first install and is immutable for the life of the canister's data — changing it later is silently ignored (only a
    reinstall
    , which drops state, switches keys). Because
    test_key_1
    is also a valid mainnet key, a production deploy that forgets to set
    VETKD_KEY_NAME
    silently runs on it — assert the expected key at deploy time if that matters.
密钥名称使用环境
vetkd_derive_key
成本
test_key_1
local + mainnet(测试)10_000_000_000
key_1
local + mainnet(生产)26_153_846_153
vetkd_public_key
免费;
vetkd_derive_key
需要消耗 cycles。
test_key_1
和
key_1
在 local 与 mainnet 上的行为相同。请让辅助函数处理所需金额:Rust binding 会计算精确成本,而 Motoko
ManagementCanister
会附加
26_153_846_153
,多余部分将自动退还——只需确保 canister 有充足资金即可。管理 canister 为
aaaaa-aa
;调用会被路由到持有主密钥的子网。
  • Rust 从
    #[init]
    参数读取密钥名称(通过
    icp.yaml
    中的
    init_args
    传入)。
  • Motoko 从
    VETKD_KEY_NAME
    canister 环境变量读取密钥名称,默认值为
    test_key_1
    。该名称会在首次安装时写入 stable state,并且在 canister 数据的整个生命周期内不可变——之后再更改会被静默忽略(只有
    reinstall
    才能切换密钥,同时会丢弃状态)。由于
    test_key_1
    在 mainnet 上也是有效密钥,生产部署如果忘记设置
    VETKD_KEY_NAME
    ,就会静默使用该密钥;如果这很重要,请在部署时断言预期的密钥名称。

The vetKD management API (foundation + symmetric encryption)

vetKD 管理 API(基础能力 + 对称加密)

The management API has two endpoints:
vetkd_public_key
(verification / offline-encryption public key) and
vetkd_derive_key
(the caller's encrypted key). This is the foundation for symmetric encryption, IBE, and BLS. Call it through the library helpers so the Candid types and cycles are correct.
管理 API 包含两个端点:
vetkd_public_key
(用于验证和离线加密的公钥)以及
vetkd_derive_key
(返回调用方的加密密钥)。这是对称加密、IBE 和 BLS 的基础。请通过库辅助函数调用,以确保 Candid 类型和 cycles 数量正确。

Backend — Rust

后端——Rust

rust
use ic_cdk::update;
use ic_cdk_management_canister::{VetKDCurve, VetKDDeriveKeyArgs, VetKDKeyId, VetKDPublicKeyArgs};

const CONTEXT: &[u8] = b"symmetric_key"; // domain separator; must match on the client

fn key_id() -> VetKDKeyId {
    // name comes from an #[init] arg in real code; "test_key_1" for local + mainnet testing
    VetKDKeyId { curve: VetKDCurve::Bls12_381_G2, name: "test_key_1".to_string() }
}

#[update]
async fn symmetric_verification_key() -> Vec<u8> {
    let res = ic_cdk_management_canister::vetkd_public_key(&VetKDPublicKeyArgs {
        canister_id: None, // defaults to this canister
        context: CONTEXT.to_vec(),
        key_id: key_id(),
    })
    .await
    .expect("vetkd_public_key failed");
    res.public_key // no cycles required
}

#[update]
async fn encrypted_symmetric_key_for_caller(transport_public_key: Vec<u8>) -> Vec<u8> {
    let caller = ic_cdk::api::msg_caller(); // capture BEFORE the await
    let res = ic_cdk_management_canister::vetkd_derive_key(&VetKDDeriveKeyArgs {
        input: caller.as_slice().to_vec(), // key identifier (plaintext) — never secret data
        context: CONTEXT.to_vec(),
        transport_public_key,
        key_id: key_id(),
    })
    .await // the binding attaches the required cycles automatically
    .expect("vetkd_derive_key failed");
    res.encrypted_key
}
rust
use ic_cdk::update;
use ic_cdk_management_canister::{VetKDCurve, VetKDDeriveKeyArgs, VetKDKeyId, VetKDPublicKeyArgs};

const CONTEXT: &[u8] = b"symmetric_key"; // domain separator; must match on the client

fn key_id() -> VetKDKeyId {
    // name comes from an #[init] arg in real code; "test_key_1" for local + mainnet testing
    VetKDKeyId { curve: VetKDCurve::Bls12_381_G2, name: "test_key_1".to_string() }
}

#[update]
async fn symmetric_verification_key() -> Vec<u8> {
    let res = ic_cdk_management_canister::vetkd_public_key(&VetKDPublicKeyArgs {
        canister_id: None, // defaults to this canister
        context: CONTEXT.to_vec(),
        key_id: key_id(),
    })
    .await
    .expect("vetkd_public_key failed");
    res.public_key // no cycles required
}

#[update]
async fn encrypted_symmetric_key_for_caller(transport_public_key: Vec<u8>) -> Vec<u8> {
    let caller = ic_cdk::api::msg_caller(); // capture BEFORE the await
    let res = ic_cdk_management_canister::vetkd_derive_key(&VetKDDeriveKeyArgs {
        input: caller.as_slice().to_vec(), // key identifier (plaintext) — never secret data
        context: CONTEXT.to_vec(),
        transport_public_key,
        key_id: key_id(),
    })
    .await // the binding attaches the required cycles automatically
    .expect("vetkd_derive_key failed");
    res.encrypted_key
}

Backend — Motoko

后端——Motoko

motoko
import ManagementCanister "mo:ic-vetkeys/ManagementCanister";
import Principal "mo:core/Principal";
import Text "mo:core/Text";
import Runtime "mo:core/Runtime";

persistent actor {
  // Captured into keyId at first install and fixed for the life of the canister's derived keys;
  // changing VETKD_KEY_NAME on a later upgrade has no effect (see the key-name warning above).
  let keyName = Runtime.envVar<system>("VETKD_KEY_NAME") ?? "test_key_1";
  let keyId : ManagementCanister.VetKdKeyid = { curve = #bls12_381_g2; name = keyName };

  public shared func symmetricVerificationKey() : async Blob {
    // context / domain separator; no cycles required
    await ManagementCanister.vetKdPublicKey(null, Text.encodeUtf8("symmetric_key"), keyId);
  };

  public shared ({ caller }) func encryptedSymmetricKeyForCaller(transportPublicKey : Blob) : async Blob {
    // signature is (input, context, keyId, transportPublicKey); helper attaches cycles automatically
    await ManagementCanister.vetKdDeriveKey(
      Principal.toBlob(caller), Text.encodeUtf8("symmetric_key"), keyId, transportPublicKey);
  };
};
motoko
import ManagementCanister "mo:ic-vetkeys/ManagementCanister";
import Principal "mo:core/Principal";
import Text "mo:core/Text";
import Runtime "mo:core/Runtime";

persistent actor {
  // Captured into keyId at first install and fixed for the life of the canister's derived keys;
  // changing VETKD_KEY_NAME on a later upgrade has no effect (see the key-name warning above).
  let keyName = Runtime.envVar<system>("VETKD_KEY_NAME") ?? "test_key_1";
  let keyId : ManagementCanister.VetKdKeyid = { curve = #bls12_381_g2; name = keyName };

  public shared func symmetricVerificationKey() : async Blob {
    // context / domain separator; no cycles required
    await ManagementCanister.vetKdPublicKey(null, Text.encodeUtf8("symmetric_key"), keyId);
  };

  public shared ({ caller }) func encryptedSymmetricKeyForCaller(transportPublicKey : Blob) : async Blob {
    // signature is (input, context, keyId, transportPublicKey); helper attaches cycles automatically
    await ManagementCanister.vetKdDeriveKey(
      Principal.toBlob(caller), Text.encodeUtf8("symmetric_key"), keyId, transportPublicKey);
  };
};

Frontend — derive an AES-GCM key (TypeScript)

前端——派生 AES-GCM 密钥(TypeScript)

The canister returns the encrypted vetKey; the frontend generates the transport key, decrypts & verifies it into a
VetKey
, then derives AES-GCM key material.
typescript
import { TransportSecretKey, DerivedPublicKey, EncryptedVetKey } from "@icp-sdk/vetkeys";
// `backend` is your actor; `myPrincipal` is the authenticated caller's Principal (@icp-sdk/core/principal)

// 1. Fresh transport key per request
const tsk = TransportSecretKey.random();

// 2. Fetch the encrypted derived key + the public verification key
const [encryptedKeyBytes, publicKeyBytes] = await Promise.all([
  backend.encrypted_symmetric_key_for_caller(tsk.publicKeyBytes()),
  backend.symmetric_verification_key(),
]);

// 3. Decrypt & verify -> VetKey. The identity bytes MUST equal the backend `input`
//    (here the caller principal), or verification throws.
const vetKey = EncryptedVetKey.deserialize(new Uint8Array(encryptedKeyBytes)).decryptAndVerify(
  tsk,
  DerivedPublicKey.deserialize(new Uint8Array(publicKeyBytes)),
  myPrincipal.toUint8Array(),
);

// 4. Derive AES-GCM key material and encrypt/decrypt. There is NO `toDerivedKeyMaterial()`.
const keyMaterial = await vetKey.asDerivedKeyMaterial();
const domainSep = "my_app:notes"; // unique per app + usage
const ciphertext = await keyMaterial.encryptMessage("secret message", domainSep, ""); // (msg, domainSep, associatedData)
const plaintext = await keyMaterial.decryptMessage(ciphertext, domainSep, "");
// new TextDecoder().decode(plaintext) === "secret message"
canister 返回已加密的 vetKey;前端生成 transport key,将其解密并验证为
VetKey
,然后派生 AES-GCM 密钥材料。
typescript
import { TransportSecretKey, DerivedPublicKey, EncryptedVetKey } from "@icp-sdk/vetkeys";
// `backend` is your actor; `myPrincipal` is the authenticated caller's Principal (@icp-sdk/core/principal)

// 1. Fresh transport key per request
const tsk = TransportSecretKey.random();

// 2. Fetch the encrypted derived key + the public verification key
const [encryptedKeyBytes, publicKeyBytes] = await Promise.all([
  backend.encrypted_symmetric_key_for_caller(tsk.publicKeyBytes()),
  backend.symmetric_verification_key(),
]);

// 3. Decrypt & verify -> VetKey. The identity bytes MUST equal the backend `input`
//    (here the caller principal), or verification throws.
const vetKey = EncryptedVetKey.deserialize(new Uint8Array(encryptedKeyBytes)).decryptAndVerify(
  tsk,
  DerivedPublicKey.deserialize(new Uint8Array(publicKeyBytes)),
  myPrincipal.toUint8Array(),
);

// 4. Derive AES-GCM key material and encrypt/decrypt. There is NO `toDerivedKeyMaterial()`.
const keyMaterial = await vetKey.asDerivedKeyMaterial();
const domainSep = "my_app:notes"; // unique per app + usage
const ciphertext = await keyMaterial.encryptMessage("secret message", domainSep, ""); // (msg, domainSep, associatedData)
const plaintext = await keyMaterial.decryptMessage(ciphertext, domainSep, "");
// new TextDecoder().decode(plaintext) === "secret message"

Offline public-key derivation

离线公钥派生

Derive a canister's public key for a context without any canister call, starting from the known mainnet master public key. Used to encrypt (IBE) to a principal when neither the recipient nor the canister is online.
TypeScript:
typescript
import { MasterPublicKey } from "@icp-sdk/vetkeys";
import { Principal } from "@icp-sdk/core/principal";

const derivedPublicKey = MasterPublicKey.productionKey()            // key_1 (default); MasterPublicKey.pocketicKey() for local
  .deriveCanisterKey(Principal.fromText(canisterId).toUint8Array())
  .deriveSubKey(new TextEncoder().encode("my_app"));               // the context / domain separator
// derivedPublicKey (a DerivedPublicKey) can now be used for IBE encryption offline
Rust:
rust
use ic_vetkeys::{MasterPublicKey, DerivedPublicKey};
use ic_cdk_management_canister::{VetKDCurve, VetKDKeyId};

let master = MasterPublicKey::for_mainnet_key(&VetKDKeyId {
    curve: VetKDCurve::Bls12_381_G2,
    name: "key_1".to_string(),
}).expect("unknown key name");                     // for_pocketic_key(..) for local
let derived: DerivedPublicKey = master
    .derive_canister_key(canister_id.as_slice())
    .derive_sub_key(b"my_app");
从已知的主网主公钥开始,为某个 context 派生 canister 的公钥,无需任何 canister 调用。当接收方和 canister 都不在线时,可用于加密(IBE)给某个 principal。
TypeScript:
typescript
import { MasterPublicKey } from "@icp-sdk/vetkeys";
import { Principal } from "@icp-sdk/core/principal";

const derivedPublicKey = MasterPublicKey.productionKey()            // key_1 (default); MasterPublicKey.pocketicKey() for local
  .deriveCanisterKey(Principal.fromText(canisterId).toUint8Array())
  .deriveSubKey(new TextEncoder().encode("my_app"));               // the context / domain separator
// derivedPublicKey (a DerivedPublicKey) can now be used for IBE encryption offline
Rust:
rust
use ic_vetkeys::{MasterPublicKey, DerivedPublicKey};
use ic_cdk_management_canister::{VetKDCurve, VetKDKeyId};

let master = MasterPublicKey::for_mainnet_key(&VetKDKeyId {
    curve: VetKDCurve::Bls12_381_G2,
    name: "key_1".to_string(),
}).expect("unknown key name");                     // for_pocketic_key(..) for local
let derived: DerivedPublicKey = master
    .derive_canister_key(canister_id.as_slice())
    .derive_sub_key(b"my_app");

Verifiable randomness (VRF)

可验证随机性(VRF)

A vetKey can be turned into verifiable randomness: a Rust canister calls
ic_vetkeys::management_canister::compute_vrf(input, context, key_id) -> VrfOutput
(scope
input
/
context
to the draw, e.g. a lottery round or leader election), and the frontend verifies the proof with
VrfOutput.deserialize(...)
from
@icp-sdk/vetkeys
. No canonical end-to-end example ships yet. (Not available in the Motoko library — derive on a Rust canister.)
vetKey 可以转换为可验证随机性:Rust canister 调用
ic_vetkeys::management_canister::compute_vrf(input, context, key_id) -> VrfOutput
(将
input
/
context
的范围限定到具体抽取场景,例如彩票轮次或领导者选举),前端则使用
@icp-sdk/vetkeys
中的
VrfOutput.deserialize(...)
验证证明。目前尚无官方提供的完整端到端示例。(Motoko 库不支持此功能——请在 Rust canister 中派生。)

Pitfalls

常见陷阱

  1. Wrong package / imports. Use
    @icp-sdk/vetkeys
    (≥0.7), not
    @dfinity/vetkeys
    (frozen at 0.4). Import agent/identity from
    @icp-sdk/core
    (
    @icp-sdk/core/agent
    ,
    @icp-sdk/core/principal
    ), and build the agent with
    await HttpAgent.create({ identity, host, rootKey })
    — the client classes take a ready
    HttpAgent
    , not options. Get
    rootKey
    from
    safeGetCanisterEnv()
    (
    @icp-sdk/core/agent/canister-env
    ); never call
    fetchRootKey()
    in shipped code (see the
    icp-cli
    skill).
  2. toDerivedKeyMaterial()
    does not exist.
    For symmetric encryption:
    const dkm = await vetKey.asDerivedKeyMaterial()
    , then
    await dkm.encryptMessage(msg, domainSep, associatedData)
    /
    await dkm.decryptMessage(ct, domainSep, associatedData)
    (all async). Never use the raw decrypted vetKey bytes directly as an AES key.
  3. Don't hand-roll the management interface. Rust:
    ic-cdk-management-canister
    (
    vetkd_public_key
    /
    vetkd_derive_key
    ) or
    ic_vetkeys::management_canister
    (also
    sign_with_bls
    ). Motoko:
    mo:ic-vetkeys/ManagementCanister
    (
    vetKdPublicKey
    ,
    vetKdDeriveKey
    ,
    signWithBls
    ,
    blsPublicKey
    ). These carry the correct Candid types and attach the right cycles automatically. Hand-declaring
    actor "aaaaa-aa"
    and the
    vetkd_*
    records is unnecessary and error-prone.
  4. Motoko has no low-level crypto. No IBE, transport keys,
    MasterPublicKey
    /
    DerivedPublicKey
    , or vetKey decryption in the Motoko library. The Motoko canister returns the encrypted vetKey; the frontend
    @icp-sdk/vetkeys
    (or a Rust off-chain client) does the rest.
  5. Fund the canister for derivations.
    vetkd_derive_key
    costs cycles (
    key_1
    = 26_153_846_153,
    test_key_1
    = 10_000_000_000 — the same locally and on mainnet);
    vetkd_public_key
    is free. Let the helpers attach the amount — the Rust binding computes the exact cost, the Motoko helper attaches 26_153_846_153 and the excess is refunded — and keep the canister topped up.
  6. context
    and
    input
    must match end to end.
    A different
    context
    (or a different
    input
    ) produces a different key;
    decryptAndVerify
    then throws (the Rust APIs return an error) rather than returning wrong plaintext — handle it, and keep
    context
    /
    input
    byte-identical across public-key, derive, and client verify/decrypt.
  7. input
    is plaintext.
    It is a key identifier sent to the management canister — use IDs (principal, document ID), never secret data.
  8. Capture the caller before
    await
    .
    ic_cdk::api::msg_caller()
    (Rust) / destructure
    ({ caller })
    (Motoko) before the async derive call.
  9. Enforce authorization when hand-rolling derivation. If you call
    vetkd_derive_key
    directly (not via
    KeyManager
    /
    EncryptedMaps
    ), the canister must ensure it only derives for an
    input
    the caller is entitled to (e.g. their own principal). Otherwise any caller can obtain anyone's key.
  10. BLS uses the unencrypted key. Use
    sign_with_bls
    /
    signWithBls
    ; don't feed an encrypted vetKey into BLS, and don't reuse the same
    context
    /
    input
    across IBE and BLS.
  11. Rust randomness on Wasm. IBE seeds need randomness; add
    ic-dummy-getrandom-for-wasm
    (or a
    getrandom
    wasm shim) or the canister traps. (The frontend uses WebCrypto — fine.)
  12. Modern ic-cdk call API. Use
    ic_cdk::api::msg_caller()
    (not
    ic_cdk::caller()
    ). If you ever call the management canister without the binding, use
    ic_cdk::call::Call::unbounded_wait(..).with_cycles(..)
    — the legacy
    ic_cdk::api::call::call*
    API is removed in ic-cdk 0.20+.
  1. 使用了错误的包或 import。 使用
    @icp-sdk/vetkeys
    (≥0.7),不要使用
    @dfinity/vetkeys
    (冻结在 0.4)。从
    @icp-sdk/core
    (
    @icp-sdk/core/agent
    、
    @icp-sdk/core/principal
    )导入 agent/identity,并使用
    await HttpAgent.create({ identity, host, rootKey })
    创建 agent——客户端类接收的是已经创建好的
    HttpAgent
    ,而不是选项对象。通过
    safeGetCanisterEnv()
    (
    @icp-sdk/core/agent/canister-env
    )获取
    rootKey
    ;在正式发布的代码中绝不调用
    fetchRootKey()
    (参见
    icp-cli
    skill)。
  2. 不存在
    toDerivedKeyMaterial()
    。
    对于对称加密:使用
    const dkm = await vetKey.asDerivedKeyMaterial()
    ,然后调用
    await dkm.encryptMessage(msg, domainSep, associatedData)
    /
    await dkm.decryptMessage(ct, domainSep, associatedData)
    (均为异步操作)。绝不要将解密后的原始 vetKey 字节直接用作 AES 密钥。
  3. 不要自行实现管理接口。 Rust:使用
    ic-cdk-management-canister
    (
    vetkd_public_key
    /
    vetkd_derive_key
    )或
    ic_vetkeys::management_canister
    (也支持
    sign_with_bls
    )。Motoko:使用
    mo:ic-vetkeys/ManagementCanister
    (
    vetKdPublicKey
    、
    vetKdDeriveKey
    、
    signWithBls
    、
    blsPublicKey
    )。这些接口包含正确的 Candid 类型,并会自动附加所需 cycles。手动声明
    actor "aaaaa-aa"
    和
    vetkd_*
    record 既没有必要,也容易出错。
  4. Motoko 不提供底层密码学原语。 Motoko 库中没有 IBE、transport key、
    MasterPublicKey
    /
    DerivedPublicKey
    或 vetKey 解密功能。Motoko canister 返回已加密的 vetKey;其余操作由前端
    @icp-sdk/vetkeys
    (或 Rust 链下客户端)完成。
  5. 为派生操作向 canister 充值。
    vetkd_derive_key
    会消耗 cycles(
    key_1
    = 26_153_846_153,
    test_key_1
    = 10_000_000_000——local 与 mainnet 上相同);
    vetkd_public_key
    免费。让辅助函数附加所需金额——Rust binding 会计算精确成本,Motoko 辅助函数会附加 26_153_846_153,多余部分将退还——并确保 canister 始终有充足资金。
  6. context
    和
    input
    必须端到端一致。
    不同的
    context
    (或不同的
    input
    )会产生不同的密钥;随后
    decryptAndVerify
    将抛出异常(Rust API 会返回错误),而不是返回错误的明文。请处理此情况,并确保公钥、派生和客户端验证/解密流程中的
    context
    /
    input
    字节完全一致。
  7. input
    是明文。
    它是发送给管理 canister 的密钥标识符——请使用 ID(principal、文档 ID),绝不要用于机密数据。
  8. 在
    await
    之前捕获调用方。
    在异步派生调用之前调用
    ic_cdk::api::msg_caller()
    (Rust),或在 Motoko 中解构
    ({ caller })
    。
  9. 自行实现派生逻辑时必须执行授权检查。 如果直接调用
    vetkd_derive_key
    (而不是通过
    KeyManager
    /
    EncryptedMaps
    ),canister 必须确保只能为调用方有权访问的
    input
    派生密钥(例如其自己的 principal)。否则任何调用方都能获取他人的密钥。
  10. BLS 使用未加密的密钥。 使用
    sign_with_bls
    /
    signWithBls
    ;不要将加密的 vetKey 传入 BLS,也不要在 IBE 和 BLS 之间复用相同的
    context
    /
    input
    。
  11. Wasm 上的 Rust 随机性。 IBE seed 需要随机性;请添加
    ic-dummy-getrandom-for-wasm
    (或
    getrandom
    wasm shim),否则 canister 会触发 trap。(前端使用 WebCrypto——没有问题。)
  12. 现代 ic-cdk 调用 API。 使用
    ic_cdk::api::msg_caller()
    (不要使用
    ic_cdk::caller()
    )。如果必须在没有 binding 的情况下调用管理 canister,请使用
    ic_cdk::call::Call::unbounded_wait(..).with_cycles(..)
    ——旧的
    ic_cdk::api::call::call*
    API 已从 ic-cdk 0.20+ 中移除。

Feature guides

功能指南

  • Identity-Based Encryption (IBE) & timelock — encrypt with
    IbeCiphertext.encrypt(publicKey, IbeIdentity.fromPrincipal(recipient), plaintext, IbeSeed.random())
    ; the recipient decrypts with
    IbeCiphertext.deserialize(ct).decrypt(vetKey)
    . Full backend + frontend + timelock:
    references/ibe.md
    .
  • Threshold BLS signatures — sign with
    ic_vetkeys::management_canister::sign_with_bls
    (Rust) /
    ManagementCanister.signWithBls
    (Motoko); verify with
    verifyBlsSignature(derivedPublicKey, message, signature)
    . Details:
    references/bls-signing.md
    .
  • Encrypted key-value storage (EncryptedMaps / KeyManager) — the
    encrypted-maps
    skill.
  • 基于身份的加密(IBE)与时间锁——使用
    IbeCiphertext.encrypt(publicKey, IbeIdentity.fromPrincipal(recipient), plaintext, IbeSeed.random())
    加密;接收方使用
    IbeCiphertext.deserialize(ct).decrypt(vetKey)
    解密。完整后端、前端和时间锁实现:
    references/ibe.md
    。
  • 阈值 BLS 签名——使用
    ic_vetkeys::management_canister::sign_with_bls
    (Rust)/
    ManagementCanister.signWithBls
    (Motoko)签名;使用
    verifyBlsSignature(derivedPublicKey, message, signature)
    验证。详情参见
    references/bls-signing.md
    。
  • 加密键值存储(EncryptedMaps / KeyManager)——使用
    encrypted-maps
    skill
    。

Deploy & verify

部署与验证

Provisioning,
icp.yaml
, and generic deploy steps belong to the
icp-cli
skill. vetKeys-specific checks:
bash
icp deploy backend                                    # local replica provisions test_key_1
icp canister call backend symmetric_verification_key '()'   # non-empty BLS public-key blob
资源配置、
icp.yaml
和通用部署步骤属于
icp-cli
skill
。vetKeys 专属检查如下:
bash
icp deploy backend                                    # local replica provisions test_key_1
icp canister call backend symmetric_verification_key '()'   # non-empty BLS public-key blob

derive needs a 48-byte transport public key from the frontend; different callers get different keys

derive needs a 48-byte transport public key from the frontend; different callers get different keys

undefined
undefined