信息安全之仿射密码加密和解密
生活随笔
收集整理的這篇文章主要介紹了
信息安全之仿射密码加密和解密
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本文利用仿射密碼,對一個只含可打印字符的txt文件進行加密和解密。
//加解密時,文件內容為所有可打印字符,即ASCII碼從32-126的95個字符 #include<iostream> #include<fstream> 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; }
總結
以上是生活随笔為你收集整理的信息安全之仿射密码加密和解密的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 有了这款IDEA插件,再也不需要post
- 下一篇: 图胜千言:电商支付架构设计