static void test_random(void) {

    long long i, j;
    unsigned char sk1[SCALARBYTES + 16];
    unsigned char pk1[BYTES + 16];
    unsigned char k1[BYTES + 16];
    unsigned char sk2[SCALARBYTES + 16];
    unsigned char pk2[BYTES + 16];
    unsigned char k2[BYTES + 16];


    for (i = 0; i < 16; ++i) {
        unsaferandombytes(sk1 + i, SCALARBYTES);
        unsaferandombytes(sk2 + i, SCALARBYTES);
        if (crypto_scalarmult_curve25519_base(pk1 + i, sk1 + i) != 0) goto fail;
        pk1[31 + i] |= 128;
        if (crypto_scalarmult_curve25519_base(pk2 + i, sk2 + i) != 0) goto fail;
        pk2[31 + i] |= 128;
        if (crypto_scalarmult_curve25519(k1 + i, sk1 + i, pk2 + i) != 0) goto fail;
        if (crypto_scalarmult_curve25519(k2 + i, sk2 + i, pk1 + i) != 0) goto fail;
        for (j = 0; j < BYTES; ++j) if (k1[j + i] != k2[j + i]) goto fail;
    }
    return;

fail:
    fail_printdata("sk1", sk1 + i, SCALARBYTES);
    fail_printdata("sk2", sk2 + i, SCALARBYTES);
    fail("crypto_scalarmult_curve25519() failure, please report it !!!!!!!!!");
}
Ejemplo n.º 2
0
int main()
{
    struct Allocator* alloc = MallocAllocator_new(1048576);
    struct Log* logger = FileWriterLog_new(stdout, alloc);
    struct Random* rand = Random_new(alloc, logger, NULL);

    uint8_t curve25519private[32];
    Random_bytes(rand, curve25519private, 32);
    uint8_t curve25519public[32];
    crypto_scalarmult_curve25519_base(curve25519public, curve25519private);

    uint8_t signingKeyPair[64];
    Sign_signingKeyPairFromCurve25519(signingKeyPair, curve25519private);
    struct Message* msg = Message_new(0, 512, alloc);
    Message_push(msg, "hello world", 12, NULL);
    Sign_signMsg(signingKeyPair, msg, rand);

    uint8_t curve25519publicB[32];
    Assert_true(!Sign_verifyMsg(&signingKeyPair[32], msg));
    Assert_true(!Sign_publicSigningKeyToCurve25519(curve25519publicB, &signingKeyPair[32]));
    Assert_true(!Bits_memcmp(curve25519publicB, curve25519public, 32));

    Allocator_free(alloc);
    return 0;
}
Ejemplo n.º 3
0
struct CryptoAuth* CryptoAuth_new(struct Allocator* allocator,
                                  const uint8_t* privateKey,
                                  struct EventBase* eventBase,
                                  struct Log* logger,
                                  struct Random* rand)
{
    struct CryptoAuth_pvt* ca = Allocator_calloc(allocator, sizeof(struct CryptoAuth_pvt), 1);
    Identity_set(ca);
    ca->allocator = allocator;
    ca->eventBase = eventBase;
    ca->logger = logger;
    ca->pub.resetAfterInactivitySeconds = CryptoAuth_DEFAULT_RESET_AFTER_INACTIVITY_SECONDS;
    ca->rand = rand;

    if (privateKey != NULL) {
        Bits_memcpyConst(ca->privateKey, privateKey, 32);
    } else {
        Random_bytes(rand, ca->privateKey, 32);
    }
    crypto_scalarmult_curve25519_base(ca->pub.publicKey, ca->privateKey);

    if (Defined(Log_KEYS)) {
        uint8_t publicKeyHex[65];
        printHexKey(publicKeyHex, ca->pub.publicKey);
        uint8_t privateKeyHex[65];
        printHexKey(privateKeyHex, ca->privateKey);
        Log_keys(logger,
                  "Initialized CryptoAuth:\n    myPrivateKey=%s\n     myPublicKey=%s\n",
                  privateKeyHex,
                  publicKeyHex);
    }

