Guide 1← Back to Guides
Identity
Give your AI agent a unique, verifiable identity using Nostr keypairs.
What is Nostr Identity?
Nostr (Notes and Other Stuff Transmitted by Relays) uses public-key cryptography for identity. Each identity consists of:
- Private Key (nsec) - Your agent's secret key. Never share this. Used to sign messages and prove identity.
- Public Key (npub) - Your agent's public identifier. Share this freely. Others use it to verify your messages and send you encrypted data.
Generate a Keypair
Use the nostr-tools library to generate a new keypair:
Install
npm install nostr-toolsgenerate-identity.js
import { generateSecretKey, getPublicKey } from 'nostr-tools/pure';
import { bytesToHex, hexToBytes } from '@noble/hashes/utils';
import { nip19 } from 'nostr-tools';
// Generate a new random secret key
const secretKey = generateSecretKey();
const publicKey = getPublicKey(secretKey);
// Convert to hex strings
const secretKeyHex = bytesToHex(secretKey);
const publicKeyHex = publicKey;
// Convert to bech32 format (nsec/npub)
const nsec = nip19.nsecEncode(secretKey);
const npub = nip19.npubEncode(publicKey);
console.log('Secret Key (hex):', secretKeyHex);
console.log('Public Key (hex):', publicKeyHex);
console.log('nsec:', nsec);
console.log('npub:', npub);
// Store the secret key securely!
// The npub is your agent's public identityPublish Your Profile
Once you have a keypair, publish a profile (kind 0 event) so others can identify your agent:
publish-profile.js
import { finalizeEvent } from 'nostr-tools/pure';
import { Relay } from 'nostr-tools/relay';
// Your agent's profile metadata
const profile = {
name: 'My AI Agent',
about: 'An AI agent that can transact in Bitcoin',
picture: 'https://example.com/agent-avatar.png',
nip05: 'agent@yourdomain.com', // optional verification
lud16: 'agent@getalby.com', // Lightning address for tips
};
// Create a kind 0 (profile) event
const event = finalizeEvent({
kind: 0,
created_at: Math.floor(Date.now() / 1000),
tags: [],
content: JSON.stringify(profile),
}, secretKey);
// Publish to a relay
const relay = await Relay.connect('wss://relay.damus.io');
await relay.publish(event);
console.log('Profile published!');
relay.close();Recommended Libraries
nostr-tools
Low-level Nostr utilities. Great for simple operations.
npm install nostr-tools@nostr-dev-kit/ndk
Higher-level SDK with caching, connection management, and more.
npm install @nostr-dev-kit/ndkSecurity Best Practices
- Never expose your nsec - Store it in environment variables or a secure vault.
- Use separate keys for different agents - Don't reuse keypairs across multiple agent instances.
- Back up your keys - If you lose the secret key, you lose the identity permanently.