Introduction to Keytar
Keytar is a Node.js module that allows you to store and retrieve secure credentials natively using the operating system’s keychain. This utility can be very useful for applications that need to securely manage passwords or tokens.
Getting Started with Keytar
First, you’ll need to install Keytar:
npm install keytar
Keytar API Examples
Here are some examples of how to use the Keytar APIs:
Storing a Password
const keytar = require('keytar');
async function storePassword() {
await keytar.setPassword('myService', 'myAccount', 'myPassword');
console.log('Password stored successfully.');
}
storePassword();
Retrieving a Password
async function getPassword() {
const password = await keytar.getPassword('myService', 'myAccount');
console.log(`Password retrieved: ${password}`);
}
getPassword();
Deleting a Password
async function deletePassword() {
await keytar.deletePassword('myService', 'myAccount');
console.log('Password deleted successfully.');
}
deletePassword();
Finding Credentials
async function findCredentials() {
const credentials = await keytar.findCredentials('myService');
credentials.forEach(cred => {
console.log(`Account: ${cred.account}, Password: ${cred.password}`);
});
}
findCredentials();
Listing All Stored Passwords
async function findPassword() {
const password = await keytar.findPassword('myService');
console.log(`Password found: ${password}`);
}
findPassword();
Example Application Using Keytar
Here is an example of a simple Node.js application that utilizes Keytar for secure password management:
const keytar = require('keytar');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
async function main() {
rl.question('Enter service name: ', service => {
rl.question('Enter account name: ', account => {
rl.question('Enter password: ', async password => {
await keytar.setPassword(service, account, password);
console.log('Password stored successfully.');
const storedPassword = await keytar.getPassword(service, account);
console.log(`Retrieved password: ${storedPassword}`);
rl.close();
});
});
});
}
main();
Hash: ca7f357f842c49aeae75282d1117181496704e4b2009d69b1a6faf4f6078acca