    return &ca->pub;
}
Ejemplo n.º 4
0
int main() {
	unsigned char n[crypto_box_NONCEBYTES];
	unsigned char m[32+crypto_box_ZEROBYTES];
	unsigned char c[32+crypto_box_ZEROBYTES];

	unsigned char pk[crypto_box_PUBLICKEYBYTES];
	unsigned char sk[crypto_box_SECRETKEYBYTES];
	//crypto_box_keypair(pk, sk);
	//randombytes(sk,32);
	sk[0]=1;
	crypto_scalarmult_curve25519_base(pk,sk);


	int r;

	unsigned char* buffer1offset = m + crypto_box_ZEROBYTES;

	strcpy(buffer1offset, "hello world");
	printf("in=$s\n", buffer1offset);
	memset(m, 0, crypto_box_ZEROBYTES);
	r=crypto_box(c, m, 32+crypto_box_ZEROBYTES, n, pk, sk);
	printf("ret=%d\n", r);

	memset(c, 0, crypto_box_BOXZEROBYTES);
	r=crypto_box_open(m, c, 32+crypto_box_ZEROBYTES, n, pk, sk);
	printf("ret=%d\n", r);
	printf("out=$s\n", buffer1offset);
}
Ejemplo n.º 5
0
int
main(void)
{
    unsigned char ed25519_pk[crypto_sign_ed25519_PUBLICKEYBYTES];
    unsigned char ed25519_skpk[crypto_sign_ed25519_SECRETKEYBYTES];
    unsigned char curve25519_pk[crypto_scalarmult_curve25519_BYTES];
    unsigned char curve25519_pk2[crypto_scalarmult_curve25519_BYTES];
    unsigned char curve25519_sk[crypto_scalarmult_curve25519_BYTES];
    char          curve25519_pk_hex[crypto_scalarmult_curve25519_BYTES * 2 + 1];
    char          curve25519_sk_hex[crypto_scalarmult_curve25519_BYTES * 2 + 1];
    unsigned int  i;

    assert(crypto_sign_ed25519_SEEDBYTES <= crypto_hash_sha512_BYTES);
    crypto_sign_ed25519_seed_keypair(ed25519_pk, ed25519_skpk, keypair_seed);

    if (crypto_sign_ed25519_pk_to_curve25519(curve25519_pk, ed25519_pk) != 0) {
        printf("conversion failed\n");
    }
    crypto_sign_ed25519_sk_to_curve25519(curve25519_sk, ed25519_skpk);
    sodium_bin2hex(curve25519_pk_hex, sizeof curve25519_pk_hex, curve25519_pk,
                   sizeof curve25519_pk);
    sodium_bin2hex(curve25519_sk_hex, sizeof curve25519_sk_hex, curve25519_sk,
                   sizeof curve25519_sk);

    printf("curve25519 pk: [%s]\n", curve25519_pk_hex);
    printf("curve25519 sk: [%s]\n", curve25519_sk_hex);

    for (i = 0U; i < 500U; i++) {
        crypto_sign_ed25519_keypair(ed25519_pk, ed25519_skpk);
        if (crypto_sign_ed25519_pk_to_curve25519(curve25519_pk, ed25519_pk) !=
            0) {
            printf("conversion failed\n");
        }
        crypto_sign_ed25519_sk_to_curve25519(curve25519_sk, ed25519_skpk);
        crypto_scalarmult_curve25519_base(curve25519_pk2, curve25519_sk);
        if (memcmp(curve25519_pk, curve25519_pk2, sizeof curve25519_pk) != 0) {
            printf("conversion failed\n");
        }
    }

    sodium_hex2bin(ed25519_pk, crypto_sign_ed25519_PUBLICKEYBYTES,
                   "0000000000000000000000000000000000000000000000000000000000000000"
                   "0000000000000000000000000000000000000000000000000000000000000000",
                   64, NULL, NULL, NULL);
    assert(crypto_sign_ed25519_pk_to_curve25519(curve25519_pk, ed25519_pk) == -1);
    sodium_hex2bin(ed25519_pk, crypto_sign_ed25519_PUBLICKEYBYTES,
                   "0200000000000000000000000000000000000000000000000000000000000000"
                   "0000000000000000000000000000000000000000000000000000000000000000",
                   64, NULL, NULL, NULL);
    assert(crypto_sign_ed25519_pk_to_curve25519(curve25519_pk, ed25519_pk) == -1);
    sodium_hex2bin(ed25519_pk, crypto_sign_ed25519_PUBLICKEYBYTES,
                   "0500000000000000000000000000000000000000000000000000000000000000"
                   "0000000000000000000000000000000000000000000000000000000000000000",
                   64, NULL, NULL, NULL);
    assert(crypto_sign_ed25519_pk_to_curve25519(curve25519_pk, ed25519_pk) == -1);

    printf("ok\n");

    return 0;
}
Ejemplo n.º 6
0
Archivo: key.c Proyecto: aloisdg/pcp
void pcp_keypairs(byte *msk, byte *mpk, byte *csk, byte *cpk, byte *esk, byte *epk) {
  /*  generate keypairs from random seed */
  byte *ms = urmalloc(32);
  byte *ss = urmalloc(32);
  byte *cs = urmalloc(32);

  /*  ed25519 master key */
  crypto_sign_seed_keypair(mpk, msk, ms);

  /*  ed25519 signing key */
  crypto_sign_seed_keypair(epk, esk, ss);

  /*  curve25519 secret key */
  memcpy(csk, cs, 32);
  csk[0]  &= 248;
  csk[31] &= 63;
  csk[31] |= 64;

  /*  curve25519 public key */
  crypto_scalarmult_curve25519_base(cpk, csk);

  ucfree(ms, 32);
  ucfree(ss, 32);
  ucfree(cs, 32);
}
Ejemplo n.º 7
0
struct CryptoAuth* CryptoAuth_new(struct Allocator* allocator,
                                  const uint8_t* privateKey,
                                  struct event_base* eventBase,
                                  struct Log* logger)
{
    struct CryptoAuth_pvt* ca = allocator->calloc(sizeof(struct CryptoAuth_pvt), 1, allocator);
    ca->allocator = allocator;

    ca->passwords = allocator->calloc(sizeof(struct CryptoAuth_Auth), 256, allocator);
    ca->passwordCount = 0;
    ca->passwordCapacity = 256;
    ca->eventBase = eventBase;
    ca->logger = logger;
    ca->pub.resetAfterInactivitySeconds = CryptoAuth_DEFAULT_RESET_AFTER_INACTIVITY_SECONDS;

    if (privateKey != NULL) {
        Bits_memcpyConst(ca->privateKey, privateKey, 32);
        crypto_scalarmult_curve25519_base(ca->pub.publicKey, ca->privateKey);
    } else {
        crypto_box_curve25519xsalsa20poly1305_keypair(ca->pub.publicKey, ca->privateKey);
    }

    #ifdef Log_KEYS
        uint8_t publicKeyHex[65];
        printHexKey(publicKeyHex, ca->pub.publicKey);
        uint8_t privateKeyHex[65];
        printHexKey(privateKeyHex, ca->privateKey);
        Log_keys(logger,
                  "Initialized CryptoAuth:\n    myPrivateKey=%s\n     myPublicKey=%s\n",
                  privateKeyHex,
                  publicKeyHex);
    #endif

