本文利用仿射密碼,對一個只含可打印字符的txt文件進行加密和解密。
//加解密時,文件內容為所有可打印字符,即ASCII碼從32-126的95個字符 #include#include using namespace std; //加密類 class Encrypt { public: void set_AB(int a, int b) {A = a; B = b;} //設置加密密鑰 int gcd(int a, int b) { while(b) { int r = a % b; a = b; b = r; } return a; } bool Judge(int a, int b) { //判斷密鑰是否合法 if(gcd(a, 95) == 1) { set_AB(a, b); return true; } else { cout << "密鑰不合法,請重新輸入!" << endl; return false; } } int get_A() {return A;} //獲取加密密鑰 int get_B() {return B;} int encrypt(char ch) { //對單個字符進行加密 int plaintext_id = ch - ' '; int A = get_A(), B = get_B(); int ciphertext_id = (A * plaintext_id + B) % 95; return ciphertext_id + 32; } private: int A, B; //加密密鑰 }; //解密類 class Decrypt { public: int x, y; //a*x + b*y = gcd(a, b) int extend_eulid(int a, int b) { if(b == 0) { x = 1; y = 0; } else { extend_eulid(b, a%b); int temp = x; x = y; y = temp - a / b * y; } } int get_inv(int a) { //求A的乘法逆元 extend_eulid(a, 95); int inv = x; if(inv < 0) inv += 95; return inv; } void set_A(int a) {A = get_inv(a);} void set_B(int b) {B = b;} int get_A() {return A;} //獲取解密密鑰 int get_B() {return B;} int decrypt(char ch) { //對單個字符進行解密 int ciphertext_id = ch - ' '; int A = get_A(), B = get_B(); int plaintext_id = A * (ciphertext_id - B + 95) % 95; return plaintext_id + 32; } private: int A, B; //解密密鑰 }; int main() { Encrypt en; Decrypt de; int A, B; char ch; while(1) { //輸入加密密鑰 cin >> A >> B; if(en.Judge(A, B) == true) break; } de.set_A(A), de.set_B(B); //設置解密密鑰 ifstream fin("F:text.txt", ios::in); //以輸入方式打開明文文件"text.txt" ofstream fout("F:ciphertext.txt", ios::out); //以輸出方式打開保存密文的文件"ciphertext.txt",並將其原有的內容清除 if(!fin) { cout << "Can not open the plaintext file!" << endl; } while(fin.get(ch) != NULL) { int ciphertext_id = en.encrypt(ch); char ciphertext_ch = char(ciphertext_id); fout << ciphertext_ch; } //從明文文件"F:test.txt"中一次讀取一個字符進行加密,將加密後的文件保存為 "ciphertext.txt" fout.close(); ifstream fin1("F:ciphertext.txt", ios::in); //以輸入方式打開密文文件"ciphertext.txt" ofstream fout1("F:plaintext.txt", ios::out); //以輸出方式打開保存解密後的文件"plaintext.txt",並將其原有的內容清除 if(!fin1) { cout << "Can not open the ciphertext file!" << endl; } while(fin1.get(ch) != NULL) { int plaintext_id = de.decrypt(ch); char plaintext_ch = char(plaintext_id); fout1 << plaintext_ch; } //從密文文件"ciphertext.txt"中一次讀取一個字符進行解密,將解密後的文件保存為"plaintext.txt" fout1.close(); return 0; }