FairEmail/app/src/main/java/eu/faircode/email/BIP39.java

62 lines
2.1 KiB
Java
Raw Normal View History

2022-03-07 08:39:06 +00:00
package eu.faircode.email;
2022-03-06 21:13:07 +00:00
2022-03-07 10:26:04 +00:00
import android.content.Context;
2022-03-08 10:51:35 +00:00
import android.text.TextUtils;
2022-03-07 10:26:04 +00:00
import androidx.annotation.NonNull;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.SecureRandom;
2022-03-08 10:51:35 +00:00
import java.util.ArrayList;
import java.util.List;
2022-03-07 10:26:04 +00:00
import java.util.Locale;
2022-03-07 08:39:06 +00:00
public class BIP39 {
2022-03-07 10:26:04 +00:00
// https://github.com/bitcoin/bips/tree/master/bip-0039
// https://github.com/bitcoin/bips/pull/1129
2022-03-08 10:51:35 +00:00
static String getMnemonic(@NonNull Locale locale, int words, Context context) {
List<String> list = new ArrayList<>();
SecureRandom rnd = new SecureRandom();
for (int i = 0; i < words; i++)
list.add(BIP39.getWord(locale, rnd.nextInt(2048), context));
String delimiter = ("ja".equals(locale.getLanguage()) ? "\u3000" : " ");
return TextUtils.join(delimiter, list);
}
private static String getWord(@NonNull Locale locale, int index, Context context) {
2022-03-07 12:52:14 +00:00
String lang = locale.getLanguage();
if ("zh".equals(lang) && "CN".equals(locale.getCountry()))
lang = "zh_cn";
try (InputStream is = context.getAssets().open("bip39/" + lang + ".txt")) {
2022-03-07 10:26:04 +00:00
return getWord(is, index);
} catch (Throwable ex) {
Log.w(ex);
try (InputStream is = context.getAssets().open("bip39/en.txt")) {
return getWord(is, index);
} catch (Throwable exex) {
Log.e(exex);
return getRandomWord(5);
}
}
}
private static String getWord(InputStream is, int index) throws IOException {
String word = null;
BufferedReader br = new BufferedReader(new InputStreamReader(is));
for (int i = 0; i <= index; i++)
word = br.readLine();
return word;
}
private static String getRandomWord(int len) {
SecureRandom rnd = new SecureRandom();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++)
sb.append((char) ('a' + rnd.nextInt(26)));
return sb.toString();
}
2022-03-07 08:39:06 +00:00
}