    return &ca->pub;
}
int
crypto_box_curve25519xsalsa20poly1305_keypair(unsigned char *pk,
                                              unsigned char *sk)
{
    randombytes_buf(sk, 32);

    return crypto_scalarmult_curve25519_base(pk, sk);
}
Ejemplo n.º 9
0
int crypto_dh_curve25519_keypair(
    unsigned char *pk,
    unsigned char *sk
    )
{
  randombytes(sk,crypto_scalarmult_curve25519_SCALARBYTES);
  crypto_scalarmult_curve25519_base(pk,sk);
  return 0;
}
Ejemplo n.º 10
0
static inline void printHexPubKey(uint8_t output[65], uint8_t privateKey[32])
{
    if (privateKey) {
        uint8_t publicKey[32];
        crypto_scalarmult_curve25519_base(publicKey, privateKey);
        printHexKey(output, publicKey);
    } else {
        printHexKey(output, NULL);
    }
}
Ejemplo n.º 11
0
int
fDns_read_secret(const char *filename)
{
//    fprintf(stderr, "(%s:%s:%i) filename: '%s'\n", __FILE__, __func__, __LINE__, filename);

    file = fopen(filename, "r");
    if (file == NULL) {
        fprintf(stderr, "(%s:%s:%i) errno: '%s'\n", __FILE__, __func__, __LINE__, strerror(errno));
        return -1;
    }

    while ((read = getline(&line, &len, file)) != -1) {
        sl = strlen(line);
//        fprintf(stderr, "(%s:%s:%i) '%.*s' sl: %u\n", __FILE__, __func__, __LINE__, sl - 1, line, sl);
        if (sl > 63) {
            //check if 64 bytes hex...
            if (fromhex((const unsigned char *)line, &dnscurve_keys[1 + dnscurve_keys_len].server_secretkey[0])) {
                rc = crypto_scalarmult_curve25519_base(&dnscurve_keys[1 + dnscurve_keys_len].server_publickey[0], &dnscurve_keys[1 + dnscurve_keys_len].server_secretkey[0]);
                if (rc != 0) {
                    explicit_bzero((void *)&dnscurve_keys[1 + dnscurve_keys_len].server_secretkey[0], crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES);
                    fprintf(stderr, "(%s:%s:%i) (crypto_scalarmult_curve25519_base) rc: %i\n", __FILE__, __func__, __LINE__, rc);
                } else {
                    dnscurve_keys[1 + dnscurve_keys_len].hash = fDns_hash_fnv64(&dnscurve_keys[1 + dnscurve_keys_len].server_publickey[0], crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES);
                    printf("Using hash: '%lu' for public key for host: ", dnscurve_keys[1 + dnscurve_keys_len].hash);
                    for (rc = 0; rc < crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES; rc++) {
                        printf("%02x", dnscurve_keys[1 + dnscurve_keys_len].server_publickey[rc]);
                    }
                    printf("\n");

                    dnscurve_keys_len++;

                    if (dnscurve_keys_len == DNSCURVE_KEYS_SIZE) {
                        fprintf(stderr, "(%s:%s:%i) Reached the limit of '%i' keys.\n", __FILE__, __func__, __LINE__, dnscurve_keys_len);
                        break;
                    }
                }
            }
        }

        explicit_bzero((void *)line, len);

        len = 0;
        if (line != NULL)
            free(line);
        line = NULL;
    }

    if (dnscurve_keys_len) {
        //the first read secret key is also the DNScurve key.
        fDns_dnscurve_the_key = &dnscurve_keys[1];
    }

    fclose(file);
    return 0;
}
Ejemplo n.º 12
0
main()
{
  int i;
  crypto_scalarmult_curve25519_base(alicepk,alicesk);
  for (i = 0;i < 32;++i) {
    if (i > 0) printf(","); else printf(" ");
    printf("0x%02x",(unsigned int) alicepk[i]);
    if (i % 8 == 7) printf("\n");
  }
  return 0;
}
int
crypto_box_curve25519xsalsa20poly1305_seed_keypair(unsigned char *pk,
                                                   unsigned char *sk,
                                                   const unsigned char *seed)
{
    unsigned char hash[64];

    crypto_hash_sha512(hash, seed, 32);
    memcpy(sk, hash, 32);
    sodium_memzero(hash, sizeof hash);

    return crypto_scalarmult_curve25519_base(pk, sk);
}
Ejemplo n.º 14
0
int
dnsperf_makekey(const unsigned char *hexkey)
{
    encryption = 0;

    if (fromhex(hexkey, &key.server_publickey[0])) {
        //client secret key
        randombytes(&key.server_secretkey[0], 32);
        int rc = crypto_scalarmult_curve25519_base(&key.client_publickey[0], &key.server_secretkey[0]);
        if (rc != 0) {
            fprintf(stderr, "(%s:%s:%i) (crypto_scalarmult_curve25519_base) rc: %i\n", __FILE__, __func__, __LINE__, rc);
            return 0;
        } else {
            key.hash = fDns_hash_fnv64(&key.server_publickey[0], crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES);
/*
            printf("Using hash: '%lu' for public key for host: ", key.hash);
            for (rc = 0; rc < crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES; rc++) {
                printf("%02x", key.server_publickey[rc]);
            }
            printf("\n");
*/
            rc = crypto_box_curve25519xsalsa20poly1305_beforenm((unsigned char *)&key.shared_new_key[0], (const unsigned char *)&key.server_publickey[0], (const unsigned char *)&key.server_secretkey[0]);
            if (rc != 0) {
                fprintf(stderr, "(%s:%s:%i) (crypto_box_curve25519xsalsa20poly1305_beforenm) rc: %i\n", __FILE__, __func__, __LINE__, rc);
                return 0;
            }
            key.shared_key = &key.shared_new_key[0];
/*
            printf("Using shared key: ");
            for (rc = 0; rc < crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES; rc++) {
                printf("%02x", key.shared_key[rc]);
            }
            printf("\n");
*/
        }

        bzero(&key.nonce[12], 12);
        randombytes(&key.nonce[0], 12);
/*
        printf("Using nonce: ");
        for (rc = 0; rc < crypto_box_curve25519xsalsa20poly1305_NONCEBYTES; rc++) {
            printf("%02x", key.nonce[rc]);
        }
        printf("\n");
*/
        encryption = 1;
    }

    return 0;
}
Ejemplo n.º 15
0
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;

    uint32_t len = strlen(argv[1]) / 2;
    unsigned char *key = hex_string_to_bin(argv[1]);
    uint8_t pub_key[32], priv_key[32], c_key[32];

    if (len > 32) {
        len = 32;
    }

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

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

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

        for (i = 32; i != 0; --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;
}
Ejemplo n.º 16
0
int main(int argc, char **argv) {
 if (argc>1) {
  unsigned char pk[64];
  unsigned char sk[32];
  int n;
  if (((n=open(argv[1],0))<0)||(read(n,sk,32)<32)||(close(n)<0)) return 64;
  crypto_scalarmult_curve25519_base(pk,sk);
  memcpy(sk,pk,32);
  if (base16_encode(pk,sk,32)!=64) return 255;
  if (write(1,"pubkey: ",8)!=8) return 255;
  if (write(1,pk,64)!=64) return 255;
  if (write(1,"\n",1)-1) return 255;
  return 0;
 }
 write(2,USAGE,strlen(USAGE));
 return 64;
}
static void test_base(void) {

    long long i, j;

    checksum_zero();
    for (i = 0; i < 1080; ++i) {
        if (crypto_scalarmult_curve25519_base(pk, skdata[i]) != 0) {
            fail_printdata("sk", skdata[i], SCALARBYTES);
            fail("crypto_scalarmult_curve25519_base() failure, please report it !!!!!!!!!");
        }
        for (j = 0; j < BYTES; ++j) if (pk[j] != pkdata[i][j]) {
            fail_printdata("pk_computed", pk, BYTES);
            fail_printdata("pk_expected", pkdata[i], BYTES);
            fail_printdata("sk", skdata[i], SCALARBYTES);
            fail("crypto_scalarmult_curve25519() failure, please report it !!!!!!!!!");
        }
    }
}
Ejemplo n.º 18
0
int curve25519_proto_init(struct curve25519_proto *p, unsigned char *pubkey_remote,
			  size_t len, char *home, int server)
{
	int fd;
	ssize_t ret;
	char path[PATH_MAX];
	unsigned char secretkey_own[crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES] = { 0 };
	unsigned char publickey_own[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES] = { 0 };

	if (!pubkey_remote ||
	    len != crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES)
		return -EINVAL;

	memset(path, 0, sizeof(path));
	slprintf(path, sizeof(path), "%s/%s", home, FILE_PRIVKEY);

	fd = open_or_die(path, O_RDONLY);

	ret = read(fd, secretkey_own, sizeof(secretkey_own));
	if (ret != sizeof(secretkey_own)) {
		xmemset(secretkey_own, 0, sizeof(secretkey_own));
		panic("Cannot read private key!\n");
	}

	close(fd);

	crypto_scalarmult_curve25519_base(publickey_own, secretkey_own);

	if (!crypto_verify_32(publickey_own, pubkey_remote)) {
		xmemset(secretkey_own, 0, sizeof(secretkey_own));
		xmemset(publickey_own, 0, sizeof(publickey_own));
		panic("PANIC: remote end has same public key as you have!!!\n");
	}

	crypto_box_beforenm(p->key, pubkey_remote, secretkey_own);

	xmemset(p->enonce, 0, sizeof(p->enonce));
	xmemset(p->dnonce, 0, sizeof(p->dnonce));

	xmemset(secretkey_own, 0, sizeof(secretkey_own));
	xmemset(publickey_own, 0, sizeof(publickey_own));

	return 0;
}
Ejemplo n.º 19
0
static int genAddress(uint8_t addressOut[40],
                      uint8_t privateKeyHexOut[65],
                      uint8_t publicKeyBase32Out[53])
{
    struct Address address;
    uint8_t privateKey[32];

    for (;;) {
        randombytes(privateKey, 32);
        crypto_scalarmult_curve25519_base(address.key, privateKey);
        AddressCalc_addressForPublicKey(address.ip6.bytes, address.key);
        // Brute force for keys until one matches FC00:/8
        if (address.ip6.bytes[0] == 0xFC) {
            Hex_encode(privateKeyHexOut, 65, privateKey, 32);
            Base32_encode(publicKeyBase32Out, 53, address.key, 32);
            Address_printIp(addressOut, &address);
            return 0;
        }
    }
}
Ejemplo n.º 20
0
static void parsePrivateKey(Dict* config, struct Address* addr, uint8_t privateKey[32])
{
    String* privateKeyStr = Dict_getString(config, BSTR("privateKey"));
    if (privateKeyStr == NULL) {
        fprintf(stderr, "Could not extract private key from configuration.\n");
    } else if (privateKeyStr->len != 64) {
        fprintf(stderr, "Private key is not 32 bytes long.\n");
    } else if (Hex_decode(privateKey, 32, (uint8_t*)privateKeyStr->bytes, 64) != 32) {
        fprintf(stderr, "Failed to parse private key.\n");
    } else {
        crypto_scalarmult_curve25519_base(addr->key, privateKey);
        AddressCalc_addressForPublicKey(addr->ip6.bytes, addr->key);
        if (addr->ip6.bytes[0] != 0xFC) {
            fprintf(stderr, "Ip address is outside of the FC00/8 range, "
                            "invalid private key.\n");
        } else {
            return;
        }
    }
    exit(-1);
}
Ejemplo n.º 21
0
static int proto_init(sigma_proto *instance)
{
    sigma_proto_nacl* inst = ((sigma_proto_nacl*) instance);
    uint8_t taipublickey[crypto_box_PUBLICKEYBYTES];

    crypto_box_beforenm(
        inst->precomp,
        inst->publickey,
        inst->privatekey
    );

    bzero(inst->encnonce, crypto_box_NONCEBYTES);
    bzero(inst->decnonce, crypto_box_NONCEBYTES);

    crypto_scalarmult_curve25519_base(taipublickey, inst->privatekey);

    inst->encnonce[nonceoffset - 1] = memcmp(taipublickey, inst->publickey, crypto_box_PUBLICKEYBYTES) > 0 ? 1 : 0;
    inst->decnonce[nonceoffset - 1] = inst->encnonce[nonceoffset - 1] ? 0 : 1;

    return 0;
}
Ejemplo n.º 22
0
int main()
{
    /* verify public key */
    struct Address address;
    crypto_scalarmult_curve25519_base(address.key, privateKey);

    AddressCalc_addressForPublicKey(address.ip6.bytes, address.key);

    uint8_t privateKeyHexOut[65];
    uint8_t publicKeyHexOut[65];
    uint8_t publicKeyBase32Out[53];

    Hex_encode(privateKeyHexOut, 65, privateKey, 32);

    Hex_encode(publicKeyHexOut, 65, publicKey, 32);

    printf("Private key %s (hex)\n\nExpect:\nPublic Key: %s (hex)\n"
           "Public Key: %s (base32)\nAddress: %s\n",
           privateKeyHexOut,
           publicKeyHexOut,
           publicKeyBase32,
           ipv6);

    uint8_t addressOut[40];

    Hex_encode(publicKeyHexOut, 65, address.key, 32);
    Base32_encode(publicKeyBase32Out, 53, address.key, 32);
    Address_printIp(addressOut, &address);

    printf("\nGot:\nPublic Key: %s (hex)\n"
           "Public Key: %s (base32)\nAddress: %s\n",
           publicKeyHexOut,
           publicKeyBase32Out,
           addressOut);

    Assert_always(0 == memcmp(address.key, publicKey, 32));
    Assert_always(0 == strcmp(publicKeyBase32, (char*) publicKeyBase32Out));
    Assert_always(0 == strcmp(ipv6, (char*) addressOut));
}
Ejemplo n.º 23
0
int main(int argc, char** argv)
{
    struct Allocator* alloc = MallocAllocator_new(1<<22);
    struct Random* rand = Random_new(alloc, NULL, NULL);

    uint8_t privateKey[32];
    uint8_t publicKey[32];
    uint8_t ip[16];
    uint8_t hexPrivateKey[65];
    uint8_t printedIp[40];

    for (;;) {
        Random_bytes(rand, privateKey, 32);
        crypto_scalarmult_curve25519_base(publicKey, privateKey);
        if (AddressCalc_addressForPublicKey(ip, publicKey)) {
            Hex_encode(hexPrivateKey, 65, privateKey, 32);
            AddrTools_printIp(printedIp, ip);
            printf("%s %s\n", hexPrivateKey, printedIp);
        }
    }
    return 0;
}
Ejemplo n.º 24
0
static int genAddress(uint8_t addressOut[40],
                      uint8_t privateKeyHexOut[65],
                      uint8_t publicKeyBase32Out[53],
                      uint8_t privateKey[32])
{
    struct Address address;

    crypto_scalarmult_curve25519_base(address.key, privateKey);
    AddressCalc_addressForPublicKey(address.ip6.bytes, address.key);
    // Brute force for keys until one matches FC00:/8
    if(
        address.ip6.bytes[0] == 0xFC// &&
        //(address.ip6.bytes[15] & 0xF) == (address.ip6.bytes[15] & 0x0F << 4) &&
        //address.ip6.bytes[14] == address.ip6.bytes[15]
    )
    {
        Hex_encode(privateKeyHexOut, 65, privateKey, 32);
        Base32_encode(publicKeyBase32Out, 53, address.key, 32);
        Address_printIp(addressOut, &address);
        return 1;
    }
    return 0;
}
Ejemplo n.º 25
0
SODIUM_EXPORT int
crypto_scalarmult_curve25519_donna_c64_base(unsigned char *q, const unsigned char *n)
{
    return crypto_scalarmult_curve25519_base(q, n);
}
Ejemplo n.º 26
0
static void check_config_keypair_or_die(char *home)
{
	int fd, err;
	ssize_t ret;
	const char * errstr = NULL;
	unsigned char publickey[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES];
	unsigned char publicres[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES];
	unsigned char secretkey[crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES];
	char path[PATH_MAX];

	memset(path, 0, sizeof(path));
	slprintf(path, sizeof(path), "%s/%s", home, FILE_PRIVKEY);

	fd = open(path, O_RDONLY);
	if (fd < 0) {
		err = EIO;
		errstr = "Cannot open privkey file!\n";
		goto out_noclose;
	}

	ret = read(fd, secretkey, sizeof(secretkey));
	if (ret != sizeof(secretkey)) {
		err = EIO;
		errstr = "Cannot read private key!\n";
		goto out;
	}

	close(fd);

	memset(path, 0, sizeof(path));
	slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);

	fd = open(path, O_RDONLY);
	if (fd < 0) {
		err = EIO;
		errstr = "Cannot open pubkey file!\n";
		goto out_noclose;
	}

	ret = read(fd, publickey, sizeof(publickey));
	if (ret != sizeof(publickey)) {
		err = EIO;
		errstr = "Cannot read public key!\n";
		goto out;
	}

	crypto_scalarmult_curve25519_base(publicres, secretkey);

	err = crypto_verify_32(publicres, publickey);
	if (err) {
		err = EINVAL;
		errstr = "WARNING: your keypair is corrupted!!! You need to "
			 "generate new keys!!!\n";
		goto out;
	}
