wallet-import.js - Import Keys to Wallet


How to write a Node.js script to Import Keys to Wallet?

✍: FYIcenter.com


After enroll (sign in) to ca.example.com, you will receive your private key and a certificate of your public key. You can save import them into a local wallet.

Here is sample Node.js script, wallet-import.js, that enrolls (signs in) to ca.example.com to retrieve your key and certificate. Then import them to local wallet.

/* Copyright (c) FYIcenter.com
'use strict';
const FabricCAServices = require('fabric-ca-client');
const { FileSystemWallet, X509WalletMixin } = require('fabric-network');

// Build the connection setting object
const fs = require('fs');
const ccp = JSON.parse(fs.readFileSync("connection.json", 'utf8'));

// Get user name and password from the command line
const user = process.argv[2];
const pass = process.argv[3];

async function main() {
   try {
      // Create a new CA client for interacting with the CA.
      const caURL = ccp.certificateAuthorities['ca.example.com'].url;
      const ca = new FabricCAServices(caURL);

      // Enroll the user
      const enrollment = await ca.enroll({ enrollmentID: user, enrollmentSecret: pass });
      // Open local wallet
      const wallet = new FileSystemWallet('wallet');

      // Remove old keys
      if (await wallet.exists(user)) {
         await wallet.delete(user);
      // Import new keys to wallet
      const identity = X509WalletMixin.createIdentity('Org1MSP', 
      enrollment.certificate, enrollment.key.toBytes());
      wallet.import(user, identity);

      console.log("User (%s) keys imported!", user);
   } catch (error) {
      console.error(`Something wrong: ${error}`); 


Like the last tutorial, to run this application script on your client system, you need to make sure that the WYFA (Write Your First Application) network is up and running on your server system. And you have a copy of the connection.json file, which contains addresses and port number of the WYFA network services.

Try with the default admin user and password pre-defined in the WYFA network:

$ cp ../../basic-network/connection.json .

$ node wallet-import.js admin adminpw
User (admin) keys imported!

Verify the local wallet:

$ ls -l wallet/admin/
-rw-rw-r-- 1 fyicenter 246 Apr  1 00:23 8f6d525de06bc7024c71f0cb608fc4b33459...-priv
-rw-rw-r-- 1 fyicenter 182 Apr  1 00:23 8f6d525de06bc7024c71f0cb608fc4b33459...-pub
-rw-rw-r-- 1 fyicenter 986 Apr  1 00:23 admin


register-user.js - Register New User

.js - Sign in to CA Server

Interfaces to Communicate with Ledger Peer

⇑⇑ Hyperledger Tutorials

2019-04-22, 1505🔥, 0💬