Vernam加密法:
#include <stdio.h>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>
#include <algorithm>
#include <vector>
#include <string.h>
#include <string>
#include <queue>
#include <stack>
#include <set>
#include <sstream>
#include <time.h>
using namespace std;
char clear_text[10000];
string ans;
char key[10000];
int main()
{
memset(key, 0, sizeof(key));
ans.clear();
printf("please enter the clear_text :");
scanf("%s", clear_text);
int len = strlen(clear_text);
printf("please enter key :");
scanf("%s", &key);
for (int i = 0;i < len;i++)
{
int tmp = (clear_text[i] - 'a' + key[i] - 'a') % 26;
ans += (char)(tmp + 'a');
}
cout << ans << endl;
return 0;
}
Playfair密码加密:
#include <stdio.h>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>
#include <algorithm>
#include <vector>
#include <string.h>
#include <string>
#include <queue>
#include <stack>
#include <set>
#include <sstream>
#include <time.h>
using namespace std;
char key[100];
int mat[30][30];
string text, ans;
bool vis[30];
void init()
{
memset(vis, false, sizeof(vis));
memset(mat, 0, sizeof(mat));
ans.clear();
text.clear();
}
struct Loca
{
int x, y;
}loc[100];
int main()
{
init();
printf("please entry the key :");
scanf("%s", key);
int len = strlen(key);
int tot = 0;
for (int i = 0;i < len;i++)
{
if (!vis[key[i] - 'a'])
{
int x = tot / 5;
int y = tot % 5;
loc[key[i] - 'a'].x = x;
loc[key[i] - 'a'].y = y;
mat[x][y] = key[i] - 'a';
vis[key[i] - 'a'] = true;
if (key[i] == 'i' || key[i] == 'j')
{
vis['i' - 'a'] = vis['j' - 'a'] = true;
loc['i' - 'a'].x = x;
loc['i' - 'a'].y = y;
loc['j' - 'a'].x = x;
loc['j' - 'a'].y = y;
}
tot++;
}
}
int pos = 0;
while (1)
{
if (!vis[pos])
{
int x = tot / 5;
int y = tot % 5;
loc[pos].x = x;
loc[pos].y = y;
mat[x][y] = pos;
vis[pos] = true;
if (pos == 'i' - 'a' || pos == 'j' - 'a')
{
vis['i' - 'a'] = vis['j' - 'a'] = true;
loc['i' - 'a'].x = x;
loc['i' - 'a'].y = y;
loc['j' - 'a'].x = x;
loc['j' - 'a'].y = y;
}
tot++;
}
pos++;
if (pos == 26) break;
}
printf("plaese enter the clear text :");
cin >> text;
if (text.size() % 2) text += 'm';//事先约定奇数+’m‘
//开始加密
for (int i = 0;i < text.size();i += 2)
{
int u = text[i] - 'a';
int v = text[i + 1] - 'a';
int x1 = loc[u].x;
int y1 = loc[u].y;
int x2 = loc[v].x;
int y2 = loc[v].y;
if (x1 == x2 && y1 == y2)//事先约定相同算作为"fq"
ans += "fq";
else if (x1 == x2)
{
int tmp = (y1 + 1) % 5;
while (tmp == y1 || tmp == y2)
tmp = (tmp + 1) % 5;
ans += mat[x1][tmp] + 'a';
int tmp2 = (y2 + 1) / 5;
while (tmp2 == y1 || tmp2 == y2 || tmp2 == tmp)
tmp2 = (tmp2 + 1) % 5;
ans += mat[x2][tmp2] + 'a';
}
else if (y1 == y2)
{
int tmp = (x1 + 1) % 5;
while (tmp == x1 || tmp == x2)
tmp = (tmp + 1) % 5;
ans += mat[tmp][y1] + 'a';
int tmp2 = (x2 + 1) % 5;
while (tmp == x1 || tmp == x2 || tmp2 == tmp)
tmp2 = (tmp2 + 1) % 5;
ans += mat[tmp2][y2] + 'a';
}
else if (x1 != x2 && y1 != y2)
{
ans += mat[x1][y2] + 'a';
ans += mat[x2][y1] + 'a';
}
}
cout << ans << endl;
return 0;
}
/*
hello
university
*/