mnemonic.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package crypto
  17. import (
  18. "fmt"
  19. "strconv"
  20. )
  21. // TODO: See if we can refactor this into a shared util lib if we need it multiple times
  22. func IndexOf(slice []string, value string) int64 {
  23. for p, v := range slice {
  24. if v == value {
  25. return int64(p)
  26. }
  27. }
  28. return -1
  29. }
  30. func MnemonicEncode(message string) []string {
  31. var out []string
  32. n := int64(len(MnemonicWords))
  33. for i := 0; i < len(message); i += (len(message) / 8) {
  34. x := message[i : i+8]
  35. bit, _ := strconv.ParseInt(x, 16, 64)
  36. w1 := (bit % n)
  37. w2 := ((bit / n) + w1) % n
  38. w3 := ((bit / n / n) + w2) % n
  39. out = append(out, MnemonicWords[w1], MnemonicWords[w2], MnemonicWords[w3])
  40. }
  41. return out
  42. }
  43. func MnemonicDecode(wordsar []string) string {
  44. var out string
  45. n := int64(len(MnemonicWords))
  46. for i := 0; i < len(wordsar); i += 3 {
  47. word1 := wordsar[i]
  48. word2 := wordsar[i+1]
  49. word3 := wordsar[i+2]
  50. w1 := IndexOf(MnemonicWords, word1)
  51. w2 := IndexOf(MnemonicWords, word2)
  52. w3 := IndexOf(MnemonicWords, word3)
  53. y := (w2 - w1) % n
  54. z := (w3 - w2) % n
  55. // Golang handles modulo with negative numbers different then most languages
  56. // The modulo can be negative, we don't want that.
  57. if z < 0 {
  58. z += n
  59. }
  60. if y < 0 {
  61. y += n
  62. }
  63. x := w1 + n*(y) + n*n*(z)
  64. out += fmt.Sprintf("%08x", x)
  65. }
  66. return out
  67. }