]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/BIP39.git/blob - src/js/entropy.js
Card entropy has improved conversion to binary
[perso/Immae/Projets/Cryptomonnaies/BIP39.git] / src / js / entropy.js
1 /*
2 * Detects entropy from a string.
3 *
4 * Formats include:
5 * binary [0-1]
6 * base 6 [0-5]
7 * dice 6 [1-6]
8 * decimal [0-9]
9 * hexadecimal [0-9A-F]
10 * card [A2-9TJQK][CDHS]
11 *
12 * Automatically uses lowest entropy to avoid issues such as interpretting 0101
13 * as hexadecimal which would be 16 bits when really it's only 4 bits of binary
14 * entropy.
15 */
16
17 window.Entropy = new (function() {
18
19 var TWO = new BigInteger(2);
20
21 // matchers returns an array of the matched events for each type of entropy.
22 // eg
23 // matchers.binary("010") returns ["0", "1", "0"]
24 // matchers.binary("a10") returns ["1", "0"]
25 // matchers.hex("a10") returns ["a", "1", "0"]
26 var matchers = {
27 binary: function(str) {
28 return str.match(/[0-1]/gi) || [];
29 },
30 base6: function(str) {
31 return str.match(/[0-5]/gi) || [];
32 },
33 dice: function(str) {
34 return str.match(/[1-6]/gi) || []; // ie dice numbers
35 },
36 base10: function(str) {
37 return str.match(/[0-9]/gi) || [];
38 },
39 hex: function(str) {
40 return str.match(/[0-9A-F]/gi) || [];
41 },
42 card: function(str) {
43 // Format is NumberSuit, eg
44 // AH ace of hearts
45 // 8C eight of clubs
46 // TD ten of diamonds
47 // JS jack of spades
48 // QH queen of hearts
49 // KC king of clubs
50 return str.match(/([A2-9TJQK][CDHS])/gi) || [];
51 }
52 }
53
54 // Convert array of cards from ["ac", "4d", "ks"]
55 // to numbers between 0 and 51 [0, 16, 51]
56 function convertCardsToInts(cards) {
57 var ints = [];
58 var values = "a23456789tjqk";
59 var suits = "cdhs";
60 for (var i=0; i<cards.length; i++) {
61 var card = cards[i].toLowerCase();
62 var value = card[0];
63 var suit = card[1];
64 var asInt = 13 * suits.indexOf(suit) + values.indexOf(value);
65 ints.push(asInt);
66 }
67 return ints;
68 }
69
70 this.fromString = function(rawEntropyStr) {
71 // Find type of entropy being used (binary, hex, dice etc)
72 var base = getBase(rawEntropyStr);
73 // Convert dice to base6 entropy (ie 1-6 to 0-5)
74 // This is done by changing all 6s to 0s
75 if (base.str == "dice") {
76 var newParts = [];
77 var newInts = [];
78 for (var i=0; i<base.parts.length; i++) {
79 var c = base.parts[i];
80 if ("12345".indexOf(c) > -1) {
81 newParts[i] = base.parts[i];
82 newInts[i] = base.ints[i];
83 }
84 else {
85 newParts[i] = "0";
86 newInts[i] = 0;
87 }
88 }
89 base.str = "base 6 (dice)";
90 base.ints = newInts;
91 base.parts = newParts;
92 base.matcher = matchers.base6;
93 }
94 // Detect empty entropy
95 if (base.parts.length == 0) {
96 return {
97 binaryStr: "",
98 cleanStr: "",
99 cleanHtml: "",
100 base: base,
101 };
102 }
103 // Convert base.ints to BigInteger.
104 // Due to using unusual bases, eg cards of base52, this is not as simple as
105 // using BigInteger.parse()
106 var entropyInt = BigInteger.ZERO;
107 for (var i=base.ints.length-1; i>=0; i--) {
108 var thisInt = BigInteger.parse(base.ints[i]);
109 var power = (base.ints.length - 1) - i;
110 var additionalEntropy = BigInteger.parse(base.asInt).pow(power).multiply(thisInt);
111 entropyInt = entropyInt.add(additionalEntropy);
112 }
113 // Convert entropy to binary
114 var entropyBin = entropyInt.toString(2);
115 // If the first integer is small, it must be padded with zeros.
116 // Otherwise the chance of the first bit being 1 is 100%, which is
117 // obviously incorrect.
118 // This is not perfect for non-2^n bases.
119 var expectedBits = Math.floor(base.parts.length * Math.log2(base.asInt));
120 while (entropyBin.length < expectedBits) {
121 entropyBin = "0" + entropyBin;
122 }
123 // Cards binary must be handled differently, since they're not replaced
124 if (base.asInt == 52) {
125 entropyBin = getCardBinary(base.parts);
126 }
127 // Supply a 'filtered' entropy string for display purposes
128 var entropyClean = base.parts.join("");
129 var entropyHtml = base.parts.join("");
130 if (base.asInt == 52) {
131 entropyClean = base.parts.join(" ").toUpperCase();
132 entropyClean = entropyClean.replace(/C/g, "\u2663");
133 entropyClean = entropyClean.replace(/D/g, "\u2666");
134 entropyClean = entropyClean.replace(/H/g, "\u2665");
135 entropyClean = entropyClean.replace(/S/g, "\u2660");
136 entropyHtml = base.parts.join(" ").toUpperCase();
137 entropyHtml = entropyHtml.replace(/C/g, "<span class='card-suit club'>\u2663</span>");
138 entropyHtml = entropyHtml.replace(/D/g, "<span class='card-suit diamond'>\u2666</span>");
139 entropyHtml = entropyHtml.replace(/H/g, "<span class='card-suit heart'>\u2665</span>");
140 entropyHtml = entropyHtml.replace(/S/g, "<span class='card-suit spade'>\u2660</span>");
141 }
142 // Return the result
143 var e = {
144 binaryStr: entropyBin,
145 cleanStr: entropyClean,
146 cleanHtml: entropyHtml,
147 base: base,
148 }
149 return e;
150 }
151
152 function getSortedDeck() {
153 var s = [];
154 var suits = "CDHS";
155 var values = "A23456789TJQK";
156 for (var i=0; i<suits.length; i++) {
157 for (var j=0; j<values.length; j++) {
158 s.push(values[j]+suits[i]);
159 }
160 }
161 return s;
162 }
163
164 function getBase(str) {
165 // Need to get the lowest base for the supplied entropy.
166 // This prevents interpreting, say, dice rolls as hexadecimal.
167 var binaryMatches = matchers.binary(str);
168 var hexMatches = matchers.hex(str);
169 // Find the lowest base that can be used, whilst ignoring any irrelevant chars
170 if (binaryMatches.length == hexMatches.length && hexMatches.length > 0) {
171 var ints = binaryMatches.map(function(i) { return parseInt(i, 2) });
172 return {
173 ints: ints,
174 parts: binaryMatches,
175 matcher: matchers.binary,
176 asInt: 2,
177 str: "binary",
178 }
179 }
180 var cardMatches = matchers.card(str);
181 if (cardMatches.length >= hexMatches.length / 2) {
182 var ints = convertCardsToInts(cardMatches);
183 return {
184 ints: ints,
185 parts: cardMatches,
186 matcher: matchers.card,
187 asInt: 52,
188 str: "card",
189 }
190 }
191 var diceMatches = matchers.dice(str);
192 if (diceMatches.length == hexMatches.length && hexMatches.length > 0) {
193 var ints = diceMatches.map(function(i) { return parseInt(i) });
194 return {
195 ints: ints,
196 parts: diceMatches,
197 matcher: matchers.dice,
198 asInt: 6,
199 str: "dice",
200 }
201 }
202 var base6Matches = matchers.base6(str);
203 if (base6Matches.length == hexMatches.length && hexMatches.length > 0) {
204 var ints = base6Matches.map(function(i) { return parseInt(i) });
205 return {
206 ints: ints,
207 parts: base6Matches,
208 matcher: matchers.base6,
209 asInt: 6,
210 str: "base 6",
211 }
212 }
213 var base10Matches = matchers.base10(str);
214 if (base10Matches.length == hexMatches.length && hexMatches.length > 0) {
215 var ints = base10Matches.map(function(i) { return parseInt(i) });
216 return {
217 ints: ints,
218 parts: base10Matches,
219 matcher: matchers.base10,
220 asInt: 10,
221 str: "base 10",
222 }
223 }
224 var ints = hexMatches.map(function(i) { return parseInt(i, 16) });
225 return {
226 ints: ints,
227 parts: hexMatches,
228 matcher: matchers.hex,
229 asInt: 16,
230 str: "hexadecimal",
231 }
232 }
233
234 // Assume cards are NOT replaced.
235 // Additional entropy decreases as more cards are used. This means
236 // total possible entropy is measured using n!, not base^n.
237 // eg the second last card can be only one of two, not one of fifty two
238 // so the added entropy for that card is only one bit at most
239 function getCardBinary(cards) {
240 // Track how many instances of each card have been used, and thus
241 // how many decks are in use.
242 var cardCounts = {};
243 var numberOfDecks = 0;
244 // Work out number of decks by max(duplicates)
245 for (var i=0; i<cards.length; i++) {
246 // Get the card that was drawn
247 var cardLower = cards[i];
248 var card = cardLower.toUpperCase();
249 // Initialize the count for this card if needed
250 if (!(card in cardCounts)) {
251 cardCounts[card] = 0;
252 }
253 cardCounts[card] += 1;
254 // See if this is max(duplicates)
255 if (cardCounts[card] > numberOfDecks) {
256 numberOfDecks = cardCounts[card];
257 }
258 }
259 // Work out the total number of bits for this many decks
260 // See http://crypto.stackexchange.com/q/41886
261 var gainedBits = Math.log2(factorial(52 * numberOfDecks));
262 var lostBits = 52 * Math.log2(factorial(numberOfDecks));
263 var maxBits = gainedBits - lostBits;
264 // Convert the drawn cards to a binary representation.
265 // The exact technique for doing this is unclear.
266 // See
267 // http://crypto.stackexchange.com/a/41896
268 // "I even doubt that this is well defined (only the average entropy
269 // is, I believe)."
270 // See
271 // https://github.com/iancoleman/bip39/issues/33#issuecomment-263021856
272 // "The binary representation can be the first log(permutations,2) bits
273 // of the sha-2 hash of the normalized deck string."
274 //
275 // In this specific implementation, the first N bits of the hash of the
276 // normalized cards string is being used. Uppercase, no spaces; eg
277 // sha256("AH8DQSTC2H")
278 var totalCards = numberOfDecks * 52;
279 var percentUsed = cards.length / totalCards;
280 // Calculate the average number of bits of entropy for the number of
281 // cards drawn.
282 var numberOfBits = Math.floor(maxBits * percentUsed);
283 // Create a normalized string of the selected cards
284 var normalizedCards = cards.join("").toUpperCase();
285 // Convert to binary using the SHA256 hash of the normalized cards.
286 // If the number of bits is more than 256, multiple rounds of hashing
287 // are used until the required number of bits is reached.
288 var entropyBin = "";
289 var iterations = 0;
290 while (entropyBin.length < numberOfBits) {
291 var hashedCards = sjcl.hash.sha256.hash(normalizedCards);
292 for (var j=0; j<iterations; j++) {
293 hashedCards = sjcl.hash.sha256.hash(hashedCards);
294 }
295 var hashHex = sjcl.codec.hex.fromBits(hashedCards);
296 for (var i=0; i<hashHex.length; i++) {
297 var decimal = parseInt(hashHex[i], 16);
298 var binary = decimal.toString(2);
299 while (binary.length < 4) {
300 binary = "0" + binary;
301 }
302 entropyBin = entropyBin + binary;
303 }
304 iterations = iterations + 1;
305 }
306 // Truncate to the appropriate number of bits.
307 entropyBin = entropyBin.substring(0, numberOfBits);
308 return entropyBin;
309 }
310
311 // Polyfill for Math.log2
312 // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log2#Polyfill
313 Math.log2 = Math.log2 || function(x) {
314 // The polyfill isn't good enough because of the poor accuracy of
315 // Math.LOG2E
316 // log2(8) gave 2.9999999999999996 which when floored causes issues.
317 // So instead use the BigInteger library to get it right.
318 return BigInteger.log(x) / BigInteger.log(2);
319 };
320
321 // Depends on BigInteger
322 function factorial(n) {
323 if (n == 0) {
324 return 1;
325 }
326 f = BigInteger.ONE;
327 for (var i=1; i<=n; i++) {
328 f = f.multiply(new BigInteger(i));
329 }
330 return f;
331 }
332
333 })();