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

50 lines
1.6 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;
import androidx.annotation.NonNull;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.SecureRandom;
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
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
}