Example #1
0
 /**
  * Convert a list of words to a byte string
  * that has the same binary representation with a checksum
  * @param array $words
  * @return string
  */
 public function toEntropy(array $words)
 {
     // collect up words, compact into bit array
     $tmp = new BitArray([]);
     for ($i = 0; $i < count($words); $i++) {
         $wordIndex = array_search($words[$i], $this->words);
         for ($j = 0; $j < 11; $j++) {
             $tmp[$i * 11 + $j] = ($wordIndex & 1 << 10 - $j) != 0;
         }
     }
     $concatLenBits = count($tmp);
     $checksumLengthBits = $concatLenBits / 33;
     $entropyLengthBits = $concatLenBits - $checksumLengthBits;
     $entropy = $tmp->slice(0, $entropyLengthBits)->toBytes();
     $hashBits = new BitArray(hash("sha256", $entropy, true));
     $checksum = $tmp->slice($entropyLengthBits, $checksumLengthBits);
     if ($checksum != $hashBits->slice(0, $checksumLengthBits)) {
         throw new \RuntimeException("Invalid checksum");
     }
     return $entropy;
 }