File: cracker_simple.c

package info (click to toggle)
libtoxcore 0.2.22-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,992 kB
  • sloc: ansic: 70,235; cpp: 14,770; sh: 1,576; python: 649; makefile: 255; perl: 39
file content (86 lines) | stat: -rw-r--r-- 2,095 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/* Public key cracker.
 *
 * Can be used to find public keys starting with specific hex (ABCD) for example.
 *
 * NOTE: There's probably a way to make this faster.
 *
 * Usage: ./cracker ABCDEF
 *
 * Will try to find a public key starting with: ABCDEF
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <sodium.h>

#include "../../toxcore/ccompat.h"

// Secret key and public key length
#define KEY_LEN 32

static void print_key(const uint8_t *client_id)
{
    for (int j = 0; j < KEY_LEN; ++j) {
        printf("%02X", client_id[j]);
    }
}

int main(int argc, char *argv[])
{
    if (argc < 2) {
        printf("usage: ./cracker public_key(or beginning of one in hex format)\n");
        return 0;
    }

    long long unsigned int num_tries = 0;

    size_t len = strlen(argv[1]) / 2;
    unsigned char *key = (unsigned char *)malloc(len);
    const char *hex_end = nullptr;
    if (sodium_hex2bin(key, len, argv[1], strlen(argv[1]), nullptr, nullptr, &hex_end) != 0
            || hex_end != argv[1] + strlen(argv[1])) {
        printf("Invalid key provided\n");
        return 1;
    }
    uint8_t pub_key[KEY_LEN], priv_key[KEY_LEN], c_key[KEY_LEN];

    if (len > KEY_LEN) {
        printf("%zu characters given, truncating to: %d\n", len * 2, KEY_LEN * 2);
        len = KEY_LEN;
    }

    memcpy(c_key, key, len);
    free(key);
    randombytes(priv_key, KEY_LEN);

    while (1) {
        crypto_scalarmult_curve25519_base(pub_key, priv_key);

        if (memcmp(c_key, pub_key, len) == 0) {
            break;
        }

        /*
         * We can't use the first and last bytes because they are masked in
         * curve25519. Using them would generate duplicate keys.
         */
        for (int i = (KEY_LEN - 1); i > 1; --i) {
            priv_key[i - 1] += 1;

            if (priv_key[i - 1] != 0) {
                break;
            }
        }

        ++num_tries;
    }

    printf("Public key:\n");
    print_key(pub_key);
    printf("\nPrivate key:\n");
    print_key(priv_key);
    printf("\n %llu keys tried\n", num_tries);
    return 0;
}