/** * @brief Decipher a buffer using AES-128 with CBC. */ int crypt_aes_dec(crypt_context_t *context, char *encBuffer, char *outBuffer, unsigned int buffLen, char *iniVector) { int rv; ASSERT(context, rv, CRYPT_FAILED, "crypt_aes_dec: Argument is NULL.\n"); ASSERT(encBuffer, rv, CRYPT_FAILED, "crypt_aes_dec: Argument is NULL.\n"); ASSERT(outBuffer, rv, CRYPT_FAILED, "crypt_aes_dec: Argument is NULL.\n"); ASSERT(iniVector, rv, CRYPT_FAILED, "crypt_aes_dec: Argument is NULL.\n"); ASSERT(context->initialised, rv, CRYPT_FAILED, "crypt_aes_dec: Context is not initialised.\n"); gcry_error_t gcryError; gcry_cipher_hd_t gcryCipherHd = NULL; size_t keyLength = gcry_cipher_get_algo_keylen(GCRY_CIPHER_AES128); size_t blkLength = gcry_cipher_get_algo_blklen(GCRY_CIPHER_AES128); gcryError = gcry_cipher_open(&gcryCipherHd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CBC, 0); ASSERT(!gcryError, rv, CRYPT_FAILED, "crypt_aes_dec: %s: %s\n", gcry_strsource(gcryError), gcry_strerror(gcryError)); gcryError = gcry_cipher_setkey(gcryCipherHd, context->secretKey, keyLength); ASSERT(!gcryError, rv, CRYPT_FAILED, "crypt_aes_dec: %s: %s\n", gcry_strsource(gcryError), gcry_strerror(gcryError)); gcryError = gcry_cipher_setiv(gcryCipherHd, iniVector, blkLength); ASSERT(!gcryError, rv, CRYPT_FAILED, "crypt_aes_dec: %s: %s\n", gcry_strsource(gcryError), gcry_strerror(gcryError)); gcryError = gcry_cipher_decrypt(gcryCipherHd, outBuffer, buffLen, encBuffer, buffLen); ASSERT(!gcryError, rv, CRYPT_FAILED, "crypt_aes_dec: %s: %s\n", gcry_strsource(gcryError), gcry_strerror(gcryError)); _err: if(gcryCipherHd) gcry_cipher_close(gcryCipherHd); return rv; }
char* decrypt(char *private_key, char *ciphertext){ gcry_error_t error; gcry_sexp_t data = sexp_new(ciphertext); gcry_sexp_t private_sexp = sexp_new(private_key); gcry_sexp_t r_plain; struct timeval timer; timer_start(&timer); if ((error = gcry_pk_decrypt(&r_plain, data, private_sexp))) { printf("Error in gcry_pk_decrypt(): %s\nSource: %s\n", gcry_strerror(error), gcry_strsource(error)); exit(1); } timer_poll("\nSoftware decrypt: %d.%06d seconds\n", &timer); gcry_mpi_t r_mpi = gcry_sexp_nth_mpi(r_plain, 0, GCRYMPI_FMT_USG); unsigned char *plaintext; size_t plaintext_size; if ((error = gcry_mpi_aprint(GCRYMPI_FMT_HEX, &plaintext, &plaintext_size, r_mpi))) { printf("Error in gcry_mpi_aprint(): %s\nSource: %s\n", gcry_strerror(error), gcry_strsource(error)); exit(1); } // Return type hack return (char *) plaintext; }
void print_gcrypt_err(gcry_error_t err){ if ( err ) { fprintf ( stderr, "Failure: %s/%s\n", gcry_strsource ( err ), gcry_strerror ( err ) ); fprintf ( stdout, "Failure: %s/%s\n", gcry_strsource ( err ), gcry_strerror ( err ) ); } }
static int initCrypt(FILE *eifp) { int r = 0; gcry_error_t gcryError; char iv[4096]; blkLength = gcry_cipher_get_algo_blklen(cry_algo); if(blkLength > sizeof(iv)) { fprintf(stderr, "internal error[%s:%d]: block length %d too large for " "iv buffer\n", __FILE__, __LINE__, blkLength); r = 1; goto done; } if((r = eiGetIV(eifp, iv, blkLength)) != 0) goto done; size_t keyLength = gcry_cipher_get_algo_keylen(cry_algo); if(strlen(cry_key) != keyLength) { fprintf(stderr, "invalid key length; key is %u characters, but " "exactly %u characters are required\n", cry_keylen, keyLength); r = 1; goto done; } gcryError = gcry_cipher_open(&gcry_chd, cry_algo, cry_mode, 0); if (gcryError) { printf("gcry_cipher_open failed: %s/%s\n", gcry_strsource(gcryError), gcry_strerror(gcryError)); r = 1; goto done; } gcryError = gcry_cipher_setkey(gcry_chd, cry_key, keyLength); if (gcryError) { printf("gcry_cipher_setkey failed: %s/%s\n", gcry_strsource(gcryError), gcry_strerror(gcryError)); r = 1; goto done; } gcryError = gcry_cipher_setiv(gcry_chd, iv, blkLength); if (gcryError) { printf("gcry_cipher_setiv failed: %s/%s\n", gcry_strsource(gcryError), gcry_strerror(gcryError)); r = 1; goto done; } done: return r; }
char* encrypt(rsa_packet * packet, char *public_key, char *plaintext){ gcry_error_t error; gcry_mpi_t r_mpi; if ((error = gcry_mpi_scan(&r_mpi, GCRYMPI_FMT_HEX, plaintext, 0, NULL))) { printf("Error in gcry_mpi_scan() in encrypt(): %s\nSource: %s\n", gcry_strerror(error), gcry_strsource(error)); exit(1); } gcry_sexp_t data; size_t erroff; if ((error = gcry_sexp_build(&data, &erroff, "(data (flags raw) (value %m))", r_mpi))) { printf("Error in gcry_sexp_build() in encrypt() at %ld: %s\nSource: %s\n", erroff, gcry_strerror(error), gcry_strsource(error)); exit(1); } gcry_sexp_t public_sexp = sexp_new(public_key); gcry_sexp_t r_ciph; struct timeval timer; timer_start(&timer); if ((error = gcry_pk_encrypt(&r_ciph, data, public_sexp))) { printf("Error in gcry_pk_encrypt(): %s\nSource: %s\n", gcry_strerror(error), gcry_strsource(error)); exit(1); } timer_poll("\nSoftware encrypt: %d.%06d seconds\n", &timer); gcry_sexp_t cipher_sexp = gcry_sexp_cdr(gcry_sexp_find_token(r_ciph, "a", 1)); gcry_mpi_t cipher_mpi = gcry_sexp_nth_mpi(cipher_sexp, 0, GCRYMPI_FMT_USG); gcry_mpi_print(GCRYMPI_FMT_USG, packet->ciphertext, 256, &packet->cipher_len, cipher_mpi); return sexp_string(r_ciph); }
/* * Load instance tags. */ static void instag_load(struct otr_user_state *ustate) { int ret; char *filename; gcry_error_t err; assert(ustate); /* Getting the otr instance filename path */ ret = asprintf(&filename, "%s%s", get_client_config_dir(), OTR_INSTAG_FILE); if (ret < 0) { goto error_filename; } ret = access(filename, F_OK); if (ret < 0) { IRSSI_DEBUG("no instance tags found at %9%s%9", filename); goto end; } err = otrl_instag_read(ustate->otr_state, filename); if (err == GPG_ERR_NO_ERROR) { IRSSI_DEBUG("Instance tags loaded from %9%s%9", filename); } else { IRSSI_DEBUG("Error loading instance tags: %d (%d)", gcry_strerror(err), gcry_strsource(err)); } end: free(filename); error_filename: return; }
char* sign(char *private_key, char *document){ gcry_error_t error; gcry_mpi_t r_mpi; if ((error = gcry_mpi_scan(&r_mpi, GCRYMPI_FMT_HEX, document, 0, NULL))) { printf("Error in gcry_mpi_scan() in encrypt(): %s\nSource: %s\n", gcry_strerror(error), gcry_strsource(error)); exit(1); } gcry_sexp_t data; size_t erroff; if ((error = gcry_sexp_build(&data, &erroff, "(data (flags raw) (value %m))", r_mpi))) { printf("Error in gcry_sexp_build() in sign() at %ld: %s\nSource: %s\n", erroff, gcry_strerror(error), gcry_strsource(error)); exit(1); } gcry_sexp_t private_sexp = sexp_new(private_key); gcry_sexp_t r_sig; struct timeval timer; timer_start(&timer); if ((error = gcry_pk_sign(&r_sig, data, private_sexp))) { printf("Error in gcry_pk_sign(): %s\nSource: %s\n", gcry_strerror(error), gcry_strsource(error)); exit(1); } timer_poll("libgcrypt Sign: %d.%06d seconds\n", &timer); return sexp_string(r_sig); }
short verify(char *public_key, char *document, char *signature){ gcry_error_t error; gcry_mpi_t r_mpi; if ((error = gcry_mpi_scan(&r_mpi, GCRYMPI_FMT_HEX, document, 0, NULL))) { printf("Error in gcry_mpi_scan() in encrypt(): %s\nSource: %s\n", gcry_strerror(error), gcry_strsource(error)); exit(1); } gcry_sexp_t data; size_t erroff; if ((error = gcry_sexp_build(&data, &erroff, "(data (flags raw) (value %m))", r_mpi))) { printf("Error in gcry_sexp_build() in sign() at %ld: %s\nSource: %s\n", erroff, gcry_strerror(error), gcry_strsource(error)); exit(1); } gcry_sexp_t sig = sexp_new(signature); gcry_sexp_t public_sexp = sexp_new(public_key); short good_sig = 1; struct timeval timer; timer_start(&timer); if ((error = gcry_pk_verify(sig, data, public_sexp))) { if (gcry_err_code(error) != GPG_ERR_BAD_SIGNATURE) { printf("Error in gcry_pk_verify(): %s\nSource: %s\n", gcry_strerror(error), gcry_strsource(error)); exit(1); } good_sig = 0; } timer_poll("libgcrypt Verify: %d.%06d seconds\n", &timer); return good_sig; }
void print_gcry_error(const char* message, const gcry_error_t* error) { printf("%s: [%d] %s - %s\n", message, gcry_err_code(*error), gcry_strerror(*error), gcry_strsource(*error)); }
/* Read the block begin metadata and set our state variables accordingly. Can also * be used to init the first block in write case. */ static rsRetVal rsgcryBlkBegin(gcryfile gf) { gcry_error_t gcryError; uchar *iv = NULL; DEFiRet; const char openMode = gf->openMode; gcryError = gcry_cipher_open(&gf->chd, gf->ctx->algo, gf->ctx->mode, 0); if (gcryError) { DBGPRINTF("gcry_cipher_open failed: %s/%s\n", gcry_strsource(gcryError), gcry_strerror(gcryError)); ABORT_FINALIZE(RS_RET_ERR); } gcryError = gcry_cipher_setkey(gf->chd, gf->ctx->key, gf->ctx->keyLen); if (gcryError) { DBGPRINTF("gcry_cipher_setkey failed: %s/%s\n", gcry_strsource(gcryError), gcry_strerror(gcryError)); ABORT_FINALIZE(RS_RET_ERR); } if(openMode == 'r') { readIV(gf, &iv); readBlkEnd(gf); } else { seedIV(gf, &iv); } gcryError = gcry_cipher_setiv(gf->chd, iv, gf->blkLength); if (gcryError) { DBGPRINTF("gcry_cipher_setiv failed: %s/%s\n", gcry_strsource(gcryError), gcry_strerror(gcryError)); ABORT_FINALIZE(RS_RET_ERR); } if(openMode == 'w') { CHKiRet(eiOpenAppend(gf)); CHKiRet(eiWriteIV(gf, iv)); } finalize_it: free(iv); RETiRet; }
/*-------------------[ Std. HASH ]-------------------------------------*/ static tree_cell * nasl_gcrypt_hash (lex_ctxt * lexic, int algorithm, void *data, size_t datalen, void *key, size_t keylen) { gcry_md_hd_t hd; gcry_error_t err; tree_cell *retc; int dlen = gcry_md_get_algo_dlen (algorithm); if (data == NULL) return NULL; err = gcry_md_open (&hd, algorithm, key ? GCRY_MD_FLAG_HMAC : 0); if (err) { nasl_perror (lexic, "nasl_gcrypt_hash(): gcry_md_open failed: %s/%s\n", gcry_strsource (err), gcry_strerror (err)); return NULL; } if (key) { err = gcry_md_setkey (hd, key, keylen); if (err) { nasl_perror (lexic, "nasl_gcrypt_hash():" " gcry_md_setkey failed: %s/%s\n", gcry_strsource (err), gcry_strerror (err)); return NULL; } } gcry_md_write (hd, data, datalen); retc = alloc_tree_cell (0, NULL); retc->type = CONST_DATA; retc->x.str_val = g_memdup (gcry_md_read (hd, algorithm), dlen + 1); retc->size = dlen; gcry_md_close (hd); return retc; }
//------------------------------------------------------------------------------ fnd::string dump_gcry_error_t(gcry_error_t err) { const char *msg = gcry_strerror(err); if(!msg) return "Failed to fetch error description"; const char *src = gcry_strsource(err); if(!src) return msg; return fmt::to_string(src, ": ", msg); }
gcry_sexp_t sexp_new(const char *str) { gcry_error_t error; gcry_sexp_t sexp; size_t len = strlen(str); if ((error = gcry_sexp_new(&sexp, str, len, 1))) { printf("Error in sexp_new(%s): %s\nSource: %s\n", str, gcry_strerror(error), gcry_strsource(error)); exit(1); } return sexp; }
rsRetVal rsgcryEncrypt(gcryfile pF, uchar *buf, size_t *len) { int gcryError; DEFiRet; if(*len == 0) FINALIZE; addPadding(pF, buf, len); gcryError = gcry_cipher_encrypt(pF->chd, buf, *len, NULL, 0); if(gcryError) { dbgprintf("gcry_cipher_encrypt failed: %s/%s\n", gcry_strsource(gcryError), gcry_strerror(gcryError)); ABORT_FINALIZE(RS_RET_ERR); } finalize_it: RETiRet; }
/* TODO: handle multiple blocks * test-read END record; if present, store offset, else unbounded (current active block) * when decrypting, check if bound is reached. If yes, split into two blocks, get new IV for * second one. */ rsRetVal rsgcryDecrypt(gcryfile pF, uchar *buf, size_t *len) { gcry_error_t gcryError; DEFiRet; if(pF->bytesToBlkEnd != -1) pF->bytesToBlkEnd -= *len; gcryError = gcry_cipher_decrypt(pF->chd, buf, *len, NULL, 0); if(gcryError) { DBGPRINTF("gcry_cipher_decrypt failed: %s/%s\n", gcry_strsource(gcryError), gcry_strerror(gcryError)); ABORT_FINALIZE(RS_RET_ERR); } removePadding(buf, len); // TODO: remove dbgprintf once things are sufficently stable -- rgerhards, 2013-05-16 dbgprintf("libgcry: decrypted, bytesToBlkEnd %lld, buffer is now '%50.50s'\n", (long long) pF->bytesToBlkEnd, buf); finalize_it: RETiRet; }
static void decryptBlock(FILE *fpin, FILE *fpout, off64_t blkEnd, off64_t *pCurrOffs) { gcry_error_t gcryError; size_t nRead, nWritten; size_t toRead; size_t leftTillBlkEnd; char buf[64*1024]; leftTillBlkEnd = blkEnd - *pCurrOffs; while(1) { toRead = sizeof(buf) <= leftTillBlkEnd ? sizeof(buf) : leftTillBlkEnd; toRead = toRead - toRead % blkLength; nRead = fread(buf, 1, toRead, fpin); if(nRead == 0) break; leftTillBlkEnd -= nRead, *pCurrOffs += nRead; gcryError = gcry_cipher_decrypt( gcry_chd, // gcry_cipher_hd_t buf, // void * nRead, // size_t NULL, // const void * 0); // size_t if (gcryError) { fprintf(stderr, "gcry_cipher_decrypt failed: %s/%s\n", gcry_strsource(gcryError), gcry_strerror(gcryError)); return; } removePadding(buf, &nRead); nWritten = fwrite(buf, 1, nRead, fpout); if(nWritten != nRead) { perror("fpout"); return; } } }
void generate_key(rsa_packet * packet, char **public_key, char **private_key) { gcry_error_t error; int i; // Generate a reduced strength (to save time) RSA key, 1024 bits long // gcry_sexp_t params = sexp_new( "(genkey (rsa (transient-key) (nbits 3:512)))" ); gcry_sexp_t params = sexp_new( "(genkey (rsa (transient-key) (nbits 4:1024)))" ); gcry_sexp_t r_key; if ((error = gcry_pk_genkey(&r_key, params))) { printf("Error in gcry_pk_genkey(): %s\nSource: %s\n", gcry_strerror(error), gcry_strsource(error)); exit(1); } // Parse the S expression strings gcry_sexp_t public_sexp = gcry_sexp_nth(r_key, 1); gcry_sexp_t private_sexp = gcry_sexp_nth(r_key, 2); gcry_sexp_t mod_sexp = gcry_sexp_cdr(gcry_sexp_find_token(private_sexp, "n", 1)); gcry_sexp_t priv_exp_sexp = gcry_sexp_cdr(gcry_sexp_find_token(private_sexp, "d", 1)); gcry_sexp_t pub_exp_sexp = gcry_sexp_cdr(gcry_sexp_find_token(public_sexp, "e", 1)); // Extract the raw data in MPI format gcry_mpi_t mod_mpi, pubexp_mpi, privexp_mpi; mod_mpi = gcry_sexp_nth_mpi(mod_sexp, 0, GCRYMPI_FMT_USG); privexp_mpi = gcry_sexp_nth_mpi(priv_exp_sexp, 0, GCRYMPI_FMT_USG); pubexp_mpi = gcry_sexp_nth_mpi(pub_exp_sexp, 0, GCRYMPI_FMT_USG); //gcry_mpi_aprint(GCRYMPI_FMT_HEX, public_key, NULL, mod_mpi); // Now pack it into unsigned char gcry_mpi_print(GCRYMPI_FMT_USG, packet->mod, 256, &packet->mod_len, mod_mpi); gcry_mpi_print(GCRYMPI_FMT_USG, packet->priv_exp, 256, &packet->priv_len, privexp_mpi); gcry_mpi_print(GCRYMPI_FMT_USG, packet->pub_exp, 256, &packet->pub_len, pubexp_mpi); // printf ("fmt: %i: %.*s\n", (int)len, (int) len, ); *public_key = sexp_string(public_sexp); *private_key = sexp_string(private_sexp); }
int decrypt_network_file(char *fname, unsigned char *key, size_t keysize, unsigned char * cipher_text, int file_len) { /* Decrypt network data */ FILE *ofd; size_t l = 16; // too many bufferses unsigned char in_buffer[l]; unsigned char out_buffer[l]; unsigned char tmp_buffer[l]; unsigned char * plain_text; // Mac initial vector char *iv; iv = (char *) malloc(16); memset(iv,0,16); *iv = 0x16d4; int i,j,k,c; int count; // ope the file for output ofd = (FILE *) fopen(fname,"w"); // set up gcrypt variables gcry_error_t err; gcry_cipher_hd_t hd; gcry_cipher_hd_t hd_mac; // set up hmac err = gcry_md_open (&hd_mac, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC); err = gcry_md_setkey (hd_mac, key, keysize); // set up aes err = gcry_cipher_open (&hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CBC, 0); if (err) printf("Failed to open cypher: %s - %s\n", gcry_strsource(err), gcry_strerror(err)); err = gcry_cipher_setkey (hd, key, keysize); if (err) printf("Failed to set key: %s - %s\n", gcry_strsource(err), gcry_strerror(err)); // Get our buffer for our plain text plain_text = (unsigned char *) malloc(file_len*sizeof(unsigned char)); // This is for making sure we can identify the last block... // or it was before I fixed it. int first = TRUE; // This is just to make the code a little easier to read int step; // Number of iterations count = file_len/l - 64/l; for(i = 0; i < count; ++i) { for(j = 0; j < l; ++j) { step = i*l + j; in_buffer[j] = cipher_text[step]; } // Encryption and HMAC err = gcry_cipher_setiv (hd, iv, 16); if (err) printf("Failed to set iv: %s - %s\n", gcry_strsource(err), gcry_strerror(err)); err = gcry_cipher_decrypt (hd, tmp_buffer, l, in_buffer, l); if (err) printf("Failed to decrypt: %s - %s\n", gcry_strsource(err), gcry_strerror(err)); gcry_md_write (hd_mac, in_buffer, l); if (first == TRUE) { // I don't remember why I had it set up like this // but there was a reason... first = FALSE; for (k = 0; k < l; ++k) out_buffer[k] = tmp_buffer[k]; } else { fwrite(out_buffer,1,l,ofd); for (k = 0; k < l; ++k) out_buffer[k] = tmp_buffer[k]; } } // Drop the padding c = 0; for (i=0;i<l;++i) { if(out_buffer[i] != 0) { c += 1; } } c+=1; fwrite(out_buffer,1,c,ofd); //gcry_cipher_close(hd); // compare the MACs unsigned char *mac_buffer_check; unsigned char *mac_buffer; mac_buffer = (unsigned char *)malloc(64); mac_buffer_check = gcry_md_read (hd_mac, GCRY_MD_SHA512); i = (count+1)*l; for(j = 0; j < 64; ++j) { mac_buffer[j] = cipher_text[i+j]; } int check = memcmp(mac_buffer,mac_buffer_check,63); if (check != 0 ) { // 1f y0u 4r3 h3r3 y0U h4v3 b33n h4x0red! printf("HMAC Verification Failed!\n"); return 62; } // Uber cyber ninja printf("Successfully Decrypted File\n"); fclose(ofd); return 0; }
int encrypt_file(char *fname, char *ofname, unsigned char *key, size_t keysize) { /* Encrypt a file in stand alone mode */ FILE *ifd; FILE *ofd; size_t l = 16; // Buffers buffer buffers unsigned char in_buffer[l]; unsigned char out_buffer[l]; unsigned char *mac_buffer; // This took forever to get figured out! // It really pissed me off char *iv; iv = (char *) malloc(16); memset(iv,0,16); *iv = 0x16d4; int i; int c; ifd = (FILE *) fopen(fname,"r"); ofd = (FILE *) fopen(ofname,"w"); /* Setup the encryption information */ gcry_error_t err; gcry_cipher_hd_t hd; gcry_cipher_hd_t hd_mac; // Needs more error checking... // This is the HMAC stuff err = gcry_md_open (&hd_mac, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC); err = gcry_md_setkey (hd_mac, key, keysize); // setup the encryption stuff err = gcry_cipher_open (&hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CBC, 0); if (err) printf("Failed to open cypher: %s - %s\n", gcry_strsource(err), gcry_strerror(err)); // set the key... now I am just being too obvious err = gcry_cipher_setkey (hd, key, keysize); if (err) printf("Failed to set key: %s - %s\n", gcry_strsource(err), gcry_strerror(err)); /* Encrypt the file */ while (!feof(ifd) && !ferror(ifd)) { c = fread(in_buffer,1,l,ifd); if (c < l) { for (i=c;i<l;++i) { in_buffer[i] = 0; } } // I didn't realize at first that you had to do // this every single time.... err = gcry_cipher_setiv (hd, iv, 16); if (err) printf("Failed to set iv: %s - %s\n", gcry_strsource(err), gcry_strerror(err)); err = gcry_cipher_encrypt (hd, out_buffer, l, in_buffer, l); if (err) printf("Failed to encrypt: %s - %s\n", gcry_strsource(err), gcry_strerror(err)); gcry_md_write (hd_mac, out_buffer, l); /* Output encrypted data */ fwrite(out_buffer,1,l,ofd); } // Get the MAC info and save it to the end of the output mac_buffer = gcry_md_read (hd_mac, GCRY_MD_SHA512); fwrite(mac_buffer,1,64,ofd); //These kept segfaulting... my fault? //gcry_cipher_close(hd); //gcry_mac_close (hd_mac); fclose(ofd); return 0; }
int main(int argc, char *argv[]) { int lflag = 0; int dflag = 0; int c; opterr = 0; while ((c = getopt(argc, argv, "dl")) != -1) switch (c) { case 'd': dflag = 1; break; case 'l': lflag = 1; break; case '?': if (isprint (optopt)) fprintf(stderr, "Unknown option `-%c'.\n", optopt); else fprintf(stderr, "Unknown option character `\\x%x'.\n", optopt); return 1; default: exit(EXIT_FAILURE); } if (dflag || lflag) { gcry_err_code_t err = 0; gcry_cipher_hd_t gchandle; const int blks = gcry_cipher_get_algo_blklen(GCRY_CIPHER_AES256); const int keyl = gcry_cipher_get_algo_keylen(GCRY_CIPHER_AES256); long outfileSize = 0; char key[keyl]; const char* salt = "iuyjdbnbtaqonbgt"; //open output file char outfile[256]; strcpy(outfile, argv[optind]); strncat(outfile, ".uf\0", 4); FILE *fout = fopen(outfile, "r"); if (!fout) { //printf("output file name : %s\n", outfile); fout = fopen(outfile, "w"); } else { printf("Output file already exist on disk.\n"); exit(EXIT_FAILURE); } char password[100]; do { printf("Please enter password between 8-20 chars :"); scanf("%s", password); } while (strlen(password) > 20 || strlen(password) < 8); err = gcry_kdf_derive(password, strlen(password), GCRY_KDF_PBKDF2, GCRY_MD_SHA256, salt, strlen(salt), 937, keyl, key); if (err) { fprintf(stderr, "Failure: %s/%s\n", gcry_strsource(err), gcry_strerror(err)); exit(EXIT_FAILURE); } char ctext[blks]; char *iv = "1234567890123456"; fwrite(iv, 1, blks, fout); outfileSize += blks; // Encryption Algo ----> start err = gcry_cipher_open(&gchandle, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC, 0); if (err) { fprintf(stderr, "Failure: %s/%s\n", gcry_strsource(err), gcry_strerror(err)); exit(EXIT_FAILURE); } err = gcry_cipher_setkey(gchandle, key, keyl); if (err) { fprintf(stderr, "Failure: %s/%s\n", gcry_strsource(err), gcry_strerror(err)); exit(EXIT_FAILURE); } err = gcry_cipher_setiv(gchandle, iv, blks); if (err) { fprintf(stderr, "Failure: %s/%s\n", gcry_strsource(err), gcry_strerror(err)); exit(EXIT_FAILURE); } FILE *finp = fopen(argv[optind], "r"); if (!finp) { printf("Could not open text file\n"); } else { int x = 0; char plaintext[blks]; while ((x = fread(plaintext, 1, blks, finp))) { if (x < blks) { // add padding to last block fseek(finp, 0, SEEK_END); for (; x < blks; x++) { plaintext[x] = '$'; fputc('$', finp); } } err = gcry_cipher_encrypt(gchandle, ctext, blks, plaintext, x); if (err && x == blks) { fprintf(stderr, "Failure: %s/%s\n", gcry_strsource(err), gcry_strerror(err)); fclose(finp); fclose(fout); exit(EXIT_FAILURE); } fwrite(ctext, 1, blks, fout); outfileSize += blks; } gcry_cipher_close(gchandle); fclose(fout); //generating HMAC fout = fopen(outfile, "r+"); fseek(fout, 0, SEEK_SET); unsigned char *hmacBuffer = malloc(outfileSize + 1); fread(hmacBuffer, 1, outfileSize, fout); fseek(fout, 0, SEEK_END); fclose(fout); gcry_md_hd_t hd; err = gcry_md_open(&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC); if (err) { fprintf(stderr, "Failure: %s/%s\n", gcry_strsource(err), gcry_strerror(err)); fclose(finp); fclose(fout); exit(EXIT_FAILURE); } err = gcry_md_setkey(hd, key, keyl); if (err) { fprintf(stderr, "Failure: %s/%s\n", gcry_strsource(err), gcry_strerror(err)); fclose(finp); fclose(fout); exit(EXIT_FAILURE); } err = gcry_md_enable(hd, GCRY_MD_SHA256); if (err) { fprintf(stderr, "Failure: %s/%s\n", gcry_strsource(err), gcry_strerror(err)); fclose(finp); fclose(fout); exit(EXIT_FAILURE); } gcry_md_write(hd, hmacBuffer, outfileSize); char thmac[keyl]; unsigned char *hmac = thmac; hmac = gcry_md_read(hd, GCRY_MD_SHA256); //printf("%s\n",hmac); //writing file contents as hmac(32 byte) + iv(16 byte) + cipher fout = fopen(outfile, "w"); fwrite(hmac, 1, keyl, fout); fwrite(hmacBuffer, 1, outfileSize, fout); gcry_md_close(hd); fclose(finp); fclose(fout); free(hmacBuffer); // Encryption Algo ----> end } /* Transferring file over ip */ if (dflag) { int client_socket; ssize_t len; struct sockaddr_in server_addr; int fd; int sent_bytes = 0; char file_size[256]; struct stat file_stat; int offset; int remain_data; char ip[15], port[4]; int i = 0, j = 0; for (; argv[optind + 1][i] != ':'; i++) { ip[i] = argv[optind + 1][i]; } i++; for (; i < strlen(argv[optind + 1]); i++, j++) { port[j] = argv[optind + 1][i]; } /* Create client socket */ client_socket = socket(AF_INET, SOCK_STREAM, 0); if (client_socket == -1) { fprintf(stderr, "Error creating socket --> %s", strerror(errno)); exit(EXIT_FAILURE); } /* Zeroing server_addr struct */ memset(&server_addr, 0, sizeof(server_addr)); /* Construct server_addr struct */ server_addr.sin_family = AF_INET; inet_pton(AF_INET, ip, &(server_addr.sin_addr)); server_addr.sin_port = htons(atoi(port)); /* Connect to the server */ if (connect(client_socket, (struct sockaddr *) &server_addr, sizeof(struct sockaddr)) == -1) { fprintf(stderr, "Error on connect --> %s\n", strerror(errno)); exit(EXIT_FAILURE); } fd = open(outfile, O_RDONLY); if (fd == -1) { fprintf(stderr, "Error opening file --> %s", strerror(errno)); exit(EXIT_FAILURE); } /* Get file stats */ if (fstat(fd, &file_stat) < 0) { fprintf(stderr, "Error fstat --> %s", strerror(errno)); exit(EXIT_FAILURE); } fprintf(stdout, "File Size: \n%ld bytes\n", file_stat.st_size); sprintf(file_size, "%d", file_stat.st_size); /* Sending file size */ len = send(client_socket, file_size, sizeof(file_size), 0); if (len < 0) { fprintf(stderr, "Error on sending greetings --> %s", strerror(errno)); exit(EXIT_FAILURE); } fprintf(stdout, "Client sent %ld bytes for the size\n", len); /* Sending file name */ len = send(client_socket, outfile, sizeof(outfile), 0); if (len < 0) { fprintf(stderr, "Error on sending greetings --> %s", strerror(errno)); exit(EXIT_FAILURE); } fprintf(stdout, "Client sent %ld bytes for the filename: %s\n", len, outfile); offset = 0; remain_data = file_stat.st_size; /* Sending file data */ while (((sent_bytes = sendfile(client_socket, fd, &offset, BUFSIZ)) > 0) && (remain_data > 0)) { fprintf(stdout, "1. Client sent %d bytes from file's data, offset is now : %d and remaining data = %d\n", sent_bytes, offset, remain_data); remain_data -= sent_bytes; fprintf(stdout, "2. Client sent %d bytes from file's data, offset is now : %d and remaining data = %d\n", sent_bytes, offset, remain_data); } close(client_socket); } } return EXIT_SUCCESS; }
int main(int argc, char **argv) { gcry_error_t gcry_error; File filein = 0; File fileout = 0; MY_INIT(argv[0]); if (get_options(&argc, &argv)) { goto err; } /* Acording to gcrypt docs (and my testing), setting up the threading callbacks must be done first, so, lets give it a shot */ gcry_error = gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread); if (gcry_error) { msg("%s: unable to set libgcrypt thread cbs - " "%s : %s\n", my_progname, gcry_strsource(gcry_error), gcry_strerror(gcry_error)); return 1; } /* Version check should be the very first call because it makes sure that important subsystems are intialized. */ if (!gcry_control(GCRYCTL_ANY_INITIALIZATION_P)) { const char *gcrypt_version; gcrypt_version = gcry_check_version(NULL); /* No other library has already initialized libgcrypt. */ if (!gcrypt_version) { msg("%s: failed to initialize libgcrypt\n", my_progname); return 1; } else if (opt_verbose) { msg("%s: using gcrypt %s\n", my_progname, gcrypt_version); } } gcry_control(GCRYCTL_DISABLE_SECMEM, 0); gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0); /* Determine the algorithm */ encrypt_algo = encrypt_algos[opt_encrypt_algo]; /* Set up the iv length */ encrypt_iv_len = gcry_cipher_get_algo_blklen(encrypt_algo); /* Now set up the key */ if (opt_encrypt_key == NULL && opt_encrypt_key_file == NULL) { msg("%s: no encryption key or key file specified.\n", my_progname); return 1; } else if (opt_encrypt_key && opt_encrypt_key_file) { msg("%s: both encryption key and key file specified.\n", my_progname); return 1; } else if (opt_encrypt_key_file) { if (!xb_crypt_read_key_file(opt_encrypt_key_file, &opt_encrypt_key, &encrypt_key_len)) { msg("%s: unable to read encryption key file \"%s\".\n", opt_encrypt_key_file, my_progname); return 1; } } else { encrypt_key_len = strlen(opt_encrypt_key); } if (opt_input_file) { MY_STAT mystat; if (opt_verbose) msg("%s: input file \"%s\".\n", my_progname, opt_input_file); if (my_stat(opt_input_file, &mystat, MYF(MY_WME)) == NULL) { goto err; } if (!MY_S_ISREG(mystat.st_mode)) { msg("%s: \"%s\" is not a regular file, exiting.\n", my_progname, opt_input_file); goto err; } if ((filein = my_open(opt_input_file, O_RDONLY, MYF(MY_WME))) < 0) { msg("%s: failed to open \"%s\".\n", my_progname, opt_input_file); goto err; } } else { if (opt_verbose) msg("%s: input from standard input.\n", my_progname); filein = fileno(stdin); } if (opt_output_file) { if (opt_verbose) msg("%s: output file \"%s\".\n", my_progname, opt_output_file); if ((fileout = my_create(opt_output_file, 0, O_WRONLY|O_BINARY|O_EXCL|O_NOFOLLOW, MYF(MY_WME))) < 0) { msg("%s: failed to create output file \"%s\".\n", my_progname, opt_output_file); goto err; } } else { if (opt_verbose) msg("%s: output to standard output.\n", my_progname); fileout = fileno(stdout); } if (opt_run_mode == RUN_MODE_DECRYPT && mode_decrypt(filein, fileout)) { goto err; } else if (opt_run_mode == RUN_MODE_ENCRYPT && mode_encrypt(filein, fileout)) { goto err; } if (opt_input_file && filein) { my_close(filein, MYF(MY_WME)); } if (opt_output_file && fileout) { my_close(fileout, MYF(MY_WME)); } my_cleanup_options(my_long_options); my_end(0); return EXIT_SUCCESS; err: if (opt_input_file && filein) { my_close(filein, MYF(MY_WME)); } if (opt_output_file && fileout) { my_close(fileout, MYF(MY_WME)); } my_cleanup_options(my_long_options); my_end(0); exit(EXIT_FAILURE); }
void Cipher::computeDES() { //rePlain = new QRegExp("^[\\w|/]+\\.(plain)$"); reCipher = new QRegExp("([\\w]+)"); // Next line is not needed since we derive the key from the passphrase // reKey = new QRegExp("^[\\w|/]+\\.(key)$"); // Let's derive the key given by the password fprintf(stdout, "passphrase: %s\n", leKey->text().toLocal8Bit().constData()); fprintf(stdout, "size in bytes: %d\n", comboSize->currentText().toInt()/8); int keylen = comboSize->currentText().toLocal8Bit().toInt()/8; int pass_len = leKey->text().length(); fprintf(stdout, "size of pass: %d\n", pass_len); Util print; int hash_len = gcry_md_get_algo_dlen(GCRY_MD_SHA256); unsigned char *pass = (unsigned char *) gcry_malloc_secure(sizeof(unsigned char)*hash_len); strcpy( (char *) pass, leKey->text().toLocal8Bit().constData()); fprintf(stdout, "pass: "******"Failure to open MD_SHA256: %s/%s\n", gcry_strsource (err), gcry_strerror (err)); goto out; } gcry_md_write(hd, pass, pass_len); pass = gcry_md_read(hd, GCRY_MD_SHA256); printf("hash_len: %d\n", hash_len); fprintf(stdout, "Digest of key: "); print.printBuff(pass, hash_len); /* Dans un soucis de contrôle minimaliste des entrées, nous vérifions, avant toutes opérations, que les QLineEdit contienne bien une extension .in pour le fichier d'entrée, une extension .out pour le fi- chier de sortie et une extension .key pour le fichier de clé */ if(reCipher->exactMatch(leCipher->text())) { des = new DES(); if(!(strcmp(comboMode->currentText().toLocal8Bit().constData(), "CBC"))) { printf("DES3 encryption\n"); rep = des->des3_cbc_encrypt(lePlain->text().toLocal8Bit().constData(), (const char *) pass, leCipher->text().toLocal8Bit().constData(), leIv->text().toLocal8Bit().constData()); } if(rep == 1){ mb = new QMessageBox(this); mb->setText("Symmetric encryption error"); mb->setWindowTitle("Information"); mb->exec(); }else{ mb = new QMessageBox(this); mb->setWindowTitle("Information"); mb->setText("Success"); mb->exec(); this->close(); } } else{ /*if(!rePlain->exactMatch(lePlain->text())){ mb = new QMessageBox(this); mb->setText("The given plain file is wrong."); mb->setWindowTitle("Information"); mb->exec(); this->close(); } else if(!reKey->exactMatch(leKey->text())){ mb = new QMessageBox(this); mb->setText("The given key is wrong."); mb->setWindowTitle("Information"); mb->exec(); this->close(); }*/ if(!reCipher->exactMatch(leCipher->text())){ mb = new QMessageBox(this); mb->setText("The given name doesn't respect the given format."); mb->setWindowTitle("Information"); mb->exec(); this->close(); } } // not actually needed, it is done by derivePassphrase out: if(hd) gcry_md_close(hd); }
void Cipher::computeAES(){ Util print; //rePlain = new QRegExp("^[\\w|/]+\\.(plain)$"); reCipher = new QRegExp("([\\w]+)"); // Next line is not needed since we derive the key from the passphrase // reKey = new QRegExp("^[\\w|/]+\\.(key)$"); reIv = new QRegExp("[a-fA-F0-9]+"); // Let's derive the key given by the password if( (leKey->text().isEmpty() || lePlain->text().isEmpty() || leCipher->text().isEmpty() || leIv->text().size() != 16 && radioIv->isChecked()) ) { mb = new QMessageBox(this); mb->setWindowTitle("Information"); mb->setText("One field is still empty!"); mb->exec(); return ; } int keylen = comboSize->currentText().toLocal8Bit().toInt()/8; int pass_len = leKey->text().length(); // Here check whether radioIv is checked and if not randomly generate IV and store in the file unsigned char *iv = NULL; int blklen = gcry_cipher_get_algo_blklen(GCRY_CIPHER_AES); if(!radioIv->isChecked()) { iv = (unsigned char *) gcry_calloc(blklen, sizeof(unsigned char)); gcry_randomize(iv, blklen, GCRY_STRONG_RANDOM); } else iv = (unsigned char *) leIv->text().toLocal8Bit().constData(); int hash_len = gcry_md_get_algo_dlen(GCRY_MD_SHA256); unsigned char *pass = (unsigned char *) gcry_calloc(sizeof(unsigned char), hash_len); strcpy( (char *) pass, leKey->text().toLocal8Bit().constData()); gcry_error_t err = 0; gcry_md_hd_t hd = NULL; if(err = gcry_md_open(&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_SECURE)) { fprintf (stderr, "Failure to open MD_SHA256: %s/%s\n", gcry_strsource (err), gcry_strerror (err)); goto out; } gcry_md_write(hd, pass, pass_len); if(pass) gcry_free(pass); pass = gcry_md_read(hd, GCRY_MD_SHA256); /* Dans un soucis de contrôle minimaliste des entrées, nous vérifions, avant toutes opérations, que les QLineEdit contienne bien une extension .in pour le fichier d'entrée, une extension .out pour le fi- chier de sortie et une extension .key pour le fichier de clé */ if(!reIv->exactMatch(leIv->text()) && radioIv->isChecked()) { mb = new QMessageBox(this); mb->setText("The IV field is incorrect"); mb->setWindowTitle("Information"); mb->exec(); return ; } if(reCipher->exactMatch(leCipher->text())) { aes = new AES(); if(!(strcmp(comboMode->currentText().toLocal8Bit().constData(), "CBC") || strcmp(comboSize->currentText().toLocal8Bit().constData(), "128"))) { printf("AES-128-CBC encryption\n"); rep = aes->aes_encrypt(lePlain->text().toLocal8Bit().constData(), leCipher->text().toLocal8Bit().constData(), GCRY_CIPHER_AES, comboMode->currentData().toInt(), (const char *) pass, (const char*) iv); } else if(!(strcmp(comboMode->currentText().toLocal8Bit().constData(), "CBC") || strcmp(comboSize->currentText().toLocal8Bit().constData(), "256"))) { printf("AES-256-CBC encryption\n"); rep = aes->aes_cbc_256_encrypt(lePlain->text().toLocal8Bit().constData(), leCipher->text().toLocal8Bit().constData(), (const char *) pass, (const char *) iv); } if(rep == 1){ mb = new QMessageBox(this); mb->setText("Symmetric encryption error"); mb->setWindowTitle("Information"); mb->exec(); }else{ mb = new QMessageBox(this); mb->setWindowTitle("Information"); mb->setText("Success"); mb->exec(); this->close(); } } else{ /*if(!rePlain->exactMatch(lePlain->text())){ mb = new QMessageBox(this); mb->setText("The given plain file is wrong."); mb->setWindowTitle("Information"); mb->exec(); this->close(); } else if(!reKey->exactMatch(leKey->text())){ mb = new QMessageBox(this); mb->setText("The given key is wrong."); mb->setWindowTitle("Information"); mb->exec(); this->close(); }*/ if(!reCipher->exactMatch(leCipher->text())){ mb = new QMessageBox(this); mb->setText("The given name doesn't respect the given format."); mb->setWindowTitle("Information"); mb->exec(); this->close(); } } // not actually needed, it is done by derivePassphrase // why is gcry_free(pass) failing? out: memset(pass, 0, hash_len); memset(iv, 0, blklen); leKey->clear(); leIv->clear(); if(hd) gcry_md_close(hd); if(iv && !radioIv->isChecked()) gcry_free(iv); return ; }
char* md5_calc_file_signature(const char *filename) { char buffer[4096]; char* strsig; int ret; FILE *stream; #ifdef HAVE_LIBGCRYPT gcry_md_hd_t md5; gcry_error_t err; unsigned char* sig; #else MD5_CTX md5; unsigned char sig[MD5_DIGEST_LENGTH]; #endif stream = fopen(filename, "r"); if (stream == NULL) { perror(filename); exit(1); } #ifdef HAVE_LIBGCRYPT err = gcry_md_open(&md5, GCRY_MD_MD5, 0); if (err) { fprintf(stderr, "MD5 context creation failure: %s/%s", gcry_strsource (err), gcry_strerror (err)); return NULL; } #else MD5_Init(&md5); #endif /* iterate over file */ while (1) { /* read in from our file */ ret = fread(buffer, sizeof(char), sizeof(buffer), stream); if (ret <= 0) break; /* process our buffer buffer */ #ifdef HAVE_LIBGCRYPT gcry_md_write(md5, buffer, ret); #else MD5_Update(&md5, buffer, ret); #endif } #ifdef HAVE_LIBGCRYPT gcry_md_final(md5); sig = gcry_md_read(md5, GCRY_MD_MD5); if (!sig) { fprintf(stderr, "Unable to calculate MD5 signature for %s", filename); return NULL; } #else MD5_Final(sig, &md5); #endif if (stream != stdin) { (void)fclose(stream); } /* convert to string to print */ strsig = (char*) malloc(16*2+1); if (strsig) { md5_sig_to_string(sig, strsig, 16*2+1); /*(void)printf("%25s '%s'\n", "File key:", strsig);*/ return strsig; } else { return NULL; } }
void gcrypt_fatal(gcry_error_t err) { fwprintf(stderr, L"gcrypt error %s/%s\n", gcry_strsource(err), gcry_strerror(err)); exit(EXIT_FAILURE); }
int decrypt_file(char *fname, char *ofname, unsigned char *key, size_t keysize) { /* Decrypt in standalone mode */ FILE *ifd; FILE *ofd; size_t l = 16; int file_len; unsigned char in_buffer[l]; unsigned char out_buffer[l]; unsigned char tmp_buffer[l]; memset(tmp_buffer,0,sizeof(tmp_buffer)); char *iv; iv = (char *) malloc(16); memset(iv,0,16); *iv = 0x16d4; int i,j; int c; int in_len; // open our files! // in file ifd = (FILE *) fopen(fname,"r"); // out file ofd = (FILE *) fopen(ofname,"w"); // Set up gcrypt stuffs gcry_error_t err; gcry_cipher_hd_t hd; gcry_cipher_hd_t hd_mac; // set up HMAC err = gcry_md_open (&hd_mac, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC); err = gcry_md_setkey (hd_mac, key, keysize); // set up encryption err = gcry_cipher_open (&hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CBC, 0); if (err) printf("Failed to open cypher: %s - %s\n", gcry_strsource(err), gcry_strerror(err)); err = gcry_cipher_setkey (hd, key, keysize); if (err) printf("Failed to set key: %s - %s\n", gcry_strsource(err), gcry_strerror(err)); // Get the in file length to make things easier fseek(ifd, 0, SEEK_END); file_len = ftell(ifd); fseek(ifd, 0, SEEK_SET); // How many iterations do we have? int count = file_len/l - 64/l; int first = TRUE; // Read the files in and encrypt them out! for(i = 0; i < count; ++i) { c = fread(in_buffer,1,l,ifd); err = gcry_cipher_setiv (hd, iv, 16); if (err) printf("Failed to set iv: %s - %s\n", gcry_strsource(err), gcry_strerror(err)); err = gcry_cipher_decrypt (hd, out_buffer, l, in_buffer, l); if (err) printf("Failed to decrypt: %s - %s\n", gcry_strsource(err), gcry_strerror(err)); gcry_md_write (hd_mac, in_buffer, l); if (i < count - 1) { fwrite(out_buffer,1,l,ofd); } else { // get rid of padding c = 0; for (j=0;j<l;++j) { if(out_buffer[j] != 0) { c += 1; } } c+=1; fwrite(out_buffer,1,c,ofd); } } // Check the current MAC vs what it is supposed to be unsigned char *mac_buffer_check; unsigned char *mac_buffer; mac_buffer = (unsigned char *)malloc(64); mac_buffer_check = gcry_md_read (hd_mac, GCRY_MD_SHA512); // Get the mac from the end of the data stream for(i = 0; i < 64/l; ++i) { c = fread(in_buffer,1,l,ifd); for(j = 0; j < l; ++j) { mac_buffer[i*l+j] = in_buffer[j]; } } // Close it up... fclose(ifd); fclose(ofd); int check = memcmp(mac_buffer,mac_buffer_check,64); if (check != 0 ) { // if you are here, something went very wrong! printf("HMAC Verification Failed!\n"); return 62; } // YAY! printf("Successfully Decrypted File\n"); //gcry_cipher_close(hd); return 0; }
static int mode_decrypt(File filein, File fileout) { xb_rcrypt_t *xbcrypt_file = NULL; void *chunkbuf = NULL; size_t chunksize; size_t originalsize; void *ivbuf = NULL; size_t ivsize; void *decryptbuf = NULL; size_t decryptbufsize = 0; ulonglong ttlchunksread = 0; ulonglong ttlbytesread = 0; xb_rcrypt_result_t result; gcry_cipher_hd_t cipher_handle; gcry_error_t gcry_error; if (encrypt_algo != GCRY_CIPHER_NONE) { gcry_error = gcry_cipher_open(&cipher_handle, encrypt_algo, encrypt_mode, 0); if (gcry_error) { msg("%s:decrypt: unable to open libgcrypt" " cipher - %s : %s\n", my_progname, gcry_strsource(gcry_error), gcry_strerror(gcry_error)); return 1; } gcry_error = gcry_cipher_setkey(cipher_handle, opt_encrypt_key, encrypt_key_len); if (gcry_error) { msg("%s:decrypt: unable to set libgcrypt cipher" "key - %s : %s\n", my_progname, gcry_strsource(gcry_error), gcry_strerror(gcry_error)); goto err; } } /* Initialize the xb_crypt format reader */ xbcrypt_file = xb_crypt_read_open(&filein, my_xb_crypt_read_callback); if (xbcrypt_file == NULL) { msg("%s:decrypt: xb_crypt_read_open() failed.\n", my_progname); goto err; } /* Walk the encrypted chunks, decrypting them and writing out */ while ((result = xb_crypt_read_chunk(xbcrypt_file, &chunkbuf, &originalsize, &chunksize, &ivbuf, &ivsize)) == XB_CRYPT_READ_CHUNK) { if (encrypt_algo != GCRY_CIPHER_NONE) { gcry_error = gcry_cipher_reset(cipher_handle); if (gcry_error) { msg("%s:decrypt: unable to reset libgcrypt" " cipher - %s : %s\n", my_progname, gcry_strsource(gcry_error), gcry_strerror(gcry_error)); goto err; } if (ivsize) { gcry_error = gcry_cipher_setiv(cipher_handle, ivbuf, ivsize); } else { gcry_error = gcry_cipher_setiv(cipher_handle, v1_encrypt_iv, encrypt_iv_len); } if (gcry_error) { msg("%s:decrypt: unable to set cipher iv - " "%s : %s\n", my_progname, gcry_strsource(gcry_error), gcry_strerror(gcry_error)); continue; } if (decryptbufsize < originalsize) { if (decryptbufsize) { decryptbuf = my_realloc(decryptbuf, originalsize, MYF(MY_WME)); decryptbufsize = originalsize; } else { decryptbuf = my_malloc(originalsize, MYF(MY_WME)); decryptbufsize = originalsize; } } /* Try to decrypt it */ gcry_error = gcry_cipher_decrypt(cipher_handle, decryptbuf, originalsize, chunkbuf, chunksize); if (gcry_error) { msg("%s:decrypt: unable to decrypt chunk - " "%s : %s\n", my_progname, gcry_strsource(gcry_error), gcry_strerror(gcry_error)); gcry_cipher_close(cipher_handle); goto err; } } else { decryptbuf = chunkbuf; } /* Write it out */ if (my_write(fileout, decryptbuf, originalsize, MYF(MY_WME | MY_NABP))) { msg("%s:decrypt: unable to write output chunk.\n", my_progname); goto err; } ttlchunksread++; ttlbytesread += chunksize; if (opt_verbose) msg("%s:decrypt: %llu chunks read, %llu bytes read\n.", my_progname, ttlchunksread, ttlbytesread); } xb_crypt_read_close(xbcrypt_file); if (encrypt_algo != GCRY_CIPHER_NONE) gcry_cipher_close(cipher_handle); if (decryptbuf && decryptbufsize) my_free(decryptbuf); if (opt_verbose) msg("\n%s:decrypt: done\n", my_progname); return 0; err: if (xbcrypt_file) xb_crypt_read_close(xbcrypt_file); if (encrypt_algo != GCRY_CIPHER_NONE) gcry_cipher_close(cipher_handle); if (decryptbuf && decryptbufsize) my_free(decryptbuf); return 1; }
static int mode_encrypt(File filein, File fileout) { size_t bytesread; size_t chunkbuflen; void *chunkbuf = NULL; void *ivbuf = NULL; size_t encryptbuflen = 0; size_t encryptedlen = 0; void *encryptbuf = NULL; ulonglong ttlchunkswritten = 0; ulonglong ttlbyteswritten = 0; xb_wcrypt_t *xbcrypt_file = NULL; gcry_cipher_hd_t cipher_handle; gcry_error_t gcry_error; if (encrypt_algo != GCRY_CIPHER_NONE) { gcry_error = gcry_cipher_open(&cipher_handle, encrypt_algo, encrypt_mode, 0); if (gcry_error) { msg("%s:encrypt: unable to open libgcrypt cipher - " "%s : %s\n", my_progname, gcry_strsource(gcry_error), gcry_strerror(gcry_error)); return 1; } gcry_error = gcry_cipher_setkey(cipher_handle, opt_encrypt_key, encrypt_key_len); if (gcry_error) { msg("%s:encrypt: unable to set libgcrypt cipher key - " "%s : %s\n", my_progname, gcry_strsource(gcry_error), gcry_strerror(gcry_error)); goto err; } } posix_fadvise(filein, 0, 0, POSIX_FADV_SEQUENTIAL); xbcrypt_file = xb_crypt_write_open(&fileout, my_xb_crypt_write_callback); if (xbcrypt_file == NULL) { msg("%s:encrypt: xb_crypt_write_open() failed.\n", my_progname); goto err; } ivbuf = my_malloc(encrypt_iv_len, MYF(MY_FAE)); /* now read in data in chunk size, encrypt and write out */ chunkbuflen = opt_encrypt_chunk_size; chunkbuf = my_malloc(chunkbuflen, MYF(MY_FAE)); while ((bytesread = my_read(filein, chunkbuf, chunkbuflen, MYF(MY_WME))) > 0) { if (encrypt_algo != GCRY_CIPHER_NONE) { gcry_error = gcry_cipher_reset(cipher_handle); if (gcry_error) { msg("%s:encrypt: unable to reset cipher - " "%s : %s\n", my_progname, gcry_strsource(gcry_error), gcry_strerror(gcry_error)); goto err; } xb_crypt_create_iv(ivbuf, encrypt_iv_len); gcry_error = gcry_cipher_setiv(cipher_handle, ivbuf, encrypt_iv_len); if (gcry_error) { msg("%s:encrypt: unable to set cipher iv - " "%s : %s\n", my_progname, gcry_strsource(gcry_error), gcry_strerror(gcry_error)); continue; } if (encryptbuflen < bytesread) { if (encryptbuflen) { encryptbuf = my_realloc(encryptbuf, bytesread, MYF(MY_WME)); encryptbuflen = bytesread; } else { encryptbuf = my_malloc(bytesread, MYF(MY_WME)); encryptbuflen = bytesread; } } gcry_error = gcry_cipher_encrypt(cipher_handle, encryptbuf, encryptbuflen, chunkbuf, bytesread); encryptedlen = bytesread; if (gcry_error) { msg("%s:encrypt: unable to encrypt chunk - " "%s : %s\n", my_progname, gcry_strsource(gcry_error), gcry_strerror(gcry_error)); gcry_cipher_close(cipher_handle); goto err; } } else { encryptedlen = bytesread; encryptbuf = chunkbuf; } if (xb_crypt_write_chunk(xbcrypt_file, encryptbuf, bytesread, encryptedlen, ivbuf, encrypt_iv_len)) { msg("%s:encrypt: abcrypt_write_chunk() failed.\n", my_progname); goto err; } ttlchunkswritten++; ttlbyteswritten += encryptedlen; if (opt_verbose) msg("%s:encrypt: %llu chunks written, %llu bytes " "written\n.", my_progname, ttlchunkswritten, ttlbyteswritten); } my_free(ivbuf); my_free(chunkbuf); if (encryptbuf && encryptbuflen) my_free(encryptbuf); xb_crypt_write_close(xbcrypt_file); if (encrypt_algo != GCRY_CIPHER_NONE) gcry_cipher_close(cipher_handle); if (opt_verbose) msg("\n%s:encrypt: done\n", my_progname); return 0; err: if (chunkbuf) my_free(chunkbuf); if (encryptbuf && encryptbuflen) my_free(encryptbuf); if (xbcrypt_file) xb_crypt_write_close(xbcrypt_file); if (encrypt_algo != GCRY_CIPHER_NONE) gcry_cipher_close(cipher_handle); return 1; }
void decrypt(char *outfile, char *inpfile) { gcry_err_code_t err = 0; gcry_cipher_hd_t gchandle; const int blks = gcry_cipher_get_algo_blklen(GCRY_CIPHER_AES256); const int keyl = gcry_cipher_get_algo_keylen(GCRY_CIPHER_AES256); long outfileSize = 0; char key[keyl]; const char* salt = "iuyjdbnbtaqonbgt"; //open output file FILE *fout = fopen(outfile, "r"); if (!fout) { printf("output file name : %s\n", outfile); fout = fopen(outfile, "w"); } else { printf("Output file already exist on disk.\n"); return;; } char password[100]; do { printf("Please enter password between 8-20 chars :"); scanf("%s", password); } while (strlen(password) > 20 || strlen(password) < 8); err = gcry_kdf_derive(password, strlen(password), GCRY_KDF_PBKDF2, GCRY_MD_SHA256, salt, strlen(salt), 937, keyl, key); if (err) { fprintf(stderr, "Failure: %s/%s\n", gcry_strsource(err), gcry_strerror(err)); exit(EXIT_FAILURE); } char ctext[blks]; char extractedIV[blks]; FILE *finp = fopen(inpfile, "r"); fseek(finp, 0, SEEK_SET); unsigned char extractedHMAC[keyl + 1]; fread(extractedHMAC, 1, keyl, finp); //extract HMAC from received file extractedHMAC[keyl] = '\0'; // Compare calculated HMAC with extracted HMAC ---> start long cipherSize = 0; fseek(finp, 0, SEEK_END); cipherSize = ftell(finp) - keyl; fseek(finp, keyl, SEEK_SET); unsigned char *hmacBuffer = malloc(cipherSize + 1); fread(hmacBuffer, 1, cipherSize, finp); gcry_md_hd_t hd; err = gcry_md_open(&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC); if (err) { fprintf(stderr, "Failure: %s/%s\n", gcry_strsource(err), gcry_strerror(err)); fclose(finp); fclose(fout); exit(EXIT_FAILURE); } err = gcry_md_setkey(hd, key, keyl); if (err) { fprintf(stderr, "Failure: %s/%s\n", gcry_strsource(err), gcry_strerror(err)); fclose(finp); fclose(fout); exit(EXIT_FAILURE); } err = gcry_md_enable(hd, GCRY_MD_SHA256); if (err) { fprintf(stderr, "Failure: %s/%s\n", gcry_strsource(err), gcry_strerror(err)); fclose(finp); fclose(fout); exit(EXIT_FAILURE); } gcry_md_write(hd, hmacBuffer, cipherSize); char thmac[keyl]; unsigned char *hmac = thmac; hmac = gcry_md_read(hd, GCRY_MD_SHA256); int i = 0; int hflag = 1; for (; i < keyl; i++) { if (hmac[i] != extractedHMAC[i]) hflag = 0; } if (hflag) printf("HMAC successfully matched\n"); else printf("HMAC not matched\n"); fseek(finp, keyl, SEEK_SET); // Compare calculated HMAC with extracted HMAC ---> end //Decryption algo ------> start fread(extractedIV, 1, blks, finp); // read IV err = gcry_cipher_open(&gchandle, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC, 0); if (err) { fprintf(stderr, "Failure: %s/%s\n", gcry_strsource(err), gcry_strerror(err)); exit(EXIT_FAILURE); } err = gcry_cipher_setkey(gchandle, key, keyl); if (err) { fprintf(stderr, "Failure: %s/%s\n", gcry_strsource(err), gcry_strerror(err)); exit(EXIT_FAILURE); } err = gcry_cipher_setiv(gchandle, extractedIV, blks); if (err) { fprintf(stderr, "Failure: %s/%s\n", gcry_strsource(err), gcry_strerror(err)); exit(EXIT_FAILURE); } if (!finp) { printf("Could not open input text file\n"); } else { int x = 0; char plaintext[blks]; while ((x = fread(plaintext, 1, blks, finp))) { if (x < blks) // add padding to last block outfileSize += x; err = gcry_cipher_decrypt(gchandle, ctext, blks, plaintext, x); if (err && x == blks) { fprintf(stderr, "Failure: %s/%s\n", gcry_strsource(err), gcry_strerror(err)); fclose(finp); fclose(fout); exit(EXIT_FAILURE); } fwrite(ctext, 1, blks, fout); } gcry_cipher_close(gchandle); gcry_md_close(hd); fclose(finp); fclose(fout); } free(hmacBuffer); //Decryption algo ------> end }
int encrypt_network_file(unsigned char *key, size_t keysize, unsigned char * file_buffer, int file_len, int *cbuffer_len) { /* encrypt files for network transfer */ // block size... l is not very descriptive... // next time I will use blk_size or something size_t l = 16; // more too many buffers... unsigned char in_buffer[l]; unsigned char out_buffer[l]; unsigned char *cipher_text; unsigned char *mac_buffer; // More of the same... iv happiness char *iv; iv = (char *) malloc(16); memset(iv,0,16); *iv = 0x16d4; // counters... too many of these as well! int i,j,k; int c; int count; /* Setup the encryption information */ gcry_error_t err; gcry_cipher_hd_t hd; gcry_cipher_hd_t hd_mac; // Set up the MAC work again err = gcry_md_open (&hd_mac, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC); err = gcry_md_setkey (hd_mac, key, keysize); // Start the encryption err = gcry_cipher_open (&hd, GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CBC, 0); if (err) printf("Failed to open cypher: %s - %s\n", gcry_strsource(err), gcry_strerror(err)); // Set the key err = gcry_cipher_setkey (hd, key, keysize); if (err) printf("Failed to set key: %s - %s\n", gcry_strsource(err), gcry_strerror(err)); /* Encrypt the file */ int x = file_len / l; int nsize = (x+1)*16; cipher_text = (unsigned char *) malloc((nsize)*sizeof(unsigned char)+64); memset(cipher_text,0,file_len); count = file_len/l+1; for(i = 0; i < count; ++i) { if (i < count-1) { for(j = 0; j < l; ++j) { in_buffer[j] = file_buffer[i*l+j]; } } else { k = file_len % l; for(j = 0; j < k; ++j) { in_buffer[j] = file_buffer[i*l+j]; } for(j = k; j < l; ++j) { in_buffer[j] = 0; } } err = gcry_cipher_setiv (hd, iv, 16); if (err) printf("Failed to set iv: %s - %s\n", gcry_strsource(err), gcry_strerror(err)); err = gcry_cipher_encrypt (hd, out_buffer, l, in_buffer, l); if (err) printf("Failed to encrypt: %s - %s\n", gcry_strsource(err), gcry_strerror(err)); gcry_md_write (hd_mac, out_buffer, l); /* Output encrypted data */ for (j = 0; j < l; ++j) { cipher_text[i*l+j] = out_buffer[j]; *cbuffer_len = i * l + j; } } // get the MAC digest and send it off! mac_buffer = gcry_md_read (hd_mac, GCRY_MD_SHA512); i += 1; for (j = 0; j < 64; ++j) { cipher_text[i*l+j] = mac_buffer[j]; *cbuffer_len = i * l + j; } //gcry_cipher_close(hd); return cipher_text; }