C言語で公開鍵と平文ファイルを与えると暗号化したファイルを出力するプログラムと 秘密鍵と暗号化されたファイルを与えると複合された平文ファイルを出力するプログラムを作成しました。 平文ファイルに"Hello"と入力し実行すると暗号化されたファイルは "34 50 89 0 186 0 75 0 75 0 76 0 13 0 108 0" 複合された平文ファイルは""!H e l l o "このように先頭に余計な文字とスペースができてしまいます。なにか良い改善策はありますか? (文字数制限の都合で関数やファイルの開閉は省略しています) 暗号化プログラムencrypt ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー #include <stdio.h> #include <stdlib.h> // バイナリ法によるべき剰余計算関数 int modpow(int base, int exp, int mod) { int result = 1; base = base % mod; while (exp > 0) { if (exp % 2 == 1) { result = (result * base) % mod; } base = (base * base) % mod; exp = exp / 2; } return result; } int main() { int p = 13, q = 17; int n = p * q; int e = 5; FILE *inputFile = fopen("plaintext.txt", "r"); FILE *outputFile = fopen("ciphertext.txt", "w"); int ch; while ((ch = fgetc(inputFile)) != EOF) { int cipher = modpow(ch, e, n); // 暗号文をファイルに書き込む fprintf(outputFile, "%d ", cipher); } } 復号プログラムdecrypt #include <stdio.h> #include <stdlib.h> // 拡張ユークリッド互除法の関数宣言 int extended_gcd(int a, int b, int *x, int *y); int main() { int p = 13, q = 17; int n = p * q; int e = 5; int phi = (p - 1) * (q - 1); int x, y; int gcd = extended_gcd(e, phi, &x, &y); int d = (x % phi + phi) % phi; FILE *inputFile = fopen("ciphertext.txt", "r"); FILE *outputFile = fopen("decrypted.txt", "w"); if (inputFile == NULL || outputFile == NULL) { printf("ファイルを開けませんでした。¥n"); return 1; } int cipher; while (fscanf(inputFile, "%d", &cipher) != EOF) { int plain = modpow(cipher, d, n); fputc(plain, outputFile); } } // 拡張ユークリッド互除法 int extended_gcd(int a, int b, int *x, int *y) { if (a == 0) { *x = 0; *y = 1; return b; } int x1, y1; int gcd = extended_gcd(b % a, a, &x1, &y1); *x = y1 - (b / a) * x1; *y = x1; return gcd; }
C言語関連