示例#1
0
int main(void)
{
    int clen;

    for (clen = 0; clen < 10000; ++clen) {
        randombytes_buf(key, sizeof key);
        randombytes_buf(c, clen);
        crypto_onetimeauth(a, c, clen, key);
        if (crypto_onetimeauth_verify(a, c, clen, key) != 0) {
            printf("fail %d\n", clen);
            return 100;
        }
        if (clen > 0) {
            c[rand() % clen] += 1 + (rand() % 255);
            if (crypto_onetimeauth_verify(a, c, clen, key) == 0) {
                printf("forgery %d\n", clen);
                return 100;
            }
            a[rand() % sizeof a] += 1 + (rand() % 255);
            if (crypto_onetimeauth_verify(a, c, clen, key) == 0) {
                printf("forgery %d\n", clen);
                return 100;
            }
        }
    }
    return 0;
}
示例#2
0
int
shick_crypto_enc_message(const SC_CHAR sender_secret_key[crypto_box_SECRETKEYBYTES],
                         const SC_CHAR** recipient_public_keys,
                         const int amount_of_recipients,
                         const SC_CHAR* message,
                         const SC_LEN message_len,
                         SC_CHAR nonce[crypto_box_NONCEBYTES],
                         SC_ENC_SYM_KEY* encrypted_symmetric_keys,
                         SC_CHAR* ciphertext) {
  int failed = 0;

  // Create symmetric key
  SC_SYM_KEY sym_key;
  randombytes_buf((void*) sym_key.key, sizeof sym_key.key);
  randombytes_buf((void*) sym_key.nonce, sizeof sym_key.nonce);

  // Encrypt message symmetrically
  failed = crypto_secretbox_easy(ciphertext, message, message_len, sym_key.nonce, sym_key.key);
  if (failed) return SC_ENC_SYM_FAILED;

  // Encrypt symmetric key asymmetrically for each recipient
  for (int i = 0; i < amount_of_recipients; i++) {
    SC_CHAR public_key[crypto_box_PUBLICKEYBYTES];
    memcpy(public_key, recipient_public_keys[i], crypto_box_PUBLICKEYBYTES);
    failed = crypto_box_easy((SC_CHAR*) &encrypted_symmetric_keys[i], (SC_CHAR*) &sym_key, sizeof sym_key, nonce, public_key, sender_secret_key);
    if (failed) return SC_ENC_ASYM_FAILED;
  }

  return 0;
}
示例#3
0
int main(void)
{
    randombytes_buf(v16, sizeof v16);
    randombytes_buf(v32, sizeof v32);
    randombytes_buf(v64, sizeof v64);

    memcpy(v16x, v16, sizeof v16);
    memcpy(v32x, v32, sizeof v32);
    memcpy(v64x, v64, sizeof v64);

    printf("%d\n", crypto_verify_16(v16, v16x));
    printf("%d\n", crypto_verify_32(v32, v32x));
    printf("%d\n", crypto_verify_64(v64, v64x));

    v16x[randombytes_random() & 15U]++;
    v32x[randombytes_random() & 31U]++;
    v64x[randombytes_random() & 63U]++;

    printf("%d\n", crypto_verify_16(v16, v16x));
    printf("%d\n", crypto_verify_32(v32, v32x));
    printf("%d\n", crypto_verify_64(v64, v64x));

    assert(crypto_verify_16_bytes() == 16U);
    assert(crypto_verify_32_bytes() == 32U);
    assert(crypto_verify_64_bytes() == 64U);

    return 0;
}
示例#4
0
文件: auth7.c 项目: 52M/libsodium
int main(void)
{
    size_t clen;

    for (clen = 0; clen < sizeof c; ++clen) {
        randombytes_buf(key, sizeof key);
        randombytes_buf(c, clen);
        crypto_auth_hmacsha512(a, c, clen, key);
        if (crypto_auth_hmacsha512_verify(a, c, clen, key) != 0) {
            printf("fail %u\n", (unsigned int) clen);
            return 100;
        }
        if (clen > 0) {
            c[(size_t) rand() % clen] += 1 + (rand() % 255);
            if (crypto_auth_hmacsha512_verify(a, c, clen, key) == 0) {
                printf("forgery %u\n", (unsigned int) clen);
                return 100;
            }
            a[rand() % sizeof a] += 1 + (rand() % 255);
            if (crypto_auth_hmacsha512_verify(a, c, clen, key) == 0) {
                printf("forgery %u\n", (unsigned int) clen);
                return 100;
            }
        }
    }
    return 0;
}
示例#5
0
文件: dfcrypt.c 项目: defuse/dfcrypt
void dfcrypt_encrypt(
    const dfcrypt_state_t *state,
    const unsigned char *ptxt,
    size_t ptxt_len_bytes,
    const unsigned char *message_number,
    unsigned char *ctxt_out
)
{
    unsigned char *salt = ctxt_out;
    unsigned char *nonce = ctxt_out + DFCRYPT_INTERNAL_SALT_BYTES;
    unsigned char *encrypted = nonce + crypto_stream_chacha20_NONCEBYTES;
    unsigned char *mac = encrypted + ptxt_len_bytes;

    unsigned char keys[DFCRYPT_INTERNAL_AKEY_BYTES + DFCRYPT_INTERNAL_EKEY_BYTES];
    const unsigned char *akey = keys;
    const unsigned char *ekey = keys + DFCRYPT_INTERNAL_AKEY_BYTES;

    /* Sample a random salt and nonce. */
    randombytes_buf(salt, DFCRYPT_INTERNAL_SALT_BYTES);
    randombytes_buf(nonce, crypto_stream_chacha20_NONCEBYTES);

    /* Derive the authentication and encryption keys. */
    assert(sizeof(keys) == 64);
    crypto_generichash_blake2b_salt_personal(
        keys,                   /* output */
        sizeof(keys),           /* output length */
        state->appseed,         /* input */
        state->appseed_length,  /* input length */
        state->key,             /* key */
        DFCRYPT_KEY_BYTES,      /* key length */
        salt,                   /* salt */
        message_number          /* personalization (can be NULL) */
    );

    /* Encrypt the ciphertext. */
    crypto_stream_chacha20_xor(
        encrypted,      /* output */
        ptxt,           /* input */
        ptxt_len_bytes, /* input length */
        nonce,          /* nonce */
        ekey            /* key */
    );

    /* Append the MAC. */
    crypto_generichash_blake2b(
        mac,                            /* output */
        DFCRYPT_INTERNAL_MAC_BYTES,     /* output length */
        ctxt_out,                       /* input */
        DFCRYPT_INTERNAL_SALT_BYTES +
        crypto_stream_chacha20_NONCEBYTES + ptxt_len_bytes, /* input length */
        akey,                           /* key */
        DFCRYPT_INTERNAL_AKEY_BYTES     /* key length */
    );
}
示例#6
0
static int
cms_init(CMS * const cms, const size_t vector_size, const size_t items_count)
{
    cms->vector_entries = (size_t) vector_size /
        (size_t) sizeof *cms->vector;
    cms->k_num = cms_optimal_k_num(cms->vector_entries, items_count);
    cms->vector = calloc(sizeof *cms->vector, vector_size);
    if (cms->vector == NULL) {
        return -1;
    }
    randombytes_buf(&cms->skeys[0], sizeof cms->skeys[0]);
    randombytes_buf(&cms->skeys[1], sizeof cms->skeys[1]);

    return 0;
}
int main(void) {
	sodium_init();

	//create random chain key
	unsigned char chain_key[crypto_auth_BYTES];
	randombytes_buf(chain_key, crypto_auth_BYTES);

	//print first chain key
	printf("Chain key (%i Bytes):\n", crypto_auth_BYTES);
	print_hex(chain_key, crypto_auth_BYTES, 30);
	putchar('\n');

	int status;


	//derive message key from chain key
	unsigned char message_key[crypto_auth_BYTES];
	status = derive_message_key(message_key, chain_key);
	sodium_memzero(chain_key, crypto_auth_BYTES);
	if (status != 0) {
		fprintf(stderr, "ERROR: Failed to derive message key. (%i)\n", status);
		sodium_memzero(message_key, crypto_auth_BYTES);
		return status;
	}

	//print message key
	printf("Message key (%i Bytes):\n", crypto_auth_BYTES);
	print_hex(message_key, crypto_auth_BYTES, 30);
	putchar('\n');

	sodium_memzero(message_key, crypto_auth_BYTES);
	return EXIT_SUCCESS;
}
示例#8
0
int
crypto_encrypt(uint8_t *c, const uint8_t *m, const uint32_t mlen) {
    uint8_t nonce[CSSNB];
    randombytes_buf(nonce, CSSNB);
    memcpy(c, nonce, CSSNB);
    return salsa208poly1305_encrypt(c + CSSNB, m, mlen, nonce, secret_key);
}
示例#9
0
int
rand_bytes(void *output, int len)
{
    randombytes_buf(output, len);
    // always return success
    return 0;
}
int encrypt(unsigned char* ciphertext, size_t* ciphertext_length, unsigned char* key) {
	unsigned char message[] = MESSAGE;
	printf("Message (%lu Bytes):\n%s\n\n", sizeof(message), message);

	//create random nonce
	unsigned char nonce[crypto_secretbox_NONCEBYTES];
	randombytes_buf(nonce, crypto_secretbox_NONCEBYTES);

	//print nonce
	printf("Nonce (%i Bytes):\n", crypto_secretbox_NONCEBYTES);
	print_hex(nonce, crypto_secretbox_NONCEBYTES, 30);
	putchar('\n');

	const unsigned char header[] = HEADER;
	printf("Header (%lu Bytes):\n%s\n\n", sizeof(header), header);

	int status = encrypt_message(
			ciphertext,
			ciphertext_length,
			message,
			sizeof(message),
			header,
			sizeof(header),
			nonce,
			key);
	sodium_memzero(message, sizeof(message));
	return status;
}
示例#11
0
文件: spud.c 项目: carriercomm/crypto
/*
* Function: generate_key_nonce
* ----------------------------
* Attempt to generate a key and nonce using the passphrase and the static salt
* values. If there are any errors then return -1 otherwise return 0.
*/
result
generate_key_nonce(unsigned char *key, unsigned char *nonce, char *passphrase)
{
    char *key_salt = "wJDNGf7/Jrce41GTllX+Z4I0eHdva+IXFsYiD5Sg50M";
    size_t r;

    r = crypto_pwhash_scryptsalsa208sha256(
        key,
        KEYBYTES,
        passphrase,
        strlen(passphrase),
        (unsigned char *)key_salt,
        crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_INTERACTIVE,
        crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_INTERACTIVE);

    if (r != 0)
    {
        fprintf(stderr, "Unable to generate key from passprase.\n");
        return FAIL;
    }

    randombytes_buf(nonce, NONCEBYTES);

    return SUCCESS;
}
示例#12
0
/* r = hash(B || empty_labelset || Z || pad1 || k || pad2 || empty_labelset || K || extra || M) (mod q) */
static void
_crypto_sign_ed25519_synthetic_r_hv(crypto_hash_sha512_state *hs,
                                    unsigned char Z[32],
                                    const unsigned char sk[64])
{
    static const unsigned char B[32] = {
        0x58, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
        0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
        0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
        0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
    };
    static const unsigned char zeros[16] = { 0x00 };
    static const unsigned char empty_labelset[3] = { 0x02, 0x00, 0x00 };

    crypto_hash_sha512_update(hs, B, 32);
    crypto_hash_sha512_update(hs, empty_labelset, 3);
    randombytes_buf(Z, 32);
    crypto_hash_sha512_update(hs, Z, 32);
    crypto_hash_sha512_update(hs, zeros, 16 - (32 + 3 + 32) % 16);
    crypto_hash_sha512_update(hs, sk, 32);
    /* empty pad2 */
    crypto_hash_sha512_update(hs, empty_labelset, 3);
    crypto_hash_sha512_update(hs, sk + 32, 32);
    /* empty extra */
}
示例#13
0
文件: auth5.c 项目: graydon/libsodium
int
main(void)
{
    size_t clen;

    for (clen = 0; clen < 1000; ++clen) {
        crypto_auth_keygen(key);
        randombytes_buf(c, clen);
        crypto_auth(a, c, clen, key);
        if (crypto_auth_verify(a, c, clen, key) != 0) {
            printf("fail %u\n", (unsigned int) clen);
            return 100;
        }
        if (clen > 0) {
            c[rand() % clen] += 1 + (rand() % 255);
            if (crypto_auth_verify(a, c, clen, key) == 0) {
                printf("forgery %u\n", (unsigned int) clen);
                return 100;
            }
            a[rand() % sizeof a] += 1 + (rand() % 255);
            if (crypto_auth_verify(a, c, clen, key) == 0) {
                printf("forgery %u\n", (unsigned int) clen);
                return 100;
            }
        }
    }

    crypto_auth_keygen(key);
    crypto_auth(a, guard_page, 0U, key);
    assert(crypto_auth_verify(a, guard_page, 0U, key) == 0);

    return 0;
}
示例#14
0
static void
mm_generichash(void)
{
    crypto_generichash_state st;
    unsigned char *h, *h2;
    unsigned char *k;
    unsigned char *m;
    size_t         hlen;
    size_t         klen;
    size_t         mlen;
    size_t         l1, l2;
    int            i;

    for (i = 0; i < MAX_ITER; i++) {
        mlen = randombytes_uniform(MAXLEN);
        m = (unsigned char *) sodium_malloc(mlen);
        klen = randombytes_uniform(crypto_generichash_KEYBYTES_MAX -
                                   crypto_generichash_KEYBYTES_MIN + 1U)
            + crypto_generichash_KEYBYTES_MIN;
        k = (unsigned char *) sodium_malloc(klen);
        hlen = randombytes_uniform(crypto_generichash_BYTES_MAX -
                                   crypto_generichash_BYTES_MIN + 1U)
            + crypto_generichash_BYTES_MIN;
        h = (unsigned char *) sodium_malloc(hlen);
        h2 = (unsigned char *) sodium_malloc(hlen);

        randombytes_buf(k, klen);
        randombytes_buf(m, mlen);

        crypto_generichash_init(&st, k, klen, hlen);
        l1 = randombytes_uniform(mlen);
        l2 = randombytes_uniform(mlen - l1);
        crypto_generichash_update(&st, m, l1);
        crypto_generichash_update(&st, m + l1, l2);
        crypto_generichash_update(&st, m + l1 + l2, mlen - l1 - l2);
        crypto_generichash_final(&st, h, hlen);

        crypto_generichash(h2, hlen, m, mlen, k, klen);

        assert(memcmp(h, h2, hlen) == 0);

        sodium_free(h2);
        sodium_free(h);
        sodium_free(k);
        sodium_free(m);
    }
}
int
crypto_box_curve25519xsalsa20poly1305_keypair(unsigned char *pk,
                                              unsigned char *sk)
{
    randombytes_buf(sk, 32);

    return crypto_scalarmult_curve25519_base(pk, sk);
}
int main(void) {
	sodium_init();

	//create random key
	unsigned char key[crypto_secretbox_KEYBYTES];
	randombytes_buf(key, crypto_secretbox_KEYBYTES);

	//print key
	printf("Key (%i Bytes):\n", crypto_secretbox_KEYBYTES);
	print_hex(key, crypto_secretbox_KEYBYTES, 30);
	putchar('\n');


	//encrypted message
	unsigned char ciphertext[500]; //TODO don't use fixed size buffer here

	size_t ciphertext_length = 0;
	int status;
	status = encrypt(ciphertext, &ciphertext_length, key);
	if (status != 0) {
		fprintf(stderr, "ERROR: Failed to encrypt message. (%i)\n", status);
		return status;
	}

	//print the ciphertext
	printf("Ciphertext (packet, %zu Bytes):\n", ciphertext_length);
	print_hex(ciphertext, ciphertext_length, 30);
	putchar('\n');

	puts("NOW DECRYPT -------------------------------------------------------------------\n");

	unsigned char header[ciphertext_length];

	size_t header_length = 0;

	status = extract_header_without_verifying(
			header,
			&header_length,
			ciphertext,
			ciphertext_length);
	if (status != 0) {
		fprintf(stderr, "ERROR: Failed to extract header from packet. (%i)\n", status);
		return status;
	}

	//print header
	printf("Received header (%zu Bytes):\n%s\n\n", header_length, header);

	//check header
	if (sodium_memcmp(header, HEADER, sizeof(HEADER)) != 0) {
		fprintf(stderr, "ERROR: Headers aren't the same!\n");
		return -1;
	}

	return EXIT_SUCCESS;
}
示例#17
0
int
crypto_kx_keypair(unsigned char pk[crypto_kx_PUBLICKEYBYTES],
                  unsigned char sk[crypto_kx_SECRETKEYBYTES])
{
    COMPILER_ASSERT(crypto_kx_SECRETKEYBYTES == crypto_scalarmult_SCALARBYTES);
    COMPILER_ASSERT(crypto_kx_PUBLICKEYBYTES == crypto_scalarmult_BYTES);

    randombytes_buf(sk, crypto_kx_SECRETKEYBYTES);
    return crypto_scalarmult_base(pk, sk);
}
示例#18
0
文件: crypto.c 项目: 11liju/ShadowVPN
int crypto_encrypt(unsigned char *c, unsigned char *m,
                   unsigned long long mlen) {
  unsigned char nonce[8];
  randombytes_buf(nonce, 8);
  int r = crypto_secretbox_salsa208poly1305(c, m, mlen + 32, nonce, key);
  if (r != 0) return r;
  // copy nonce to the head
  memcpy(c + 8, nonce, 8);
  return 0;
}
示例#19
0
int crypto_sign_keypair(unsigned char *pk, unsigned char *sk)
{
    unsigned char seed[32];
    int           ret;

    randombytes_buf(seed, sizeof seed);
    ret = crypto_sign_seed_keypair(pk, sk, seed);
    sodium_memzero(seed, sizeof seed);

    return ret;
}
示例#20
0
int main(void) {
	sodium_init();

	printf("HKDF as described in RFC 5869 based on HMAC-SHA512256!\n\n");

	unsigned char output_key[200];
	size_t output_key_length = sizeof(output_key);

	//create random salt
	unsigned char salt[crypto_auth_KEYBYTES];
	randombytes_buf(salt, crypto_auth_KEYBYTES);
	printf("Salt (%i Bytes):\n", crypto_auth_KEYBYTES);
	print_hex(salt, crypto_auth_KEYBYTES, 30);
	putchar('\n');

	//create key to derive from
	unsigned char input_key[100];
	size_t input_key_length = sizeof(input_key);
	randombytes_buf(input_key, input_key_length);
	printf("Input key (%zu Bytes):\n", input_key_length);
	print_hex(input_key, input_key_length, 30);
	putchar('\n');

	//info
	unsigned char* info = (unsigned char*) "This is some info!";
	size_t info_length = sizeof(info);
	printf("Info (%zu Bytes):\n", info_length); //this could also be binary data
	printf("%s\n\n", info);

	int status;
	status = hkdf(output_key, output_key_length, salt, input_key, input_key_length, info, info_length);
	if (status != 0) {
		fprintf(stderr, "ERROR: Failed to derive key. %i\n", status);
		return EXIT_FAILURE;
	}

	printf("Derived key (%zu Bytes):\n", output_key_length);
	print_hex(output_key, output_key_length, 30);
	putchar('\n');
	return EXIT_SUCCESS;
}
示例#21
0
int
crypto_pwhash_scryptsalsa208sha256_str(char out[crypto_pwhash_scryptsalsa208sha256_STRBYTES],
                                       const char * const passwd,
                                       unsigned long long passwdlen,
                                       unsigned long long opslimit,
                                       size_t memlimit)
{
    uint8_t         salt[crypto_pwhash_scryptsalsa208sha256_STRSALTBYTES];
    char            setting[crypto_pwhash_scryptsalsa208sha256_STRSETTINGBYTES + 1U];
    escrypt_local_t escrypt_local;
    uint32_t        N_log2;
    uint32_t        p;
    uint32_t        r;

    memset(out, 0, crypto_pwhash_scryptsalsa208sha256_STRBYTES);
    if (passwdlen > SIZE_MAX) {
        errno = EFBIG; /* LCOV_EXCL_LINE */
        return -1; /* LCOV_EXCL_LINE */
    }
    if (pickparams(opslimit, memlimit, &N_log2, &p, &r) != 0) {
        errno = EINVAL; /* LCOV_EXCL_LINE */
        return -1; /* LCOV_EXCL_LINE */
    }
    randombytes_buf(salt, sizeof salt);
    if (escrypt_gensalt_r(N_log2, r, p, salt, sizeof salt,
                          (uint8_t *) setting, sizeof setting) == NULL) {
        errno = EINVAL; /* LCOV_EXCL_LINE */
        return -1; /* LCOV_EXCL_LINE */
    }
    if (escrypt_init_local(&escrypt_local) != 0) {
        return -1; /* LCOV_EXCL_LINE */
    }
    if (escrypt_r(&escrypt_local, (const uint8_t *) passwd, (size_t) passwdlen,
                  (const uint8_t *) setting, (uint8_t *) out,
                  crypto_pwhash_scryptsalsa208sha256_STRBYTES) == NULL) {
        /* LCOV_EXCL_START */
        escrypt_free_local(&escrypt_local);
        errno = EINVAL;
        return -1;
        /* LCOV_EXCL_STOP */
    }
    escrypt_free_local(&escrypt_local);

    (void) sizeof
        (int[SETTING_SIZE(crypto_pwhash_scryptsalsa208sha256_STRSALTBYTES)
            == crypto_pwhash_scryptsalsa208sha256_STRSETTINGBYTES ? 1 : -1]);
    (void) sizeof
        (int[crypto_pwhash_scryptsalsa208sha256_STRSETTINGBYTES + 1U +
             crypto_pwhash_scryptsalsa208sha256_STRHASHBYTES_ENCODED + 1U
             == crypto_pwhash_scryptsalsa208sha256_STRBYTES ? 1 : -1]);

    return 0;
}
示例#22
0
文件: crypto.c 项目: turnage/Charl
/**
 *  Encrypt data without making it a packet.
 *  @src: source of the data
 *  @len: length of the data
 *  @pk: public key to encrypt the data for
 *  @sk: secret key to encrypt the data with
 *  @dest: destination for ciphertext, must be as big as len + PREFIX
 */
