/* * Encrypt a plaintext message using the mt19937 generator as keystream */ size_t encrypt( uint8_t *ctext[], const uint8_t ptext[], const size_t len) { size_t i; uint8_t *keystream; if (!random_prefix_len) random_prefix_len = 1 + (get_random_value() % 15); // Init MT19937 prng to a new seed password_token_reset(); keystream = malloc(len*sizeof(uint8_t)); if (NULL == keystream) return 0x00; *ctext = malloc((random_prefix_len + len)*sizeof(uint8_t)); if (NULL == *ctext) { free(keystream); return 0x00; } for (i = 0; i < random_prefix_len; i++) (*ctext)[i] = (uint8_t) get_random_value(); mt19937_init( &cipher_mt, cipher_mt.seed); for (i = 0; i < len; i++) keystream[i] = mt19937_get_value(&cipher_mt); xor_encode(&((*ctext)[random_prefix_len]), ptext, len, keystream, len); free(keystream); return random_prefix_len + len; }
/* * Decrypt a ciphertext message using the mt19937 generator as keystream */ unsigned int decrypt( uint8_t *ptext[], const uint8_t ctext[], const size_t len) { size_t i; uint8_t *keystream; // MT PRNG not init if (!token_init) return 0x01; keystream = malloc(len*sizeof(uint8_t)); if (NULL == keystream) return 0x01; *ptext = malloc((len - random_prefix_len)*sizeof(uint8_t)); if (NULL == ptext) { free(keystream); return 0x01; } mt19937_init( &cipher_mt, cipher_mt.seed); for (i = 0; i < len; i++) keystream[i] = mt19937_get_value(&cipher_mt); xor_encode(*ptext , ctext + random_prefix_len, len, keystream, len); free(keystream); return 0x00; }
int main(int argc, char *argv[]) { clock_t start, finish; FILE *in, *out; if (argc != 4) { fprintf(stderr, "Usage: xe <key> <input file name> <output file name>\n"); return EXIT_FAILURE; } in = fopen(argv[2], "rb"); out = fopen(argv[3], "wb"); if (in == NULL || out == NULL) { if (in != NULL) fclose(in); if (out != NULL) { fclose(out); remove(argv[3]); } fprintf(stderr, "One or more files can't be opened.\n"); return EXIT_FAILURE; } fprintf(stderr, "Encrypting...\t"); start = clock(); if (!xor_encode(atoi(argv[1]), in, out)) { perror("Unexpected error occured.\n" \ "Details of the last error (if any)"); return errno; } finish = clock(); fprintf(stderr, "done! (%g seconds)\n", (float)(finish - start) / CLOCKS_PER_SEC); return EXIT_SUCCESS; }