1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| void
enCrypt(void) {
char keyFile[MAX_FILENAME+EXTENSION_LENGTH+1], encryptFile[MAX_FILENAME+1];
char outFile[MAX_FILENAME+1];
FILE *PK,*OF;
mpz_t e,n,m,c;
int blockSize, *block, i, j;
char *cBlock, scratch[4];
/* initialize our integers */
mpz_init(e);
mpz_init(n);
mpz_init(m);
mpz_init(c);
/* grab name of file to encrypt */
printf("Enter filename to encrypt\n");
fgets(encryptFile,MAX_FILENAME+1,stdin);
encryptFile[strlen(encryptFile)-1] = NULL;
getchar();
/* grab name of ciphertext */
printf("Enter filename to store ciphertext in\n");
fgets(outFile,MAX_FILENAME+1,stdin);
outFile[strlen(outFile)-1] = NULL;
getchar();
/* grab name of keyfile */
printf("Enter filename for the public key to encrypt this file with\n");
printf("WITHOUT the .public extension\n");
fgets(keyFile,MAX_FILENAME+1,stdin);
keyFile[strlen(keyFile)-1] = NULL;
strcat(keyFile,".public");
/* read in key */
PK=fopen(keyFile,"r");
mpz_inp_str(e,PK,10);
mpz_inp_str(n,PK,10);
fclose(PK);
#if 0
printf("e = %s\n",mpz_get_str(NULL,10,e));
printf("n = %s\n",mpz_get_str(NULL,10,n));
#endif
/* compute blocksize */
blockSize = (strlen(mpz_get_str(NULL,10,n)) - 1) / 3;
block = calloc(blockSize+1, sizeof(int));
cBlock = calloc(3 * blockSize + 1, sizeof(char));
#if 0
printf("blockSize = %d\n",blockSize);
#endif
PK=fopen(encryptFile,"r");
OF=fopen(outFile,"w+");
/* loop thru plaintext, reading in blocks */
while(!feof(PK)) {
/* read in enough chars for block */
for(i=0;i<blockSize && !feof(PK);i++) {
block[i] = fgetc(PK);
if(block[i] == EOF) {
block[i] = 0;
break;
}
else if((block[i] < 32) || (block[i] > 127))
block[i] = ' ';
block[i+1]=0;
}
/* concat decimal representations */
for(j=0;j<i;j++) {
sprintf(scratch,"%d",block[j]);
strcat(cBlock,scratch);
}
/* put string into integer type */
mpz_set_str(m,cBlock,10);
/* c = (m^e) % n ... RSA encryption */
mpz_powm(c,m,e,n);
/* write out encrypted block */
mpz_out_str(OF,10,c);
fprintf(OF,"\n");
cBlock[0]='\0';
fclose(PK);
fclose(OF);
mpz_clear(e);
mpz_clear(n);
mpz_clear(m);
mpz_clear(c);
free(cBlock);
free(block);
} } |
Partager