out:
	close(fd);
out_noclose:
	xmemset(publickey, 0, sizeof(publickey));
	xmemset(publicres, 0, sizeof(publicres));
	xmemset(secretkey, 0, sizeof(secretkey));

	if (err)
		panic("%s: %s\n", errstr, strerror(errno));
}
Ejemplo n.º 27
0
static void create_keypair(char *home)
{
	int fd, err = 0;
	ssize_t ret;
	unsigned char publickey[crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES] = { 0 };
	unsigned char secretkey[crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES] = { 0 };
	char path[PATH_MAX];
	const char * errstr = NULL;

	printf("Reading from %s (this may take a while) ...\n", HIG_ENTROPY_SOURCE);

	gen_key_bytes(secretkey, sizeof(secretkey));
	crypto_scalarmult_curve25519_base(publickey, secretkey);

	memset(path, 0, sizeof(path));
	slprintf(path, sizeof(path), "%s/%s", home, FILE_PUBKEY);

	fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
	if (fd < 0) {
		err = EIO;
		errstr = "Cannot open pubkey file!\n";
		goto out_noclose;
	}

	ret = write(fd, publickey, sizeof(publickey));
	if (ret != sizeof(publickey)) {
		err = EIO;
		errstr = "Cannot write public key!\n";
		goto out;
	}

	close(fd);

	printf("Public key written to %s!\n", path);

	memset(path, 0, sizeof(path));
	slprintf(path, sizeof(path), "%s/%s", home, FILE_PRIVKEY);

	fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
	if (fd < 0) {
		err = EIO;
		errstr = "Cannot open privkey file!\n";
		goto out_noclose;
	}

	ret = write(fd, secretkey, sizeof(secretkey));
	if (ret != sizeof(secretkey)) {
		err = EIO;
		errstr = "Cannot write private key!\n";
		goto out;
	}
out:
	close(fd);
out_noclose:
	xmemset(publickey, 0, sizeof(publickey));
	xmemset(secretkey, 0, sizeof(secretkey));

	if (err)
		panic("%s: %s", errstr, strerror(errno));
	else
		printf("Private key written to %s!\n", path);
}
Ejemplo n.º 28
0
keyring_identity *keyring_unpack_identity(unsigned char *slot, const char *pin)
{
  /* Skip salt and MAC */
  int i;
  int ofs;
  keyring_identity *id=calloc(sizeof(keyring_identity),1);
  if (!id) { WHY("calloc() of identity failed"); return NULL; }
  if (!slot) { WHY("slot is null"); return NULL; }

  id->PKRPin=strdup(pin);

  /* There was a known plain-text opportunity here:
     byte 96 must be 0x01, and some other bytes are likely deducible, e.g., the
     location of the trailing 0x00 byte can probably be guessed with confidence.
     Payload rotation would help here.  So let's do that.  First two bytes is
     rotation in bytes of remainder of block.
  */

  int rotation=(slot[PKR_SALT_BYTES+PKR_MAC_BYTES]<<8)
    |slot[PKR_SALT_BYTES+PKR_MAC_BYTES+1];
  ofs=PKR_SALT_BYTES+PKR_MAC_BYTES+2;

  /* Parse block */
  for(ofs=0;ofs<(KEYRING_PAGE_SIZE-PKR_SALT_BYTES-PKR_MAC_BYTES-2);)
    {
      switch(slot_byte(ofs)) {
      case 0x00:
	/* End of data, stop looking */
	ofs=KEYRING_PAGE_SIZE;
	break;
      case KEYTYPE_RHIZOME:
      case KEYTYPE_DID:
      case KEYTYPE_CRYPTOBOX:
      case KEYTYPE_CRYPTOSIGN:
	if (id->keypair_count>=PKR_MAX_KEYPAIRS) {
	  WHY("Too many key pairs in identity");
	  keyring_free_identity(id);
	  return NULL;
	}
	keypair *kp=id->keypairs[id->keypair_count]=calloc(sizeof(keypair),1);
	if (!id->keypairs[id->keypair_count]) {
	  WHY("calloc() of key pair structure failed.");
	  keyring_free_identity(id);
	  return NULL;
	}
	kp->type=slot_byte(ofs);
	switch(kp->type) {
	case KEYTYPE_CRYPTOBOX:
	  kp->private_key_len=crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES;
	  kp->public_key_len=crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES;
	  break;
	case KEYTYPE_CRYPTOSIGN:
	  kp->private_key_len=crypto_sign_edwards25519sha512batch_SECRETKEYBYTES;
	  kp->public_key_len=crypto_sign_edwards25519sha512batch_PUBLICKEYBYTES;
	  break;
	case KEYTYPE_RHIZOME: 
	  kp->private_key_len=32; kp->public_key_len=0;
	  break;
	case KEYTYPE_DID:
	  kp->private_key_len=32; kp->public_key_len=64;
	  break;
	}
	kp->private_key=malloc(kp->private_key_len);
	if (!kp->private_key) {
	  WHY("malloc() of private key storage failed.");
	  keyring_free_identity(id);
	  return NULL;
	}
	for(i=0;i<kp->private_key_len;i++) kp->private_key[i]=slot_byte(ofs+1+i);
	kp->public_key=malloc(kp->public_key_len);
	if (!kp->public_key) {
	  WHY("malloc() of public key storage failed.");
	  keyring_free_identity(id);
	  return NULL;
	}
	/* Hop over the private key and token that we have read */
	ofs+=1+kp->private_key_len;
	switch(kp->type) {
	case KEYTYPE_CRYPTOBOX:
	  /* Compute public key from private key.
	     
	     Public key calculation as below is taken from section 3 of:
	     http://cr.yp.to/highspeed/naclcrypto-20090310.pdf
	     
	     XXX - This can take a while on a mobile phone since it involves a
	     scalarmult operation, so searching through all slots for a pin could 
	     take a while (perhaps 1 second per pin:slot cominbation).  
	     This is both good and bad.  The other option is to store
	     the public key as well, which would make entering a pin faster, but
	     would also make trying an incorrect pin faster, thus simplifying some
	     brute-force attacks.  We need to make a decision between speed/convenience
	     and security here.
	  */
	  crypto_scalarmult_curve25519_base(kp->public_key,kp->private_key);
	  break;
	case KEYTYPE_DID:
	case KEYTYPE_CRYPTOSIGN:
	  /* While it is possible to compute the public key from the private key,
	     NaCl currently does not provide a function to do this, so we have to
	     store it, or else subvert the NaCl API, which I would rather not do.
	     So we just copy it out.  We use the same code for extracting the
	     public key for a DID (i.e, subscriber name)
	  */
	  for(i=0;i<kp->public_key_len;i++) kp->public_key[i]=slot_byte(ofs+i);
	  ofs+=kp->public_key_len;
	  break;
	case KEYTYPE_RHIZOME: 
	  /* no public key value for these, just do nothing */
	  break;
	}
	id->keypair_count++;
	break;
      default:
	/* Invalid data, so invalid record.  Free and return failure.
	   We don't complain about this, however, as it is the natural
	   effect of trying a pin on an incorrect keyring slot. */
	keyring_free_identity(id);	
	return NULL;
      }
      
    }
  return id;
}
Ejemplo n.º 29
0
static uint8_t encryptHandshake(struct Message* message, struct Wrapper* wrapper)
{
    assert(message->padding >= sizeof(union Headers_CryptoAuth) || !"not enough padding");

    Message_shift(message, sizeof(union Headers_CryptoAuth));

    union Headers_CryptoAuth* header = (union Headers_CryptoAuth*) message->bytes;

    // garbage the auth field to frustrate DPI and set the nonce (next 24 bytes after the auth)
    randombytes((uint8_t*) &header->handshake.auth, sizeof(union Headers_AuthChallenge) + 24);
    memcpy(&header->handshake.publicKey, wrapper->context->publicKey, 32);

    if (!knowHerKey(wrapper)) {
        return genReverseHandshake(message, wrapper, header);
    }

    // Password auth
    uint8_t* passwordHash = NULL;
    if (wrapper->password != NULL) {
        struct Auth auth;
        passwordHash = hashPassword(&auth, wrapper->password, wrapper->authType);
        memcpy(header->handshake.auth.bytes, &auth.challenge, sizeof(union Headers_AuthChallenge));
    }
    header->handshake.auth.challenge.type = wrapper->authType;

    Headers_setPacketAuthRequired(&header->handshake.auth, wrapper->authenticatePackets);

    // set the session state
    uint32_t sessionState_be = Endian_hostToBigEndian32(wrapper->nextNonce);
    header->nonce = sessionState_be;

    if (wrapper->nextNonce == 0 || wrapper->nextNonce == 2) {
        // If we're sending a hello or a key
        crypto_box_curve25519xsalsa20poly1305_keypair(header->handshake.encryptedTempKey,
                                                      wrapper->secret);
        if (wrapper->nextNonce == 0) {
            memcpy(wrapper->tempKey, header->handshake.encryptedTempKey, 32);
        }
        #ifdef Log_DEBUG
            assert(!Bits_isZero(header->handshake.encryptedTempKey, 32));
            assert(!Bits_isZero(wrapper->secret, 32));
        #endif
    } else if (wrapper->nextNonce == 3) {
        // Dupe key
        // If nextNonce is 1 then we have our pubkey stored in wrapper->tempKey,
        // If nextNonce is 3 we need to recalculate it each time
        // because tempKey the final secret.
        crypto_scalarmult_curve25519_base(header->handshake.encryptedTempKey,
                                          wrapper->secret);
    } else {
        // Dupe hello
        // wrapper->nextNonce == 1
        // Our public key is cached in wrapper->tempKey so lets copy it out.
        memcpy(header->handshake.encryptedTempKey, wrapper->tempKey, 32);
    }

    uint8_t sharedSecret[32];
    if (wrapper->nextNonce < 2) {
        if (wrapper->nextNonce == 0) {
            Log_debug(wrapper->context->logger, "Sending hello packet\n");
        } else {
            Log_debug(wrapper->context->logger, "Sending repeat hello packet\n");
        }
        getSharedSecret(sharedSecret,
                        wrapper->context->privateKey,
                        wrapper->herPerminentPubKey,
                        passwordHash,
                        wrapper->context->logger);
        wrapper->isInitiator = true;
        wrapper->nextNonce = 1;
        #ifdef Log_DEBUG
            assert(!Bits_isZero(header->handshake.encryptedTempKey, 32));
            uint8_t myTempPubKey[32];
            crypto_scalarmult_curve25519_base(myTempPubKey, wrapper->secret);
            assert(!memcmp(header->handshake.encryptedTempKey, myTempPubKey, 32));
        #endif
        #ifdef Log_KEYS
            uint8_t tempKeyHex[65];
            Hex_encode(tempKeyHex, 65, header->handshake.encryptedTempKey, 32);
            Log_keys1(wrapper->context->logger,
                      "Wrapping temp public key:\n"
                      "    %s\n",
                      tempKeyHex);
        #endif
    } else {
        if (wrapper->nextNonce == 2) {
            Log_debug(wrapper->context->logger, "Sending key packet\n");
        } else {
            Log_debug(wrapper->context->logger, "Sending repeat key packet\n");
        }
        // Handshake2 wrapper->tempKey holds her public temp key.
        // it was put there by receiveMessage()
        getSharedSecret(sharedSecret,
                        wrapper->context->privateKey,
                        wrapper->tempKey,
                        passwordHash,
                        wrapper->context->logger);
        wrapper->nextNonce = 3;

        #ifdef Log_KEYS
            uint8_t tempKeyHex[65];
            Hex_encode(tempKeyHex, 65, wrapper->tempKey, 32);
            Log_keys1(wrapper->context->logger,
                      "Using their temp public key:\n"
                      "    %s\n",
                      tempKeyHex);
        #endif
    }

    // Shift message over the encryptedTempKey field.
    Message_shift(message, 32 - Headers_CryptoAuth_SIZE);

    encryptRndNonce(header->handshake.nonce, message, sharedSecret);

    Log_debug1(wrapper->context->logger, "Message length: %u\n", message->length);
    #ifdef Log_KEYS
        uint8_t sharedSecretHex[65];
        printHexKey(sharedSecretHex, sharedSecret);
        uint8_t nonceHex[49];
        Hex_encode(nonceHex, 49, header->handshake.nonce, 24);
        uint8_t cipherHex[65];
        printHexKey(cipherHex, message->bytes);
        Log_keys3(wrapper->context->logger,
                  "Encrypting message with:\n"
                  "    nonce: %s\n"
                  "   secret: %s\n"
                  "   cipher: %s\n",
                  nonceHex, sharedSecretHex, cipherHex);
    #endif
    #ifdef Log_DEBUG
        assert(!Bits_isZero(header->handshake.encryptedTempKey, 32));
    #endif

    // Shift it back -- encryptRndNonce adds 16 bytes of authenticator.
    Message_shift(message, Headers_CryptoAuth_SIZE - 32 - 16);

    return wrapper->wrappedInterface->sendMessage(message, wrapper->wrappedInterface);
}
Ejemplo n.º 30
0
TCP_Server *new_TCP_server(uint8_t ipv6_enabled, uint16_t num_sockets, const uint16_t *ports, const uint8_t *secret_key,
                           Onion *onion)
{
    if (num_sockets == 0 || ports == NULL) {
        return NULL;
    }

    if (networking_at_startup() != 0) {
        return NULL;
    }

    TCP_Server *temp = (TCP_Server *)calloc(1, sizeof(TCP_Server));

    if (temp == NULL) {
        return NULL;
    }

    temp->socks_listening = (sock_t *)calloc(num_sockets, sizeof(sock_t));

    if (temp->socks_listening == NULL) {
        free(temp);
        return NULL;
    }

#ifdef TCP_SERVER_USE_EPOLL
    temp->efd = epoll_create(8);

    if (temp->efd == -1) {
        free(temp->socks_listening);
        free(temp);
        return NULL;
    }

#endif

    uint8_t family;

    if (ipv6_enabled) {
        family = AF_INET6;
    } else {
        family = AF_INET;
    }

    uint32_t i;
#ifdef TCP_SERVER_USE_EPOLL
    struct epoll_event ev;
#endif

    for (i = 0; i < num_sockets; ++i) {
        sock_t sock = new_listening_TCP_socket(family, ports[i]);

        if (sock_valid(sock)) {
#ifdef TCP_SERVER_USE_EPOLL
            ev.events = EPOLLIN | EPOLLET;
            ev.data.u64 = sock | ((uint64_t)TCP_SOCKET_LISTENING << 32);

            if (epoll_ctl(temp->efd, EPOLL_CTL_ADD, sock, &ev) == -1) {
                continue;
            }

#endif

            temp->socks_listening[temp->num_listening_socks] = sock;
            ++temp->num_listening_socks;
        }
    }

    if (temp->num_listening_socks == 0) {
        free(temp->socks_listening);
        free(temp);
        return NULL;
    }

    if (onion) {
        temp->onion = onion;
        set_callback_handle_recv_1(onion, &handle_onion_recv_1, temp);
    }

    memcpy(temp->secret_key, secret_key, crypto_box_SECRETKEYBYTES);
    crypto_scalarmult_curve25519_base(temp->public_key, temp->secret_key);

    bs_list_init(&temp->accepted_key_list, crypto_box_PUBLICKEYBYTES, 8);

    return temp;
}