mnencode.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <errno.h>
  5. #include <ctype.h>
  6. #include "mnemonic.h"
  7. int counthex(const mn_byte *s, size_t len) {
  8. int total = 0;
  9. size_t i;
  10. for(i = 0; i < len; i++) {
  11. if(isxdigit(s[i])) total++;
  12. }
  13. return total;
  14. }
  15. int countLeadingCrapAndZeros(const mn_byte *in, size_t inlen) {
  16. size_t i;
  17. for(i = 0; i < inlen; i++) {
  18. if(in[i] != '0' && isxdigit(in[i])) break; /* Find first non-zero hex digit */
  19. }
  20. return i;
  21. }
  22. int hex2bytes(int inlen, const mn_byte *in, mn_byte *out) {
  23. char t[3];
  24. int i, j = 0, k = 0;
  25. i = countLeadingCrapAndZeros(in, inlen);
  26. inlen = inlen - i;
  27. in = in + i;
  28. if(counthex(in, inlen) % 2 != 0) {
  29. t[j++] = '0';
  30. }
  31. for(i = 0; i < inlen; i++) {
  32. if(isxdigit(in[i])) {
  33. t[j++] = in[i];
  34. if(j == 2) {
  35. t[2] = '\0';
  36. errno = 0;
  37. out[k++] = strtol(t, NULL, 16);
  38. if(errno != 0) {
  39. return -1;
  40. }
  41. j = 0;
  42. }
  43. }
  44. }
  45. return k;
  46. }
  47. int main(int argc, char **argv) {
  48. mn_byte *buf;
  49. mn_byte cbuf[0x10000];
  50. mn_byte xbuf[0x8000];
  51. char outbuf[0x90000];
  52. int buflen;
  53. int n;
  54. int hex_encoded_input = 0;
  55. if(argc > 1 && strcmp(argv[1],"-x") == 0) {
  56. hex_encoded_input = 1;
  57. }
  58. fprintf (stderr, "%s\n", mn_wordlist_version);
  59. buflen = fread(cbuf, 1, sizeof cbuf, stdin);
  60. if(hex_encoded_input) {
  61. buflen = hex2bytes(buflen, cbuf, xbuf);
  62. if(buflen < 0) {
  63. perror("hex2bytes");
  64. return EXIT_FAILURE;
  65. }
  66. buf = xbuf;
  67. } else {
  68. buf = cbuf;
  69. }
  70. n = mn_encode(buf, buflen, outbuf, sizeof outbuf, "x x x. x x x. x x x\n");
  71. if(n != 0) {
  72. fprintf(stderr, "mn_encode error %d\n", n);
  73. return EXIT_FAILURE;
  74. }
  75. fwrite(outbuf, 1, strlen (outbuf), stdout);
  76. putchar('\n');
  77. return EXIT_SUCCESS;
  78. }