Flutter 区块链开发android技术

Flutter 使用助记词,私钥,keystore生成钱包地址

2021-12-27  本文已影响0人  职场过客

首先是引入依赖:

web3dart: ^1.2.0
 json_rpc_2: any
 bip39: ^1.0.0
 bip32: ^1.0.3

具体flutter代码使用

import 'package:bip39/bip39.dart' as bip39;
import 'package:bip32/bip32.dart' as bip32;
import 'package:web3dart/crypto.dart';

//导入助记词
 Future<void> importMnemonic(String mnemonic, String walletname, String password) async {
    print('助记词====      ' + mnemonic);
    String seed = bip39.mnemonicToSeedHex(mnemonic);
    print('seed====    ' + seed);
    var root = bip32.BIP32.fromSeed(hex.decode(seed));
    var child = root.derivePath("m/44'/60'/0'/0/0");
    String privateKey = '0x' + hex.encode(child.privateKey);
    print("私钥:" + privateKey);
    // String privateKey ='0x'+ bytesToHex(child.privateKey);
    // print("公钥:" + bytesToHex(child1.publicKey));
    Credentials credentials = EthPrivateKey.fromHex(privateKey);
    EthereumAddress address = await credentials.extractAddress();
    String mAddress = address.hexEip55;
    print("地址   ====   " + mAddress);
    var random = Random();
    Wallet wallet = Wallet.createNew(credentials, password, random);
    String keystore = wallet.toJson();
    print("keystore==== " + keystore);

  }

  //导入keystore
  Future<void> importKetystore(String keystore, String walletname, String password) async {
    print('解析keystore====     ' + keystore);
    Wallet wallet = Wallet.fromJson(keystore, password);
    EthereumAddress address = await wallet.privateKey.extractAddress();
    String mAddress = address.hexEip55;
    print("地址   ====   " + mAddress);
    String privateKey = bytesToHex(wallet.privateKey.privateKey);
    print("私钥====     " + privateKey);
  }

  //导入私钥
  Future<void> importPrivate( String mprivate, String walletname, String password) async {
    print('私钥====     ' + mprivate);
    Credentials credentials = EthPrivateKey.fromHex(mprivate);
    EthereumAddress address = await credentials.extractAddress();
    String mAddress = address.hexEip55;
    print("地址   ====   " + mAddress);
    var random = new Random.secure();
    Wallet wallet = Wallet.createNew(credentials, password, random);
    String keystore = wallet.toJson();
    print("keystore====     " + keystore);
  }

这个方法已通过https://iancoleman.io/bip39/#english和小狐狸验证,可以相互导入验证

上一篇下一篇

猜你喜欢

热点阅读