mnemonic.go 1.3 KB

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