void Blowfish_expand0state(blf_ctx *c, const u_int8_t *key, u_int16_t keybytes) { u_int16_t i; u_int16_t j; u_int16_t k; u_int32_t temp; u_int32_t data[2]; j = 0; for (i = 0; i < BLF_N + 2; i++) { /* Extract 4 int8 to 1 int32 from keystream */ temp = Blowfish_stream2word(key, keybytes, &j); c->P[i] = c->P[i] ^ temp; } j = 0; data[0] = 0x00000000; data[1] = 0x00000000; for (i = 0; i < BLF_N + 2; i += 2) { Blowfish_encipher(c, data); c->P[i] = data[0]; c->P[i + 1] = data[1]; } for (i = 0; i < 4; i++) { for (k = 0; k < 256; k += 2) { Blowfish_encipher(c, data); c->S[i][k] = data[0]; c->S[i][k + 1] = data[1]; } } }
void Blowfish_expandstate(ssh_blf_ctx *c, const uint8_t *data, uint16_t databytes, const uint8_t *key, uint16_t keybytes) { uint16_t i; uint16_t j; uint16_t k; uint32_t temp; uint32_t datal; uint32_t datar; j = 0; for (i = 0; i < BLF_N + 2; i++) { /* Extract 4 int8 to 1 int32 from keystream */ temp = Blowfish_stream2word(key, keybytes, &j); c->P[i] = c->P[i] ^ temp; } j = 0; datal = 0x00000000; datar = 0x00000000; for (i = 0; i < BLF_N + 2; i += 2) { datal ^= Blowfish_stream2word(data, databytes, &j); datar ^= Blowfish_stream2word(data, databytes, &j); Blowfish_encipher(c, &datal, &datar); c->P[i] = datal; c->P[i + 1] = datar; } for (i = 0; i < 4; i++) { for (k = 0; k < 256; k += 2) { datal ^= Blowfish_stream2word(data, databytes, &j); datar ^= Blowfish_stream2word(data, databytes, &j); Blowfish_encipher(c, &datal, &datar); c->S[i][k] = datal; c->S[i][k + 1] = datar; } } }
static ERL_NIF_TERM bf_encrypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { ErlNifBinary state; uint32_t i, k, m; uint16_t j; uint8_t ciphertext[4 * BCRYPT_WORDS] = "OrpheanBeholderScryDoubt"; uint32_t cdata[BCRYPT_WORDS]; ERL_NIF_TERM encrypted[4 * BCRYPT_WORDS]; /* Initialize our data from argv */ if (argc != 1 || !enif_inspect_binary(env, argv[0], &state)) return enif_make_badarg(env); /* This can be precomputed later */ j = 0; for (i = 0; i < BCRYPT_WORDS; i++) cdata[i] = Blowfish_stream2word(ciphertext, 4 * BCRYPT_WORDS, &j); /* Now do the encryption */ for (k = 0; k < 64; k++) blf_enc((blf_ctx *) state.data, cdata, BCRYPT_WORDS / 2); for (i = 0; i < BCRYPT_WORDS; i++) { ciphertext[4 * i + 3] = cdata[i] & 0xff; cdata[i] = cdata[i] >> 8; ciphertext[4 * i + 2] = cdata[i] & 0xff; cdata[i] = cdata[i] >> 8; ciphertext[4 * i + 1] = cdata[i] & 0xff; cdata[i] = cdata[i] >> 8; ciphertext[4 * i + 0] = cdata[i] & 0xff; } for (m = 0; m < BCRYPT_HASHLEN; m++) { encrypted[m] = enif_make_uint(env, ciphertext[m]); } secure_bzero(state.data, state.size); enif_release_binary(&state); secure_bzero(ciphertext, sizeof(ciphertext)); secure_bzero(cdata, sizeof(cdata)); return enif_make_list_from_array(env, encrypted, BCRYPT_HASHLEN); }