void crypto_encipher_data (const void *src, int len, const unsigned char *pek,
                           const unsigned char *sek, void *dest)
{
        unsigned char m[crypto_box_ZEROBYTES + len];

        memset(m, 0, crypto_box_ZEROBYTES + len);
        memset(dest, 0, PREFIX + len);
        memcpy(m + crypto_box_ZEROBYTES, src, len);
        randombytes_buf(dest, crypto_box_NONCEBYTES);

        crypto_box((unsigned char *)dest + crypto_box_NONCEBYTES, m,
                   crypto_box_ZEROBYTES + len, dest, pek, sek);
}
示例#23
0
int crypto_sign_edwards25519sha512batch_keypair(unsigned char *pk,
                                                unsigned char *sk)
{
    ge_p3 A;

    randombytes_buf(sk, 32);
    crypto_hash_sha512(sk, sk, 32);
    sk[0] &= 248;
    sk[31] &= 63;
    sk[31] |= 64;
    ge_scalarmult_base(&A, sk);
    ge_p3_tobytes(pk, &A);

    return 0;
}
示例#24
0
文件: sodium.cpp 项目: jedisct1/sdk
// Generates a new Ed25519 private key seed. The key seed is stored in the object.
int EdDSA::genKeySeed(unsigned char* privKey) {
    // Make space for a new key seed (if not present).
    if (!this->keySeed) {
        this->keySeed = (unsigned char*)sodium_malloc(crypto_sign_SEEDBYTES);
        if (this->keySeed == NULL) {
            // Something went wrong allocating the memory.
            return(0);
        }
    }
    // Now make the new key seed.
    randombytes_buf(this->keySeed, crypto_sign_SEEDBYTES);
    // Copy it to privKey before returning.
    if (privKey)
    {
        memcpy(privKey, this->keySeed, crypto_sign_SEEDBYTES);
    }
    return(1);
}
示例#25
0
QString ClientConfiguration::toBackup(QString const& password) const {
	QByteArray encryptionKey(BACKUP_ENCRYPTION_KEY_BYTES, 0x00);

	// Generate a Salt
	QByteArray salt(BACKUP_SALT_BYTES, 0x00);
	randombytes_buf(salt.data(), BACKUP_SALT_BYTES);

	// Convert the password into bytes
	QByteArray password8Bit = password.toUtf8();

	// Generate the encryption key for the Backup from the Salt and the Password
	PKCS5_PBKDF2_HMAC(reinterpret_cast<unsigned char*>(password8Bit.data()), password8Bit.size(), reinterpret_cast<unsigned char*>(salt.data()), BACKUP_SALT_BYTES, BACKUP_KEY_PBKDF_ITERATIONS, BACKUP_ENCRYPTION_KEY_BYTES, reinterpret_cast<unsigned char*>(encryptionKey.data()));

	QByteArray nonceBytes(crypto_stream_NONCEBYTES, 0x00);

	// The backup content
	QByteArray clientId(IdentityHelper::uint64ToIdentityString(getClientIdentity().getContactId()).toLatin1());
	if (clientId.size() != BACKUP_IDENTITY_BYTES) {
		throw InternalErrorException() << QString("Could not build backup - invalid client identity length (%1 vs. %2 Bytes).").arg(clientId.size()).arg(BACKUP_IDENTITY_BYTES).toStdString();
	}
	QByteArray clientSecKey(getClientLongTermKeyPair().getPrivateKey());
	if (clientSecKey.size() != PROTO_KEY_LENGTH_BYTES) {
		throw InternalErrorException() << QString("Could not build backup - invalid client secret key length (%1 vs. %2 Bytes).").arg(clientSecKey.size()).arg(PROTO_KEY_LENGTH_BYTES).toStdString();
	}

	QByteArray backup(salt);
	backup.append(clientId);
	backup.append(clientSecKey);

	// Compute Hash
	QByteArray controlHash(crypto_hash_sha256_BYTES, 0x00);
	crypto_hash_sha256(reinterpret_cast<unsigned char*>(controlHash.data()), reinterpret_cast<unsigned char*>(backup.data() + BACKUP_SALT_BYTES), BACKUP_IDENTITY_BYTES + PROTO_KEY_LENGTH_BYTES);
	backup.append(controlHash.left(BACKUP_HASH_BYTES));

	if (backup.size() != (BACKUP_SALT_BYTES + BACKUP_IDENTITY_BYTES + PROTO_KEY_LENGTH_BYTES + BACKUP_HASH_BYTES)) {
		throw InternalErrorException() << QString("Could not build backup - invalid packet length (%1 vs. %2 Bytes).").arg(clientSecKey.size()).arg(BACKUP_SALT_BYTES + BACKUP_IDENTITY_BYTES + PROTO_KEY_LENGTH_BYTES + BACKUP_HASH_BYTES).toStdString();
	}

	// The Backup is build from SALT + IDENTITY + KEY + HASH
	crypto_stream_xor(reinterpret_cast<unsigned char*>(backup.data() + BACKUP_SALT_BYTES), reinterpret_cast<unsigned char*>(backup.data() + BACKUP_SALT_BYTES), BACKUP_IDENTITY_BYTES + PROTO_KEY_LENGTH_BYTES + BACKUP_HASH_BYTES, reinterpret_cast<unsigned char*>(nonceBytes.data()), reinterpret_cast<unsigned char*>(encryptionKey.data()));

	// Encode in Base32
	return Base32::encodeBase32Sequence(backup);
}
示例#26
0
QString ClientConfiguration::generateRandomPassword(int length) {
	if (length <= 0) {
		return "";
	}

	QString result;
	result.reserve(length);

	for (int i = 0; i < length; ++i) {
		uint16_t value = 0;
		randombytes_buf(&value, sizeof(uint16_t));
		value = value % (26 + 26 + 10); // a-z, A-Z, 0-9
		if (value < 26) {
			result.append('A' + value);
		} else if (value < 52) {
			result.append('a' + (value - 26));
		} else {
			result.append('0' + (value - 52));
		}
	}
	return result;
}
示例#27
0
static void
mm_hmacsha256(void)
{
    crypto_auth_hmacsha256_state st;
    unsigned char *h, *h2;
    unsigned char *k;
    unsigned char *m;
    size_t         mlen;
    size_t         l1, l2;
    int            i;

    for (i = 0; i < MAX_ITER; i++) {
        mlen = randombytes_uniform(MAXLEN);
        m = (unsigned char *) sodium_malloc(mlen);
        k = (unsigned char *) sodium_malloc(crypto_auth_hmacsha256_KEYBYTES);
        h = (unsigned char *) sodium_malloc(crypto_auth_hmacsha256_BYTES);
        h2 = (unsigned char *) sodium_malloc(crypto_auth_hmacsha256_BYTES);

        crypto_auth_hmacsha256_keygen(k);
        randombytes_buf(m, mlen);

        crypto_auth_hmacsha256_init(&st, k, crypto_auth_hmacsha256_KEYBYTES);
        l1 = randombytes_uniform(mlen);
        l2 = randombytes_uniform(mlen - l1);
        crypto_auth_hmacsha256_update(&st, m, l1);
        crypto_auth_hmacsha256_update(&st, m + l1, l2);
        crypto_auth_hmacsha256_update(&st, m + l1 + l2, mlen - l1 - l2);
        crypto_auth_hmacsha256_final(&st, h);

        crypto_auth_hmacsha256(h2, m, mlen, k);

        assert(memcmp(h, h2, crypto_auth_hmacsha256_BYTES) == 0);

        sodium_free(h2);
        sodium_free(h);
        sodium_free(k);
        sodium_free(m);
    }
}
示例#28
0
void
randombytes(unsigned char * const buf, const unsigned long long buf_len)
{
    assert(buf_len <= SIZE_MAX);
    randombytes_buf(buf, (size_t) buf_len);
}
示例#29
0
void
crypto_auth_hmacsha512256_keygen(
    unsigned char k[crypto_auth_hmacsha512256_KEYBYTES])
{
    randombytes_buf(k, crypto_auth_hmacsha512256_KEYBYTES);
}
示例#30
0
static void
tv_stream_xchacha20(void)
{
    static const XChaCha20TV tvs[] = {
        { "79c99798ac67300bbb2704c95c341e3245f3dcb21761b98e52ff45b24f304fc4", "b33ffd3096479bcfbc9aee49417688a0a2554f8d95389419", "c6e9758160083ac604ef90e712ce6e75d7797590744e0cf060f013739c" },
        { "ddf7784fee099612c40700862189d0397fcc4cc4b3cc02b5456b3a97d1186173", "a9a04491e7bf00c3ca91ac7c2d38a777d88993a7047dfcc4", "2f289d371f6f0abc3cb60d11d9b7b29adf6bc5ad843e8493e928448d" },
        { "3d12800e7b014e88d68a73f0a95b04b435719936feba60473f02a9e61ae60682", "56bed2599eac99fb27ebf4ffcb770a64772dec4d5849ea2d", "a2c3c1406f33c054a92760a8e0666b84f84fa3a618f0" },
        { "5f5763ff9a30c95da5c9f2a8dfd7cc6efd9dfb431812c075aa3e4f32e04f53e4", "a5fa890efa3b9a034d377926ce0e08ee6d7faccaee41b771", "8a1a5ba898bdbcff602b1036e469a18a5e45789d0e8d9837d81a2388a52b0b6a0f51891528f424c4a7f492a8dd7bce8bac19fbdbe1fb379ac0" },
        { "eadc0e27f77113b5241f8ca9d6f9a5e7f09eee68d8a5cf30700563bf01060b4e", "a171a4ef3fde7c4794c5b86170dc5a099b478f1b852f7b64", "23839f61795c3cdbcee2c749a92543baeeea3cbb721402aa42e6cae140447575f2916c5d71108e3b13357eaf86f060cb" },
        { "91319c9545c7c804ba6b712e22294c386fe31c4ff3d278827637b959d3dbaab2", "410e854b2a911f174aaf1a56540fc3855851f41c65967a4e", "cbe7d24177119b7fdfa8b06ee04dade4256ba7d35ffda6b89f014e479faef6" },
        { "6a6d3f412fc86c4450fc31f89f64ed46baa3256ffcf8616e8c23a06c422842b6", "6b7773fce3c2546a5db4829f53a9165f41b08faae2fb72d5", "8b23e35b3cdd5f3f75525fc37960ec2b68918e8c046d8a832b9838f1546be662e54feb1203e2" },
        { "d45e56368ebc7ba9be7c55cfd2da0feb633c1d86cab67cd5627514fd20c2b391", "fd37da2db31e0c738754463edadc7dafb0833bd45da497fc", "47950efa8217e3dec437454bd6b6a80a287e2570f0a48b3fa1ea3eb868be3d486f6516606d85e5643becc473b370871ab9ef8e2a728f73b92bd98e6e26ea7c8ff96ec5a9e8de95e1eee9300c" },
        { "aface41a64a9a40cbc604d42bd363523bd762eb717f3e08fe2e0b4611eb4dcf3", "6906e0383b895ab9f1cf3803f42f27c79ad47b681c552c63", "a5fa7c0190792ee17675d52ad7570f1fb0892239c76d6e802c26b5b3544d13151e67513b8aaa1ac5af2d7fd0d5e4216964324838" },
        { "9d23bd4149cb979ccf3c5c94dd217e9808cb0e50cd0f67812235eaaf601d6232", "c047548266b7c370d33566a2425cbf30d82d1eaf5294109e", "a21209096594de8c5667b1d13ad93f744106d054df210e4782cd396fec692d3515a20bf351eec011a92c367888bc464c32f0807acd6c203a247e0db854148468e9f96bee4cf718d68d5f637cbd5a376457788e6fae90fc31097cfc" },
    };
    const XChaCha20TV *tv;
    char              *hex;
    unsigned char     *key;
    unsigned char     *nonce;
    unsigned char     *out;
    unsigned char     *out2;
    size_t             out_len;
    int                i;

    key = (unsigned char *) sodium_malloc(crypto_stream_xchacha20_KEYBYTES);
    nonce = (unsigned char *) sodium_malloc(crypto_stream_xchacha20_NONCEBYTES);
    out = (unsigned char *) sodium_malloc(XCHACHA20_OUT_MAX);
    for (i = 0; i < (sizeof tvs) / (sizeof tvs[0]); i++) {
        tv = &tvs[i];

        sodium_hex2bin(key, crypto_stream_xchacha20_KEYBYTES,
                       tv->key, strlen(tv->key), NULL, NULL, NULL);
        sodium_hex2bin(nonce, crypto_stream_xchacha20_NONCEBYTES,
                       tv->nonce, strlen(tv->nonce), NULL, NULL, NULL);
        sodium_hex2bin(out, XCHACHA20_OUT_MAX,
                       tv->out, strlen(tv->out), NULL, &out_len, NULL);
        out2 = (unsigned char *) sodium_malloc(out_len);
        crypto_stream_xchacha20(out2, out_len, nonce, key);
        assert(memcmp(out, out2, out_len) == 0);
        crypto_stream_xchacha20_xor(out2, out, out_len, nonce, key);
        assert(sodium_is_zero(out2, out_len));
        crypto_stream_xchacha20_xor_ic(out2, out, out_len, nonce, 0, key);
        assert(sodium_is_zero(out2, out_len));
        crypto_stream_xchacha20_xor_ic(out2, out, out_len, nonce, 1, key);
        assert(!sodium_is_zero(out2, out_len));
        crypto_stream_xchacha20_xor(out, out, out_len, nonce, key);
        assert(sodium_is_zero(out, out_len));
        sodium_free(out2);
    }

    out2 = (unsigned char *) sodium_malloc(0);
    crypto_stream_xchacha20(out2, 0, nonce, key);
    crypto_stream_xchacha20_xor(out2, out2, 0, nonce, key);
    crypto_stream_xchacha20_xor_ic(out2, out2, 0, nonce, 1, key);
    sodium_free(out2);
    sodium_free(out);

    out = (unsigned char *) sodium_malloc(64);
    out2 = (unsigned char *) sodium_malloc(128);
    randombytes_buf(out, 64);
    randombytes_buf(out2, 64);
    memcpy(out2 + 64, out, 64);
    crypto_stream_xchacha20_xor_ic(out, out, 64, nonce, 1, key);
    crypto_stream_xchacha20_xor(out2, out2, 128, nonce, key);
    assert(memcmp(out, out2 + 64, 64) == 0);
    sodium_free(out);
    sodium_free(out2);

    out = (unsigned char *) sodium_malloc(192);
    out2 = (unsigned char *) sodium_malloc(192);
    memset(out, 0, 192);
    memset(out2, 0, 192);
    crypto_stream_xchacha20_xor_ic(out2, out2, 192, nonce,
                                   (1ULL << 32) - 1ULL, key);
    crypto_stream_xchacha20_xor_ic(out, out, 64, nonce,
                                   (1ULL << 32) - 1ULL, key);
    crypto_stream_xchacha20_xor_ic(out + 64, out + 64, 64, nonce,
                                   (1ULL << 32), key);
    crypto_stream_xchacha20_xor_ic(out + 128, out + 128, 64, nonce,
                                   (1ULL << 32) + 1, key);
    assert(memcmp(out, out2, 192) == 0);
    hex = (char *) sodium_malloc(192 * 2 + 1);
    sodium_bin2hex(hex, 192 * 2 + 1, out, 192);
    printf("%s\n", hex);
    sodium_free(hex);
    sodium_free(out);
    sodium_free(out2);

    sodium_free(nonce);
    sodium_free(key);

    assert(crypto_stream_xchacha20_keybytes() == crypto_stream_xchacha20_KEYBYTES);
    assert(crypto_stream_xchacha20_noncebytes() == crypto_stream_xchacha20_NONCEBYTES);

    printf("tv_stream_xchacha20: ok\n");
}