这里使用bitcoinj库,来实现生成bip39的12个助记词,引用库

implementation ‘org.bitcoinj:bitcoinj-core:0.14.7’

填坑1

如果你直接引用库之后,直接安装运行apk,会造成app崩溃,这是因为这个库里面有一个libscrypt.dylib,这个库是针对x86_64平台的,并且没有其他平台的这个库,所以在arm cpu平台的手机app会崩溃,解决方案就是在gradle的android节点下,加上以下配置

1
2
3
4
5
6
7
packagingOptions {
exclude 'lib/x86_64/darwin/libscrypt.dylib'
exclude 'com/google/thirdparty/publicsuffix/PublicSuffixPatterns.gwt.xml'
exclude 'com/google/thirdparty/publicsuffix/PublicSuffixType.gwt.xml'
exclude 'org/bitcoinj/crypto/mnemonic/wordlist/english.txt'
exclude 'org/bitcoinj/crypto/cacerts'
}

填坑2

我们要得到12个随机的单词,就要用到里面的MnemonicCode类,但是这个类,默认会new一个实例出来,并且默认加载的单词库路径方式是不支持android的,官方代码如下

1
2
3
4
5
6
7
8
9
10
11
static {
try {
INSTANCE = new MnemonicCode();
} catch (FileNotFoundException e) {
// We expect failure on Android. The developer has to set INSTANCE themselves.
if (!Utils.isAndroidRuntime())
log.error("Could not find word list", e);
} catch (IOException e) {
log.error("Failed to load word list", e);
}
}

1
2
3
4
5
6
7
8
9
10
11
/** Initialise from the included word list. Won't work on Android. */
public MnemonicCode() throws IOException {
this(openDefaultWords(), BIP39_ENGLISH_SHA256);
}

private static InputStream openDefaultWords() throws IOException {
InputStream stream = MnemonicCode.class.getResourceAsStream(BIP39_ENGLISH_RESOURCE_NAME);
if (stream == null)
throw new FileNotFoundException(BIP39_ENGLISH_RESOURCE_NAME);
return stream;
}

可以从代码中看出来,在android平台此路径是绝对不可用的,所以我们要手动自己new这个对象,使用public MnemonicCode(InputStream wordstream, String wordListDigest) throws IOException, IllegalArgumentException这个构造函数

具体实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static void generateMnemonic(Context context) throws Exception {
MnemonicCode mnemonicCode = new MnemonicCode(context.getAssets().open("english.txt"), null);

SecureRandom secureRandom = SecureRandomUtils.secureRandom();
byte[] initialEntropy = new byte[16];//算法需要,必须是被4整除
secureRandom.nextBytes(initialEntropy);
List<String> wd = mnemonicCode.toMnemonic(initialEntropy);
if (wd == null || wd.size() != 12)
throw new RuntimeException("generate word error");
else {
words.clear();
words.addAll(wd);
LogUtils.d(words.toString());
}
}