encrypted-maps
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseEncrypted Maps (vetKeys)
Encrypted Maps (vetKeys)
EncryptedMapsmapKey → valueUse the skill instead when you need lower-level primitives: identity-based encryption (IBE), threshold BLS signatures, timelock encryption, or your own symmetric-key scheme.
vetkeys| Layer | Rust | Motoko | Frontend |
|---|---|---|---|
| Package | | | |
| Backend | | | |
Use(≥0.7), not the legacy@icp-sdk/vetkeys(frozen at 0.4). 0.5 and 0.6 carried@dfinity/vetkeysas a plain dependency and could nest a second copy of it; 0.7 peers it as@icp-sdk/core, with an identical API. Frontend agent/identity come from^5 || ^6, not@icp-sdk/core.@dfinity/agent
EncryptedMapsmapKey → value当你需要更底层的原语时,请改用 skill:identity-based encryption(IBE)、threshold BLS signatures、timelock encryption,或你自己的 symmetric-key scheme。
vetkeys| 层级 | Rust | Motoko | 前端 |
|---|---|---|---|
| 包 | | | |
| 后端 | | | |
使用(≥0.7),不要使用冻结在 0.4 的旧版@icp-sdk/vetkeys。0.5 和 0.6 将@dfinity/vetkeys作为普通依赖项引入,因此可能会嵌套第二份副本;0.7 使用@icp-sdk/core将其作为 peer dependency,且 API 保持不变。前端 agent/identity 来自^5 || ^6,而不是@icp-sdk/core。@dfinity/agent
Concepts
概念
- Map — identified by . Contains
(mapOwner: Principal, mapName: bytes)entries.mapKey → encryptedValueandmapNameare byte arrays, max 32 bytes each.mapKey - Access rights — ,
Read,ReadWrite(manage = may grant/revoke others). The owner always has full rights.ReadWriteManage - Client-side encryption — the frontend fetches a per-map vetKey and encrypts/decrypts locally; the canister enforces access control and stores ciphertext. Sharing a map re-encrypts the map key for the new user automatically.
- Key name & domain separator are immutable once any value is encrypted — they feed key derivation, so changing them makes stored values undecryptable. See pitfalls.
- Map — 通过 标识。包含
(mapOwner: Principal, mapName: bytes)条目。mapKey → encryptedValue和mapName均为字节数组,每个最长 32 字节。mapKey - Access rights — 、
Read、ReadWrite(manage 表示可以授予或撤销他人的权限)。所有者始终拥有完整权限。ReadWriteManage - 客户端加密 — 前端获取每个 map 对应的 vetKey,并在本地进行加密和解密;canister 负责强制执行访问控制并存储密文。共享 map 时,会自动为新用户重新加密 map key。
- 一旦有任何值被加密,密钥名称与 domain separator 就不可更改 — 二者都会参与密钥派生,因此更改它们会导致已存储的值无法解密。请参阅常见问题。
Backend — the whole canister in a few lines
后端——几行代码构建整个 canister
The generator emits the /, the stable state, and every endpoint the frontend expects — so the Candid matches the client by construction. Do not hand-write the ~200 lines of delegation.
#[init]#[post_upgrade]@icp-sdk/vetkeys生成器会生成 /、稳定状态,以及 前端所期望的所有 endpoint,因此从结构上保证 Candid 与客户端一致。不要手写约 200 行的 delegation 代码。
#[init]#[post_upgrade]@icp-sdk/vetkeysRust — export_encrypted_maps_canister!
export_encrypted_maps_canister!Rust — export_encrypted_maps_canister!
export_encrypted_maps_canister!rust
use ic_stable_structures::memory_manager::{MemoryId, MemoryManager, VirtualMemory};
use ic_stable_structures::DefaultMemoryImpl;
use std::cell::RefCell;
type Memory = VirtualMemory<DefaultMemoryImpl>;
thread_local! {
static MEMORY_MANAGER: RefCell<MemoryManager<DefaultMemoryImpl>> =
RefCell::new(MemoryManager::init(DefaultMemoryImpl::default()));
}
fn memory(id: u8) -> Memory {
MEMORY_MANAGER.with(|m| m.borrow().get(MemoryId::new(id)))
}
// Arg 1: the domain separator that isolates this app's derived keys (keep it
// stable forever). Then four Memory instances, in order: domain-separator config,
// access control, shared keys, encrypted values.
ic_vetkeys::export_encrypted_maps_canister!(
"password_manager_app",
[memory(0), memory(1), memory(2), memory(3)],
);
ic_cdk::export_candid!();The generated takes the vetKD key name ( / ) as a argument — pass it via in .
#[init]test_key_1key_1Stringinit_argsicp.yamlrust
use ic_stable_structures::memory_manager::{MemoryId, MemoryManager, VirtualMemory};
use ic_stable_structures::DefaultMemoryImpl;
use std::cell::RefCell;
type Memory = VirtualMemory<DefaultMemoryImpl>;
thread_local! {
static MEMORY_MANAGER: RefCell<MemoryManager<DefaultMemoryImpl>> =
RefCell::new(MemoryManager::init(DefaultMemoryImpl::default()));
}
fn memory(id: u8) -> Memory {
MEMORY_MANAGER.with(|m| m.borrow().get(MemoryId::new(id)))
}
// Arg 1: the domain separator that isolates this app's derived keys (keep it
// stable forever). Then four Memory instances, in order: domain-separator config,
// access control, shared keys, encrypted values.
ic_vetkeys::export_encrypted_maps_canister!(
"password_manager_app",
[memory(0), memory(1), memory(2), memory(3)],
);
ic_cdk::export_candid!();生成的 接受 vetKD 密钥名称( / )作为 参数——请通过 中的 传入。
#[init]test_key_1key_1Stringicp.yamlinit_argsMotoko — EncryptedMapsCanister
mixin
EncryptedMapsCanisterMotoko — EncryptedMapsCanister
mixin
EncryptedMapsCanistermotoko
import EncryptedMapsCanister "mo:ic-vetkeys/encrypted_maps/Canister";
import EncryptedMaps "mo:ic-vetkeys/encrypted_maps/EncryptedMaps";
import Types "mo:ic-vetkeys/Types";
import Runtime "mo:core/Runtime";
persistent actor PasswordManager {
// `transient`: the key name is baked into `encryptedMapsState` at install and never re-read.
transient let keyName = Runtime.envVar<system>("VETKD_KEY_NAME") ?? "test_key_1";
// Arg 2 is the domain separator; like the key name it must stay stable for the life of the canister.
let encryptedMapsState = EncryptedMaps.newEncryptedMapsState<Types.AccessRights>(
{ curve = #bls12_381_g2; name = keyName },
"password_manager_app",
);
// The mixin contributes the full endpoint set (vetKD key, access control, map-name, value endpoints)
// as snake_case methods, exactly what the frontend client calls.
include EncryptedMapsCanister(encryptedMapsState);
};In a the binding is stable and persists across upgrades with no keyword; the actor owns it, so it stays a plain, migratable variable. Set at deploy time via canister settings (see the skill).
persistent actorencryptedMapsStatestableVETKD_KEY_NAMEicp-climotoko
import EncryptedMapsCanister "mo:ic-vetkeys/encrypted_maps/Canister";
import EncryptedMaps "mo:ic-vetkeys/encrypted_maps/EncryptedMaps";
import Types "mo:ic-vetkeys/Types";
import Runtime "mo:core/Runtime";
persistent actor PasswordManager {
// `transient`: the key name is baked into `encryptedMapsState` at install and never re-read.
transient let keyName = Runtime.envVar<system>("VETKD_KEY_NAME") ?? "test_key_1";
// Arg 2 is the domain separator; like the key name it must stay stable for the life of the canister.
let encryptedMapsState = EncryptedMaps.newEncryptedMapsState<Types.AccessRights>(
{ curve = #bls12_381_g2; name = keyName },
"password_manager_app",
);
// The mixin contributes the full endpoint set (vetKD key, access control, map-name, value endpoints)
// as snake_case methods, exactly what the frontend client calls.
include EncryptedMapsCanister(encryptedMapsState);
};在 中, 绑定是稳定的,升级后无需使用 关键字即可持久化;actor 拥有它,因此它仍是普通且可迁移的变量。部署时通过 canister 设置配置 (请参阅 skill)。
persistent actorencryptedMapsStatestableVETKD_KEY_NAMEicp-cliFrontend (TypeScript)
前端(TypeScript)
typescript
import { HttpAgent, type Identity } from "@icp-sdk/core/agent";
import { safeGetCanisterEnv } from "@icp-sdk/core/agent/canister-env";
import {
DefaultEncryptedMapsClient,
EncryptedMaps,
IndexedDbDerivedKeyMaterialCache,
type AccessRights,
} from "@icp-sdk/vetkeys/encrypted_maps";
export async function createEncryptedMaps(
identity: Identity, canisterId: string, host: string,
): Promise<EncryptedMaps> {
// rootKey from the canister env (never fetchRootKey() in shipped code); undefined on mainnet
const rootKey = safeGetCanisterEnv()?.IC_ROOT_KEY;
const agent = await HttpAgent.create({ identity, host, rootKey });
// Since 0.5.0 derived key material is cached in memory only by default.
// Opt into cross-reload persistence, namespaced by principal; clearCache() on logout.
const cache = new IndexedDbDerivedKeyMaterialCache(`vetkeys-${identity.getPrincipal().toText()}`);
return new EncryptedMaps(new DefaultEncryptedMapsClient(agent, canisterId), { cache });
}typescript
const owner = myPrincipal; // Principal from @icp-sdk/core/principal
const mapName = new TextEncoder().encode("my-vault"); // ≤ 32 bytes
const mapKey = new TextEncoder().encode("github.com"); // ≤ 32 bytes
// Store / read / remove (encryption happens client-side)
await encryptedMaps.setValue(owner, mapName, mapKey, new TextEncoder().encode("s3cr3t"));
const value = await encryptedMaps.getValue(owner, mapName, mapKey); // Uint8Array (empty if absent)
await encryptedMaps.removeEncryptedValue(owner, mapName, mapKey);
// Share the map with another principal (AccessRights is a Candid variant, not a string)
const rights: AccessRights = { ReadWrite: null }; // or { Read: null } / { ReadWriteManage: null }
await encryptedMaps.setUserRights(owner, mapName, otherPrincipal, rights);
const theirRights = await encryptedMaps.getUserRights(owner, mapName, otherPrincipal);
// Everything the caller can access (owned + shared)
const maps = await encryptedMaps.getAllAccessibleMaps();
await encryptedMaps.clearCache(); // on logout / identity switchtypescript
import { HttpAgent, type Identity } from "@icp-sdk/core/agent";
import { safeGetCanisterEnv } from "@icp-sdk/core/agent/canister-env";
import {
DefaultEncryptedMapsClient,
EncryptedMaps,
IndexedDbDerivedKeyMaterialCache,
type AccessRights,
} from "@icp-sdk/vetkeys/encrypted_maps";
export async function createEncryptedMaps(
identity: Identity, canisterId: string, host: string,
): Promise<EncryptedMaps> {
// rootKey from the canister env (never fetchRootKey() in shipped code); undefined on mainnet
const rootKey = safeGetCanisterEnv()?.IC_ROOT_KEY;
const agent = await HttpAgent.create({ identity, host, rootKey });
// Since 0.5.0 derived key material is cached in memory only by default.
// Opt into cross-reload persistence, namespaced by principal; clearCache() on logout.
const cache = new IndexedDbDerivedKeyMaterialCache(`vetkeys-${identity.getPrincipal().toText()}`);
return new EncryptedMaps(new DefaultEncryptedMapsClient(agent, canisterId), { cache });
}typescript
const owner = myPrincipal; // Principal from @icp-sdk/core/principal
const mapName = new TextEncoder().encode("my-vault"); // ≤ 32 bytes
const mapKey = new TextEncoder().encode("github.com"); // ≤ 32 bytes
// Store / read / remove (encryption happens client-side)
await encryptedMaps.setValue(owner, mapName, mapKey, new TextEncoder().encode("s3cr3t"));
const value = await encryptedMaps.getValue(owner, mapName, mapKey); // Uint8Array (empty if absent)
await encryptedMaps.removeEncryptedValue(owner, mapName, mapKey);
// Share the map with another principal (AccessRights is a Candid variant, not a string)
const rights: AccessRights = { ReadWrite: null }; // or { Read: null } / { ReadWriteManage: null }
await encryptedMaps.setUserRights(owner, mapName, otherPrincipal, rights);
const theirRights = await encryptedMaps.getUserRights(owner, mapName, otherPrincipal);
// Everything the caller can access (owned + shared)
const maps = await encryptedMaps.getAllAccessibleMaps();
await encryptedMaps.clearCache(); // on logout / identity switchKeyManager — the layer beneath (use only when EncryptedMaps doesn't fit)
KeyManager——底层能力(仅在 EncryptedMaps 不适用时使用)
EncryptedMapsKeyManagerKeyManagerEncryptedMapsCaveat: there is no ready-made canister generator for KeyManager yet (dfinity/vetkeys#422) — unlike EncryptedMaps, you wire the endpoints by hand. In Rust, takes the domain separator, the , and three instances (config, access control, shared keys), and exposes , , , , . Motoko mirrors this via + the class; the frontend uses ( + ).
ic_vetkeys::key_manager::KeyManager::initVetKDKeyIdMemoryget_vetkey_verification_keyget_encrypted_vetkeyget_user_rightsset_user_rightsremove_userKeyManager.newKeyManagerStateKeyManager@icp-sdk/vetkeys/key_managerKeyManagerDefaultKeyManagerClientEncryptedMapsKeyManagerKeyManagerEncryptedMaps注意:目前尚未提供适用于 KeyManager 的现成 canister 生成器(dfinity/vetkeys#422)——与 EncryptedMaps 不同,你需要手动连接各个 endpoint。在 Rust 中, 接受 domain separator、 和三个 实例(配置、访问控制、共享密钥),并公开 、、、、。Motoko 通过 和 class 提供对应能力;前端使用 ( 与 )。
ic_vetkeys::key_manager::KeyManager::initVETKDKeyIdMemoryget_vetkey_verification_keyget_encrypted_vetkeyget_user_rightsset_user_rightsremove_userKeyManager.newKeyManagerStateKeyManager@icp-sdk/vetkeys/key_managerKeyManagerDefaultKeyManagerClientPitfalls
常见问题
-
Use the generator, don't hand-write endpoints. Rust, Motoko
export_encrypted_maps_canister!. Hand-written delegation drifts from the Candid the frontend client expects and breaks silently.include EncryptedMapsCanister(state) -
Domain separator and vetKD key name are immutable once data exists. Both feed key derivation; changing either makes every stored value undecryptable. In Motoko theenv var is captured into stable state at first install — editing it on a later upgrade is silently ignored (only a
VETKD_KEY_NAME, which drops all data, 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.VETKD_KEY_NAME -
Derived key material is in-memory by default since 0.5.0 (was IndexedDB). Passto persist it across reloads, and call
IndexedDbDerivedKeyMaterialCacheon logout / identity change. OldclearCache()0.1–0.4 IndexedDB entries remain at rest after upgrading — clear them once.@dfinity/vetkeys -
Client construction changed.takes a ready
DefaultEncryptedMapsClient(HttpAgent), notawait HttpAgent.create({ identity, host, rootKey }). Agent/identity come fromHttpAgentOptions.@icp-sdk/core -
is a Candid variant, not a string —
AccessRights, not{ ReadWrite: null }. Three levels:"ReadWrite",Read,ReadWrite.ReadWriteManage -
and
mapNameare byte arrays, ≤ 32 bytes each — encode strings withmapKey.TextEncoder -
Keep per-value app state consistent via the control-plane variant. If you store metadata alongside each value, use(Rust) /
custom_value_endpoints(Motoko) and own the value endpoints — seeEncryptedMapsControlPlaneCanister. Don't also expose the library's raw value mutators, or the two stores desync.references/metadata.md -
Don't re-init state on upgrade. The macro/mixin generate the lifecycle hooks; stable memory survives upgrades. Adding your ownthat rebuilds state corrupts it.
post_upgrade -
Cycles.(used under the hood) costs cycles —
vetkd_derive_keyandtest_key_1cost the same locally and on mainnet, and the library attaches the right amount (excess refunded). Keep the canister funded. (See thekey_1skill for the cost table.)vetkeys
-
使用生成器,不要手写 endpoint。 Rust 使用,Motoko 使用
export_encrypted_maps_canister!。手写 delegation 会逐渐偏离前端客户端所期望的 Candid,并且会在悄无声息中导致故障。include EncryptedMapsCanister(state) -
一旦已有数据,domain separator 和 vetKD 密钥名称便不可更改。 二者都会参与密钥派生;更改任意一个都会导致所有已存储的值无法解密。在 Motoko 中,环境变量会在首次安装时被捕获到稳定状态中——后续升级时修改它会被静默忽略(只有
VETKD_KEY_NAME才会切换密钥,而这会删除所有数据)。由于reinstall同时也是有效的主网密钥,生产环境部署时若忘记设置test_key_1,就会悄无声息地使用它运行——请在部署时断言预期的密钥。VETKD_KEY_NAME -
从 0.5.0 开始,派生密钥材料默认仅缓存在内存中(此前使用 IndexedDB)。传入以在页面重新加载后继续持久化,并在退出登录或切换 identity 时调用
IndexedDbDerivedKeyMaterialCache。升级后,旧的clearCache()0.1–0.4 IndexedDB 条目仍会保留在磁盘上——请一次性清除。@dfinity/vetkeys -
客户端构造方式已经改变。接受已创建的
DefaultEncryptedMapsClient(HttpAgent),而不是await HttpAgent.create({ identity, host, rootKey })。Agent/identity 来自HttpAgentOptions。@icp-sdk/core -
是 Candid variant,而不是字符串——应使用
AccessRights,而不是{ ReadWrite: null }。共有三个级别:"ReadWrite"、Read、ReadWrite。ReadWriteManage -
和
mapName是字节数组,每个最长 32 字节——请使用mapKey编码字符串。TextEncoder -
通过 control-plane 变体保持每个值的应用状态一致。 如果要在每个值旁存储元数据,请使用(Rust)或
custom_value_endpoints(Motoko),并自行实现 value endpoints——请参阅EncryptedMapsControlPlaneCanister。不要同时暴露库原生的 value mutators,否则两个存储区会失去同步。references/metadata.md -
升级时不要重新初始化状态。 宏或 mixin 会生成生命周期 hooks,稳定内存会在升级后继续保留。添加自己的并重新构建状态会破坏已有状态。
post_upgrade -
Cycles。 底层使用的会消耗 cycles——
vetkd_derive_key和test_key_1在本地及主网上的成本相同,库会附加正确的 cycles 数量(超出部分会退还)。请确保 canister 拥有充足资金。(费用表请参阅key_1skill。)vetkeys
Additional References
其他参考
- Metadata / custom value endpoints:
references/metadata.md - Lower-level vetKeys (IBE, BLS, timelock, symmetric, offline derivation): the skill
vetkeys - Canonical examples: ,
motoko/vetkeys/password_managerin dfinity/examplesrust/vetkeys/password_manager
- 元数据/自定义 value endpoints:
references/metadata.md - 更底层的 vetKeys(IBE、BLS、timelock、对称加密、离线派生):skill
vetkeys - 规范示例:dfinity/examples 中的 、
motoko/vetkeys/password_managerrust/vetkeys/password_manager
Deploy & verify
部署与验证
Provisioning and generic deploy steps belong to the skill. EncryptedMaps-specific checks:
icp-clibash
icp deploy backend # local replica provisions test_key_1资源准备和通用部署步骤属于 skill。EncryptedMaps 专属检查如下:
icp-clibash
icp deploy backend # local replica provisions test_key_1From the frontend: setValue then getValue round-trips the plaintext for the owner;
From the frontend: setValue then getValue round-trips the plaintext for the owner;
a principal without rights gets an access-control error on getValue.
a principal without rights gets an access-control error on getValue.
undefinedundefined