vetkeys
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesevetKeys (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 always yields the same key.
(canister, context, input)Build on the maintained libraries — do not hand-roll the cryptography or the Candid interface:
| Layer | Rust | Motoko | Frontend |
|---|---|---|---|
| Package | | | |
| Management API | | | — |
| Low-level primitives | crate root ( | — (not available, see below) | package root ( |
is legacy (frozen at 0.4.0). The package was renamed to@dfinity/vetkeysat 0.5.0. Frontend agent/identity types come from@icp-sdk/vetkeys(@icp-sdk/core,@icp-sdk/core/agent), not@icp-sdk/core/principal/@dfinity/agent.@dfinity/principalUse 0.7 or later. 0.5 and 0.6 declaredas 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@icp-sdk/core. The API is identical across all three.^5 || ^6
Also required: Rust + (and for IBE); Motoko 0.6 needs / ; frontend — vetKeys itself accepts , but the rest of the SDK peers .
ic-cdk = "0.20"ic-cdk-management-canister = "0.1"ic-dummy-getrandom-for-wasmic-vetkeysmoc ≥ 1.13.0core ≥ 2.6.1@icp-sdk/core@^6^5 || ^6^6vetKeys 通过 vetKD 协议为 IC 带来链上隐私:canister 请求由子网的阈值密钥派生基础设施生成的密钥,该密钥以客户端提供的传输密钥加密后返回,并且只有客户端能在本地解密。任何子网节点都不会看到原始密钥;在这种标准的客户端交付模式中,canister 也不会看到——它只会将仍处于加密状态的密钥转发给客户端。(某些流程会刻意让 canister 自行获取密钥材料:阈值 BLS 签名和 canister 内的时间锁解密——参见相应章节。)派生过程是确定性的:相同的 始终会产生相同的密钥。
(canister, context, input)请基于持续维护的库进行构建——不要自行实现密码学或 Candid 接口:
| 层级 | Rust | Motoko | Frontend |
|---|---|---|---|
| 包 | | | |
| 管理 API | | | — |
| 底层原语 | crate 根( | —(不可用,见下文) | 包根( |
已过时(冻结在 0.4.0)。该包从 0.5.0 起更名为@dfinity/vetkeys。前端 agent/identity 类型来自@icp-sdk/vetkeys(@icp-sdk/core、@icp-sdk/core/agent),而不是@icp-sdk/core/principal/@dfinity/agent。@dfinity/principal使用 0.7 或更高版本。0.5 和 0.6 将声明为普通依赖,因此它们可能会在应用安装的 core 旁再嵌套一份 core,而不是直接失败;0.7 将其声明为 peer dependency@icp-sdk/core。三个库的 API 完全相同。^5 || ^6
还需要:Rust + (IBE 还需要 );Motoko 0.6 需要 / ;前端需要 ——vetKeys 本身接受 ,但 SDK 的其余部分要求 peer dependency 为 。
ic-cdk = "0.20"ic-cdk-management-canister = "0.1"ic-dummy-getrandom-for-wasmic-vetkeysmoc ≥ 1.13.0core ≥ 2.6.1@icp-sdk/core@^6^5 || ^6^6Which skill / which feature
选择哪个 skill / 功能
| You want to… | Use |
|---|---|
| Store & share encrypted key-value data (password manager, notes, vault) | |
| Encrypt to a principal so only they can decrypt (messaging) | IBE → |
| Reveal data only after a deadline (sealed-bid auction, timelock) | Timelock IBE → |
| Have the canister produce a signature verifiable by anyone | Threshold BLS → |
| Derive a per-user/per-resource symmetric (AES) key | Symmetric derivation → this file |
| Encrypt to a principal without any canister call | Offline public-key derivation → this file |
| Produce on-chain verifiable randomness | Verifiable randomness (VRF) → this file |
| Authenticate users / logins | not vetKeys — use the |
| 你想做什么…… | 使用 |
|---|---|
| 存储和共享加密键值数据(密码管理器、笔记、vault) | |
| 加密给某个 principal,使其成为唯一能够解密的人(消息传递) | IBE → |
| 仅在截止时间后公开数据(密封竞价、时间锁) | 时间锁 IBE → |
| 让 canister 生成任何人都能验证的签名 | 阈值 BLS → |
| 派生按用户或资源划分的对称(AES)密钥 | 对称派生 → 本文件 |
| 不进行任何 canister 调用,即可加密给某个 principal | 离线公钥派生 → 本文件 |
| 生成链上可验证随机性 | 可验证随机性(VRF) → 本文件 |
| 认证用户 / 登录 | 不属于 vetKeys——请使用 |
Core concepts
核心概念
- context — a domain-separator blob that namespaces derived keys within a canister (e.g. , or a per-purpose value like
"my_app"). It must be identical between the public-key call, the derive call, and any client-side verify/decrypt, or the keys will not match —"symmetric_key"then throws (the Rust APIs return an error), so handle that failure rather than assuming success.decryptAndVerify - 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). Threshold BLS uses the unencrypted vetKey directly; the library'sVetKey/sign_with_blshandles that — never feed an encrypted vetKey into BLS.signWithBls - Motoko asymmetry — the Motoko library exposes only the management API +
ic-vetkeys/KeyManager. It has no IBE, transport keys,EncryptedMaps/MasterPublicKey, or vetKey decryption. In a Motoko app the canister returns the encrypted vetKey and the frontend (DerivedPublicKey) does transport-key generation,@icp-sdk/vetkeys, IBE, and symmetric derivation. Those primitives exist in Rust and TypeScript only.decryptAndVerify
- context — 用于在 canister 内对派生密钥进行命名空间隔离的域分隔 blob(例如 ,或
"my_app"之类的用途标识)。它在公钥调用、派生调用以及任何客户端验证/解密操作中必须完全一致,否则密钥将无法匹配——随后"symmetric_key"会抛出异常(Rust API 会返回错误)。应正确处理此失败情况,而不是假定操作一定成功。decryptAndVerify - input — 用于标识要派生哪个密钥的应用数据(例如调用方 principal 或文档 ID)。它会以明文形式发送给管理 canister——请将其用作标识符,绝不能用于机密数据。
- transport key — 客户端为每次请求生成的临时密钥对。其公钥部分会被发送出去,使子网能够加密派生密钥并交付;只有持有私钥部分的人才能解密。每次请求都要生成一个全新的密钥对()。
TransportSecretKey.random() - 加密与未加密的 vetKeys — IBE 和对称派生使用加密交付流程(transport key → →
decryptAndVerify)。阈值 BLS 直接使用未加密的 vetKey;库的VetKey/sign_with_bls会处理这一过程——绝不要将加密的 vetKey 传入 BLS。signWithBls - Motoko 的不对称性 — Motoko 库仅公开管理 API 以及
ic-vetkeys/KeyManager。它不提供 IBE、transport key、EncryptedMaps/MasterPublicKey或 vetKey 解密功能。在 Motoko 应用中,canister 返回已加密的 vetKey,由前端(DerivedPublicKey)完成 transport key 生成、@icp-sdk/vetkeys、IBE 和对称派生。这些原语仅在 Rust 和 TypeScript 中可用。decryptAndVerify
Key names & cycles
密钥名称与 cycles
| Key name | Where | |
|---|---|---|
| local + mainnet (testing) | 10_000_000_000 |
| local + mainnet (production) | 26_153_846_153 |
vetkd_public_keyvetkd_derive_keytest_key_1key_1ManagementCanister26_153_846_153aaaaa-aa- Rust reads the key name from an argument (passed via
#[init]ininit_args).icp.yaml - Motoko reads it from the canister environment variable, defaulting to
VETKD_KEY_NAME. 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 atest_key_1, which drops state, switches keys). Becausereinstallis also a valid mainnet key, a production deploy that forgets to settest_key_1silently runs on it — assert the expected key at deploy time if that matters.VETKD_KEY_NAME
| 密钥名称 | 使用环境 | |
|---|---|---|
| local + mainnet(测试) | 10_000_000_000 |
| local + mainnet(生产) | 26_153_846_153 |
vetkd_public_keyvetkd_derive_keytest_key_1key_1ManagementCanister26_153_846_153aaaaa-aa- Rust 从 参数读取密钥名称(通过
#[init]中的icp.yaml传入)。init_args - Motoko 从 canister 环境变量读取密钥名称,默认值为
VETKD_KEY_NAME。该名称会在首次安装时写入 stable state,并且在 canister 数据的整个生命周期内不可变——之后再更改会被静默忽略(只有test_key_1才能切换密钥,同时会丢弃状态)。由于reinstall在 mainnet 上也是有效密钥,生产部署如果忘记设置test_key_1,就会静默使用该密钥;如果这很重要,请在部署时断言预期的密钥名称。VETKD_KEY_NAME
The vetKD management API (foundation + symmetric encryption)
vetKD 管理 API(基础能力 + 对称加密)
The management API has two endpoints: (verification / offline-encryption public key) and (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.
vetkd_public_keyvetkd_derive_key管理 API 包含两个端点:(用于验证和离线加密的公钥)以及 (返回调用方的加密密钥)。这是对称加密、IBE 和 BLS 的基础。请通过库辅助函数调用,以确保 Candid 类型和 cycles 数量正确。
vetkd_public_keyvetkd_derive_keyBackend — 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 , then derives AES-GCM key material.
VetKeytypescript
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,将其解密并验证为 ,然后派生 AES-GCM 密钥材料。
VetKeytypescript
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 offlineRust:
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 offlineRust:
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 (scope / to the draw, e.g. a lottery round or leader election), and the frontend verifies the proof with from . No canonical end-to-end example ships yet. (Not available in the Motoko library — derive on a Rust canister.)
ic_vetkeys::management_canister::compute_vrf(input, context, key_id) -> VrfOutputinputcontextVrfOutput.deserialize(...)@icp-sdk/vetkeysvetKey 可以转换为可验证随机性:Rust canister 调用 (将 / 的范围限定到具体抽取场景,例如彩票轮次或领导者选举),前端则使用 中的 验证证明。目前尚无官方提供的完整端到端示例。(Motoko 库不支持此功能——请在 Rust canister 中派生。)
ic_vetkeys::management_canister::compute_vrf(input, context, key_id) -> VrfOutputinputcontext@icp-sdk/vetkeysVrfOutput.deserialize(...)Pitfalls
常见陷阱
-
Wrong package / imports. Use(≥0.7), not
@icp-sdk/vetkeys(frozen at 0.4). Import agent/identity from@dfinity/vetkeys(@icp-sdk/core,@icp-sdk/core/agent), and build the agent with@icp-sdk/core/principal— the client classes take a readyawait HttpAgent.create({ identity, host, rootKey }), not options. GetHttpAgentfromrootKey(safeGetCanisterEnv()); never call@icp-sdk/core/agent/canister-envin shipped code (see thefetchRootKey()skill).icp-cli -
does not exist. For symmetric encryption:
toDerivedKeyMaterial(), thenconst dkm = await vetKey.asDerivedKeyMaterial()/await dkm.encryptMessage(msg, domainSep, associatedData)(all async). Never use the raw decrypted vetKey bytes directly as an AES key.await dkm.decryptMessage(ct, domainSep, associatedData) -
Don't hand-roll the management interface. Rust:(
ic-cdk-management-canister/vetkd_public_key) orvetkd_derive_key(alsoic_vetkeys::management_canister). Motoko:sign_with_bls(mo:ic-vetkeys/ManagementCanister,vetKdPublicKey,vetKdDeriveKey,signWithBls). These carry the correct Candid types and attach the right cycles automatically. Hand-declaringblsPublicKeyand theactor "aaaaa-aa"records is unnecessary and error-prone.vetkd_* -
Motoko has no low-level crypto. No IBE, transport keys,/
MasterPublicKey, or vetKey decryption in the Motoko library. The Motoko canister returns the encrypted vetKey; the frontendDerivedPublicKey(or a Rust off-chain client) does the rest.@icp-sdk/vetkeys -
Fund the canister for derivations.costs cycles (
vetkd_derive_key= 26_153_846_153,key_1= 10_000_000_000 — the same locally and on mainnet);test_key_1is 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.vetkd_public_key -
and
contextmust match end to end. A differentinput(or a differentcontext) produces a different key;inputthen throws (the Rust APIs return an error) rather than returning wrong plaintext — handle it, and keepdecryptAndVerify/contextbyte-identical across public-key, derive, and client verify/decrypt.input -
is plaintext. It is a key identifier sent to the management canister — use IDs (principal, document ID), never secret data.
input -
Capture the caller before.
await(Rust) / destructureic_cdk::api::msg_caller()(Motoko) before the async derive call.({ caller }) -
Enforce authorization when hand-rolling derivation. If you calldirectly (not via
vetkd_derive_key/KeyManager), the canister must ensure it only derives for anEncryptedMapsthe caller is entitled to (e.g. their own principal). Otherwise any caller can obtain anyone's key.input -
BLS uses the unencrypted key. Use/
sign_with_bls; don't feed an encrypted vetKey into BLS, and don't reuse the samesignWithBls/contextacross IBE and BLS.input -
Rust randomness on Wasm. IBE seeds need randomness; add(or a
ic-dummy-getrandom-for-wasmwasm shim) or the canister traps. (The frontend uses WebCrypto — fine.)getrandom -
Modern ic-cdk call API. Use(not
ic_cdk::api::msg_caller()). If you ever call the management canister without the binding, useic_cdk::caller()— the legacyic_cdk::call::Call::unbounded_wait(..).with_cycles(..)API is removed in ic-cdk 0.20+.ic_cdk::api::call::call*
-
使用了错误的包或 import。 使用(≥0.7),不要使用
@icp-sdk/vetkeys(冻结在 0.4)。从@dfinity/vetkeys(@icp-sdk/core、@icp-sdk/core/agent)导入 agent/identity,并使用@icp-sdk/core/principal创建 agent——客户端类接收的是已经创建好的await HttpAgent.create({ identity, host, rootKey }),而不是选项对象。通过HttpAgent(safeGetCanisterEnv())获取@icp-sdk/core/agent/canister-env;在正式发布的代码中绝不调用rootKey(参见fetchRootKey()skill)。icp-cli -
不存在。 对于对称加密:使用
toDerivedKeyMaterial(),然后调用const dkm = await vetKey.asDerivedKeyMaterial()/await dkm.encryptMessage(msg, domainSep, associatedData)(均为异步操作)。绝不要将解密后的原始 vetKey 字节直接用作 AES 密钥。await dkm.decryptMessage(ct, domainSep, associatedData) -
不要自行实现管理接口。 Rust:使用(
ic-cdk-management-canister/vetkd_public_key)或vetkd_derive_key(也支持ic_vetkeys::management_canister)。Motoko:使用sign_with_bls(mo:ic-vetkeys/ManagementCanister、vetKdPublicKey、vetKdDeriveKey、signWithBls)。这些接口包含正确的 Candid 类型,并会自动附加所需 cycles。手动声明blsPublicKey和actor "aaaaa-aa"record 既没有必要,也容易出错。vetkd_* -
Motoko 不提供底层密码学原语。 Motoko 库中没有 IBE、transport key、/
MasterPublicKey或 vetKey 解密功能。Motoko canister 返回已加密的 vetKey;其余操作由前端DerivedPublicKey(或 Rust 链下客户端)完成。@icp-sdk/vetkeys -
为派生操作向 canister 充值。会消耗 cycles(
vetkd_derive_key= 26_153_846_153,key_1= 10_000_000_000——local 与 mainnet 上相同);test_key_1免费。让辅助函数附加所需金额——Rust binding 会计算精确成本,Motoko 辅助函数会附加 26_153_846_153,多余部分将退还——并确保 canister 始终有充足资金。vetkd_public_key -
和
context必须端到端一致。 不同的input(或不同的context)会产生不同的密钥;随后input将抛出异常(Rust API 会返回错误),而不是返回错误的明文。请处理此情况,并确保公钥、派生和客户端验证/解密流程中的decryptAndVerify/context字节完全一致。input -
是明文。 它是发送给管理 canister 的密钥标识符——请使用 ID(principal、文档 ID),绝不要用于机密数据。
input -
在之前捕获调用方。 在异步派生调用之前调用
await(Rust),或在 Motoko 中解构ic_cdk::api::msg_caller()。({ caller }) -
自行实现派生逻辑时必须执行授权检查。 如果直接调用(而不是通过
vetkd_derive_key/KeyManager),canister 必须确保只能为调用方有权访问的EncryptedMaps派生密钥(例如其自己的 principal)。否则任何调用方都能获取他人的密钥。input -
BLS 使用未加密的密钥。 使用/
sign_with_bls;不要将加密的 vetKey 传入 BLS,也不要在 IBE 和 BLS 之间复用相同的signWithBls/context。input -
Wasm 上的 Rust 随机性。 IBE seed 需要随机性;请添加(或
ic-dummy-getrandom-for-wasmwasm shim),否则 canister 会触发 trap。(前端使用 WebCrypto——没有问题。)getrandom -
现代 ic-cdk 调用 API。 使用(不要使用
ic_cdk::api::msg_caller())。如果必须在没有 binding 的情况下调用管理 canister,请使用ic_cdk::caller()——旧的ic_cdk::call::Call::unbounded_wait(..).with_cycles(..)API 已从 ic-cdk 0.20+ 中移除。ic_cdk::api::call::call*
Feature guides
功能指南
- Identity-Based Encryption (IBE) & timelock — encrypt with ; the recipient decrypts with
IbeCiphertext.encrypt(publicKey, IbeIdentity.fromPrincipal(recipient), plaintext, IbeSeed.random()). Full backend + frontend + timelock:IbeCiphertext.deserialize(ct).decrypt(vetKey).references/ibe.md - Threshold BLS signatures — sign with (Rust) /
ic_vetkeys::management_canister::sign_with_bls(Motoko); verify withManagementCanister.signWithBls. Details:verifyBlsSignature(derivedPublicKey, message, signature).references/bls-signing.md - Encrypted key-value storage (EncryptedMaps / KeyManager) — the skill.
encrypted-maps
- 基于身份的加密(IBE)与时间锁——使用 加密;接收方使用
IbeCiphertext.encrypt(publicKey, IbeIdentity.fromPrincipal(recipient), plaintext, IbeSeed.random())解密。完整后端、前端和时间锁实现:IbeCiphertext.deserialize(ct).decrypt(vetKey)。references/ibe.md - 阈值 BLS 签名——使用 (Rust)/
ic_vetkeys::management_canister::sign_with_bls(Motoko)签名;使用ManagementCanister.signWithBls验证。详情参见verifyBlsSignature(derivedPublicKey, message, signature)。references/bls-signing.md - 加密键值存储(EncryptedMaps / KeyManager)——使用 skill。
encrypted-maps
Deploy & verify
部署与验证
Provisioning, , and generic deploy steps belong to the skill. vetKeys-specific checks:
icp.yamlicp-clibash
icp deploy backend # local replica provisions test_key_1
icp canister call backend symmetric_verification_key '()' # non-empty BLS public-key blob资源配置、 和通用部署步骤属于 skill。vetKeys 专属检查如下:
icp.yamlicp-clibash
icp deploy backend # local replica provisions test_key_1
icp canister call backend symmetric_verification_key '()' # non-empty BLS public-key blobderive 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
undefinedundefined