Loading...
Loading...
Add access-controlled, end-to-end encrypted key-value storage to a canister with the vetKeys EncryptedMaps library (ic-vetkeys for Rust and Motoko backends, @icp-sdk/vetkeys for the frontend). Values are encrypted client-side under vetKeys and shared between principals with per-user access rights (Read, ReadWrite, ReadWriteManage). Use when building a password manager, encrypted notes, a secure vault, or any app that stores and shares encrypted data on-chain. Start here for encrypted storage; escalate to the vetkeys skill only for BLS signatures, custom IBE, or timelock encryption.
npx skill4agent add dfinity/icskills encrypted-mapsEncryptedMapsmapKey → valuevetkeys| 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
(mapOwner: Principal, mapName: bytes)mapKey → encryptedValuemapNamemapKeyReadReadWriteReadWriteManage#[init]#[post_upgrade]@icp-sdk/vetkeysexport_encrypted_maps_canister!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!();#[init]test_key_1key_1Stringinit_argsicp.yamlEncryptedMapsCanisterimport 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);
};persistent actorencryptedMapsStatestableVETKD_KEY_NAMEicp-cliimport { 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 });
}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 switchEncryptedMapsKeyManagerKeyManagerEncryptedMapsic_vetkeys::key_manager::KeyManager::initVetKDKeyIdMemoryget_vetkey_verification_keyget_encrypted_vetkeyget_user_rightsset_user_rightsremove_userKeyManager.newKeyManagerStateKeyManager@icp-sdk/vetkeys/key_managerKeyManagerDefaultKeyManagerClientexport_encrypted_maps_canister!include EncryptedMapsCanister(state)VETKD_KEY_NAMEreinstalltest_key_1VETKD_KEY_NAMEIndexedDbDerivedKeyMaterialCacheclearCache()@dfinity/vetkeysDefaultEncryptedMapsClientHttpAgentawait HttpAgent.create({ identity, host, rootKey })HttpAgentOptions@icp-sdk/coreAccessRights{ ReadWrite: null }"ReadWrite"ReadReadWriteReadWriteManagemapNamemapKeyTextEncodercustom_value_endpointsEncryptedMapsControlPlaneCanisterreferences/metadata.mdpost_upgradevetkd_derive_keytest_key_1key_1vetkeysreferences/metadata.mdvetkeysmotoko/vetkeys/password_managerrust/vetkeys/password_managericp-cliicp deploy backend # local replica provisions test_key_1
# From the frontend: setValue then getValue round-trips the plaintext for the owner;
# a principal without rights gets an access-control error on getValue.