
凱撒密碼
凱撒密碼就是簡單移位,注意負數取模的情況就好了,
#include<bits/stdc++.h>
using namespace std;
const int mod = 26;
int k;
string str;
// 解密函式
string decryptionFunction(string eCode){
string dCode = "";
for(int i=0;i<eCode.length();i++){
int n = eCode[i] - 'a';
int m = (n-k+mod)%mod;
dCode += ('a'+m);
}
return dCode;
}
int main(){
cout<<"請輸入明文和密鑰:"<<endl;
while(cin>>str>>k){
string eCode = "";
for(int i=0;i<str.length();i++){
int n = str[i]-'a';
int m = (n+k)%mod;
eCode += ('a'+m);
}
cout<<"加密后的密文:"<<eCode<<endl;
cout<<"呼叫解密函式:"<<decryptionFunction(eCode)<<endl;
}
return 0;
}
/*
測驗用例
security 3
*/

仿射密碼
仿射密碼的話,加密程序和上述凱撒密碼沒多少區別,重在在于解密那一塊,
首先,我們得到了密文編號 c ,怎么求得 m 呢?
m = ( c - 5 ) / 3(mod 26)
但是這里會有一種情況要考慮,如果 c-5 的結果小于 3 ,那么是不是 m 的值就為 0,所以我們采用如下解決方式,讓 m = (c-5) * X (mod 26)這個 X 是 3 的逆元,我們呼叫求逆元函式,就可以得到 X
#include<bits/stdc++.h>
using namespace std;
const int mod = 26;
int k;
string str;
typedef long long ll;
// 拓展gcd
void exgcd(ll a,ll b,ll& d,ll& x,ll& y){
if(!b) { d = a; x = 1; y = 0; }
else{ exgcd(b, a%b, d, y, x); y -= x*(a/b); }
}
// 求逆元
ll inv(ll a, ll p){
ll d,x,y;
exgcd(a,p,d,x,y);
return d == 1 ? (x+p)%p : -1;
}
// 解密函式
string decryptionFunction(string eCode){
string dCode = "";
// 求逆元
int rev = inv(3,mod);
for(int i=0;i<eCode.length();i++){
int c = eCode[i] - 'a';
c = (c-5+mod)%mod;
int m = (c*rev)%mod;
dCode += ('a'+m);
}
return dCode;
}
int main(){
cout<<"請輸入明文:"<<endl;
while(cin>>str){
string eCode = "";
for(int i=0;i<str.length();i++){
int n = str[i]-'a';
int m = (3*n+5)%mod;
eCode += ('a'+m);
}
cout<<"加密后的密文:"<<eCode<<endl;
cout<<"呼叫解密函式:"<<decryptionFunction(eCode)<<endl;
}
return 0;
}
/*
測驗用例
security
hrlnedkz
*/
學如逆水行舟,不進則退
CSDN認證博客專家
CSDN博客專家
博客之星
前端開發攻城獅
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/12989.html
標籤:其他
