aboutsummaryrefslogtreecommitdiffstats
path: root/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/experimental/SentenceConfirm.java
blob: 0374d878c236967b23fddc9d587845d551d57258 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
/*
 * Copyright (C) 2015 Dominik Schürmann <dominik@dominikschuermann.de>
 * Copyright (C) 2014 Jake McGinty (Open Whisper Systems)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.sufficientlysecure.keychain.experimental;

import android.content.Context;

import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.util.Log;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * From https://github.com/mcginty/TextSecure/tree/mnemonic-poem
 */
public class SentenceConfirm {
    Context context;
    List<String> n, vi, vt, adj, adv, p, art;

    public SentenceConfirm(Context context) {
        this.context = context;
        try {
            n = readFile(R.raw.fp_sentence_nouns);
            vi = readFile(R.raw.fp_sentence_verbs_i);
            vt = readFile(R.raw.fp_sentence_verbs_t);
            adj = readFile(R.raw.fp_sentence_adjectives);
            adv = readFile(R.raw.fp_sentence_adverbs);
            p = readFile(R.raw.fp_sentence_prepositions);
            art = readFile(R.raw.fp_sentence_articles);
        } catch (IOException e) {
            Log.e(Constants.TAG, "Reading sentence files failed", e);
        }
    }

    List<String> readFile(int resId) throws IOException {
        if (context.getApplicationContext() == null) {
            throw new AssertionError("app context can't be null");
        }

        BufferedReader in = new BufferedReader(new InputStreamReader(
                context.getApplicationContext()
                        .getResources()
                        .openRawResource(resId)));
        List<String> words = new ArrayList<>();
        String word = in.readLine();
        while (word != null) {
            words.add(word);
            word = in.readLine();
        }
        in.close();
        return words;
    }

    public String fromBytes(final byte[] bytes, int desiredBytes) throws IOException {
        BitInputStream bin = new BitInputStream(new ByteArrayInputStream(bytes));
        EntropyString fingerprint = new EntropyString();

        while (fingerprint.getBits() < (desiredBytes * 8)) {
            if (!fingerprint.isEmpty()) {
                fingerprint.append("\n\n");
            }
            try {
                fingerprint.append(getSentence(bin));
            } catch (IOException e) {
                Log.e(Constants.TAG, "IOException when creating the sentence");
                throw e;
            }
        }
        return fingerprint.toString();
    }

    /**
     * Grab a word for a list of them using the necessary bits to choose from a BitInputStream
     *
     * @param words the list of words to select from
     * @param bin   the bit input stream to encode from
     * @return A Pair of the word and the number of bits consumed from the stream
     */
    private EntropyString getWord(List<String> words, BitInputStream bin) throws IOException {
        final int neededBits = log(words.size(), 2);
        Log.d(Constants.TAG, "need: " + neededBits + " bits of entropy");
        Log.d(Constants.TAG, "available: " + bin.available() + " bits");
        if (neededBits > bin.available()) {
            Log.d(Constants.TAG, "stuffed with " + (neededBits - bin.available()) + " ones!");
        }
        int bits = bin.readBits(neededBits, true);
        Log.d(Constants.TAG, "got word " + words.get(bits) + " with " + neededBits + " bits of entropy");
        return new EntropyString(words.get(bits), neededBits);
    }

    private EntropyString getNounPhrase(BitInputStream bits) throws IOException {
        final EntropyString phrase = new EntropyString();
        phrase.append(getWord(art, bits)).append(" ");
        if (bits.readBit(true) != 0) {
            phrase.append(getWord(adj, bits)).append(" ");
        }
        phrase.incBits();

        phrase.append(getWord(n, bits));
        Log.d(Constants.TAG, "got phrase " + phrase + " with " + phrase.getBits() + " bits of entropy");
        return phrase;
    }

    EntropyString getSentence(BitInputStream bits) throws IOException {
        final EntropyString sentence = new EntropyString();
        sentence.append(getNounPhrase(bits));   // Subject
        if (bits.readBit(true) != 0) {
            sentence.append(" ").append(getWord(vt, bits));   // Transitive verb
            sentence.append(" ").append(getNounPhrase(bits)); // Object of transitive verb
        } else {
            sentence.append(" ").append(getWord(vi, bits));   // Intransitive verb
        }
        sentence.incBits();

        if (bits.readBit(true) != 0) {
            sentence.append(" ").append(getWord(adv, bits)); // Adverb
        }

        sentence.incBits();
        if (bits.readBit(true) != 0) {
            sentence.append(" ").append(getWord(p, bits));    // Preposition
            sentence.append(" ").append(getNounPhrase(bits)); // Object of preposition
        }
        sentence.incBits();
        Log.d(Constants.TAG, "got sentence '" + sentence + "' with " + sentence.getBits() + " bits of entropy");

        // uppercase first character, end with dot (without increasing the bits)
        sentence.getBuilder().replace(0, 1,
                Character.toString(Character.toUpperCase(sentence.getBuilder().charAt(0))));
        sentence.getBuilder().append(".");

        return sentence;
    }

    public static class EntropyString {
        private StringBuilder builder;
        private int bits;

        public EntropyString(String phrase, int bits) {
            this.builder = new StringBuilder(phrase);
            this.bits = bits;
        }

        public EntropyString() {
            this("", 0);
        }

        public StringBuilder getBuilder() {
            return builder;
        }

        public boolean isEmpty() {
            return builder.length() == 0;
        }

        public EntropyString append(EntropyString phrase) {
            builder.append(phrase);
            bits += phrase.getBits();
            return this;
        }

        public EntropyString append(String string) {
            builder.append(string);
            return this;
        }

        public int getBits() {
            return bits;
        }

        public void setBits(int bits) {
            this.bits = bits;
        }

        public void incBits() {
            bits += 1;
        }

        @Override
        public String toString() {
            return builder.toString();
        }
    }

    private static int log(int x, int base) {
        return (int) (Math.log(x) / Math.log(base));
    }

}