web3.js离线生成帐户 / 学习智能合约#50

in hive-180932 •  3 years ago 

前面尝试过用ether.js来生成帐户,但平时开发不是很常用这个库,所以想换成web3.js来试试。

总体来说,web3.js在以太坊帐户方面不是很全面,比如助记词生成这个功能就没有。还有就是有些keystore解密时会出现一些错误,努力排查很久也不知原因何在。但用ether.js时却又完全没问题!到此,对比之下,在帐户这方面还是尽量用ether.js较好。

//nodejs
const Web3 = require('web3')
const fs = require('fs')

let web3 = new Web3(Web3.givenProvider) //如果只是使用web3的方法可以使用此方法

//创建账号
web3.eth.accounts.create([entropy])

//获取私钥
// let account = web3.eth.accounts.create()
let account = web3.eth.accounts.create(web3.utils.randomHex(32))
let privateKey = account.privateKey

//获取keystore方法一, 将私钥加密到keystore文件中。
let account = web3.eth.accounts.create(web3.utils.randomHex(32))
let privateKey = account.privateKey
let keystore = web3.eth.accounts.encrypt(privateKey, password)
eg:
let password = "jiangxxx"
let account = web3.eth.accounts.create(web3.utils.randomHex(32))
let privateKey = account.privateKey
let keystore = web3.eth.accounts.encrypt(privateKey, password)
// console.log(56, account, keystore)
let d = new Date()
let time = d.getTime()
let path = './keystore/' + time + '-' + account.address
fs.writeFileSync(path, JSON.stringify(keystore))

//获取keystore方法二
let account = web3.eth.accounts.create(password)
let keystore = account.encrypt(password)


//解密keystore
let res = fs.readFileSync('./1633xxxx', "utf8")
let password = "jiangxxxx"
let wallet = web3.eth.accounts.decrypt(res, password)
console.log(56, wallet)

// web3.eth.accounts.encrypt(privateKey, password);
// web3.eth.accounts.decrypt(keystoreJsonV3, password);
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!