github.com/jonasnick/go-ethereum@v0.7.12-0.20150216215225-22176f05d387/crypto/mnemonic.go (about)

     1  package crypto
     2  
     3  import (
     4  	"fmt"
     5  	"strconv"
     6  )
     7  
     8  // TODO: See if we can refactor this into a shared util lib if we need it multiple times
     9  func IndexOf(slice []string, value string) int64 {
    10  	for p, v := range slice {
    11  		if v == value {
    12  			return int64(p)
    13  		}
    14  	}
    15  	return -1
    16  }
    17  
    18  func MnemonicEncode(message string) []string {
    19  	var out []string
    20  	n := int64(len(MnemonicWords))
    21  
    22  	for i := 0; i < len(message); i += (len(message) / 8) {
    23  		x := message[i : i+8]
    24  		bit, _ := strconv.ParseInt(x, 16, 64)
    25  		w1 := (bit % n)
    26  		w2 := ((bit / n) + w1) % n
    27  		w3 := ((bit / n / n) + w2) % n
    28  		out = append(out, MnemonicWords[w1], MnemonicWords[w2], MnemonicWords[w3])
    29  	}
    30  	return out
    31  }
    32  
    33  func MnemonicDecode(wordsar []string) string {
    34  	var out string
    35  	n := int64(len(MnemonicWords))
    36  
    37  	for i := 0; i < len(wordsar); i += 3 {
    38  		word1 := wordsar[i]
    39  		word2 := wordsar[i+1]
    40  		word3 := wordsar[i+2]
    41  		w1 := IndexOf(MnemonicWords, word1)
    42  		w2 := IndexOf(MnemonicWords, word2)
    43  		w3 := IndexOf(MnemonicWords, word3)
    44  
    45  		y := (w2 - w1) % n
    46  		z := (w3 - w2) % n
    47  
    48  		// Golang handles modulo with negative numbers different then most languages
    49  		// The modulo can be negative, we don't want that.
    50  		if z < 0 {
    51  			z += n
    52  		}
    53  		if y < 0 {
    54  			y += n
    55  		}
    56  		x := w1 + n*(y) + n*n*(z)
    57  		out += fmt.Sprintf("%08x", x)
    58  	}
    59  	return out
    60  }