一个维吉尼亚密码,求解!?
的有关信息介绍如下:
给你一份C语言的代码,自己编的,试过337位密文可解
用的是重合指数法算的密钥
代码给你了,你这个只有31位其实自己手算也可以,加油哦~
#include<stdio.h>
#include<stdlib.h>
#include<String.h>
#include<conio.h>
#include<math.h>
void Static(int L);
void DenKey();
int main()
{
int L=0;
int select=0;
while(1){
printf("请选择操作:计算密钥(1);解密(2):退出(3)\n");
scanf("%d",&select);
if(select==1)//加密操作
{
printf("请输入密钥长度\n");
scanf("%d",&L);
Static(L);
}
else if(select==2)//解密操作
{
DenKey();
}
else if(select==3)
{
exit(0);
}
else
{
printf("输入有误!\n");
}
}
return 0;
}
void Static(int L)
{
int number=0,i=0,j=0;
char ch;
char cipher[1000];
FILE *fp;
int num1[26];
int m=0;
for(m=0;m<26;m++)
{
num1[m]=0;
}
int al=0,bl=0;
fp=fopen("E:\\cipher\\密文.txt","r");
if(fp==NULL)
{
printf("文件打开失败!");
}
i=0,j=0;
fscanf(fp,"%c",&ch);
while(!feof(fp))
{
if(ch>='A'&&ch<='Z')
{
al=(int)(ch-'A');
num1[al]++;
j++;
}
fscanf(fp,"%c",&ch);
}
printf("密文的个数%d\n",j);
fclose(fp);
//放入到一个char型数组中
fp = fopen("E:\\cipher\\密文.txt", "r"); //打开文件。
int cnt=0;
int c;
while(1)
{
c = fgetc(fp); //读一个字节。
if(c == EOF) break; //到文件尾,退出循环。
cipher[cnt] = c;//赋值到字符数组中。
cnt ++;//读到的字符增加一个。
}
fclose(fp);//关闭文件。
printf("输出cipher:\n");
for(i=0;i<cnt;i++)
printf("%c ",cipher[i]);
//按密钥长度来分组
int num2[26];
int sum1=0;
int x=0;
for(m=0;m<26;m++)
{
num2[m]=0;
}
i=0;
char a[1000];
int n=0;
int l;
int len1[10000];
double len[100][27];
while(n<L){
for(m=0;m<cnt;m++){
if(m%L==n){
a[i]=cipher[m];
i++;
}
}
printf("\n输出i:%d\n",i);
printf("\n输出数组a\n");
for(l=0;l<i;l++){
printf("%c ",a[l]);
if(a[l]>='A'&&a[l]<='Z'){
bl=(int)(a[l]-'A');
num2[bl]++;
x++;
}
}
//分组密文中各字符出现的频率
printf("\n分组后密文中各字符出现的频率(a-z):");
for(m=0;m<26;m++)
{
printf("%.3f%% ",(float)num2[m]/i*100);
if((m%5)==0){
printf("\n");
}
}
//计算重合指数
for(m=0;m<26;m++)
{
len[n][m+1]=(float)num2[m]/i*100;
sum1=sum1+num2[m]*(num2[m]-1);
}
for(m=0;m<26;m++)
{
num2[m]=0;
}
printf("\n分组密文的重合指数为:%.3f%%\n",(float)sum1/(i*(i-1))*100);
len[n][0]=(float)sum1/(i*(i-1))*100;
sum1=0;
i=0;
n++;
}
//计算重合指数的平均数,判断是否满足条件,如果满足条件将执行1.计算密钥;2.打印密钥。若不满足输出“请重新选择密钥长度”。
float sum3=0;
for(m=0;m<L;m++)
sum3=sum3+len[m][0];
sum3=sum3/L;
printf("\n输出重合指数平均数:%.3f%% \n",sum3);
if(6.0<sum3)
{
printf("重合指数在合理范围(在6.5%左右)之间,满足条件,可以解码\n");
//重合指数计算密钥
double chance[26]={0.082,0.015,0.028,0.043,0.127,0.022,0.020,0.061,0.070,0.002,0.008,0.040,0.024,0.067,0.075,0.019,0.001,0.060,0.063,0.091,0.028,0.010,0.023,0.001,0.020,0.001};
int k;
double sum2=0,max=0;
double summ[100];
m=0;
while(m<L){
for(k=0;k<26;k++){
for(i=0;i<26;i++){
sum2=sum2+chance[i]*len[m][(i+k)%26+1];
}
summ[k]=sum2;
sum2=0;
}
for(i=1;i<26;i++)
if(summ[i]>max){
max=summ[i];
l=i;
}
for(i=0;i<26;i++)
summ[i]=0;
max=0;
len1[m]=l;
l=0;
printf("\n");
m++;
}
//打印密钥
char key[10000];
char alp[26]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
n=0;
printf("输出密钥字母对应的数字:\n");
for(n=0;n<L;n++){
for(i=0;i<L;i++){
for(l=0;l<26;l++){
if(l==len1[n])
key[i]=alp[l];
}
n++;
}
}
for(i=0;i<L;i++)
printf("%c ",key[i]);
printf("\n");
}
else
{
printf("\n不满足条件,请重新选择密钥长度!\n");
}
}
void DenKey(){
char key[10000];
char ch,temp;
int L,j=0;
if(getchar()=='\n')
temp=' ';
printf("请输入密钥(小写字母): ");
gets(key);
L=strlen(key);
FILE *fp,*fp1;
fp=fopen("E:\\cipher\\密文.txt","r");
fp1=fopen("E:\\cipher\\明文.txt","w");
if(fp==NULL)
{
printf("文件打开失败!");
}
else{
fscanf(fp,"%c",&ch);
while(!feof(fp))
{
if(ch>='A'&&ch<='Z')
{
fprintf(fp1,"%c",(ch-key[j%L]-'A'+'a'+26)%26+'A');
j++;
}
else if(ch>='a'&&ch<='z')
{
fprintf(fp1,"%c",(ch-key[j%L]-'a'+'a'+26)%26+'A');
j++;
}
fscanf(fp,"%c",&ch);
}
printf("解密结果请查看文档!\n");
fclose(fp1);
fclose(fp);
}
}
Java版本的
package cryptography;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class Main {
private JButton decodeButton;
private JButton encodeButton;
private JTextArea ciphertextArea;
private JTextArea plaintextArea;
private JTextField keyField;
private String ciphertext;
private int keyLength; // 密钥长度
private ArrayList<String> cipherGroup; // 密文的分组
public static void main(String[] args) {
Main main = new Main();
}
Main() {
// 1 初始化框架
JFrame frame = new JFrame();
frame.setSize(Toolkit.getDefaultToolkit().getScreenSize().width / 2,
Toolkit.getDefaultToolkit().getScreenSize().height / 2);
frame.setLocationByPlatform(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("维吉尼亚密文解密和加密");
// 2.1 密文区
ciphertextArea = new JTextArea(8, 135);
JScrollPane ciphertextScrollPane = new JScrollPane(ciphertextArea);
ciphertextArea.setLineWrap(true);
ciphertextScrollPane
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
ciphertextScrollPane
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
// 2.2 明文区
plaintextArea = new JTextArea(8, 135);
JScrollPane plaintextScrollPane = new JScrollPane(plaintextArea);
plaintextArea.setLineWrap(true);
plaintextScrollPane
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
plaintextScrollPane
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
// 2.3 把密文区和明文区加入Panel
JPanel textPanel = new JPanel();
textPanel.setLayout(new BoxLayout(textPanel, BoxLayout.Y_AXIS));
textPanel.add(new JLabel("密文"));
textPanel.add(ciphertextScrollPane);
textPanel.add(new JLabel("明文"));
textPanel.add(plaintextScrollPane);
// 3.1 解密按钮
decodeButton = new JButton("解密");
// 3.2 加密按钮
encodeButton = new JButton("加密");
// 3.3 密钥输入框
JPanel keyPanel = new JPanel();
keyField = new JTextField(10);
JLabel keyJLabel = new JLabel("密钥");
keyPanel.add(keyJLabel);
keyPanel.add(keyField);
// 3.4 加入Panel
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
buttonPanel.add(decodeButton);
buttonPanel.add(encodeButton);
buttonPanel.add(keyPanel);
// 4 把组件加入框架
frame.getContentPane().add(BorderLayout.WEST, textPanel);
frame.getContentPane().add(BorderLayout.EAST, buttonPanel);
frame.setVisible(true);
// 5.1 解密按钮注册事件
// ciphertextArea
// .setText("KCCPKBGUFDPHQTYAVINRRTMVGRKDNBVFDETDGILTXRGUDDKOTFMBPVGEGLTGCKQRACQCWDNAWCRXIZAKFTLEWRPTYCQKYVXCHKFTPONCQQRHJVAJUWETMCMSPKQDYHJVDAHCTRLSVSKCGCZQQDZXGSFRLSWCWSJTBHAFSIASPRJAHKJRJUMVGKMITZHFPDISPZLVLGWTFPLKKEBDPGCEBSHCTJRWXBAFSPEZQNRWXCVYCGAONWDDKACKAWBBIKFTIOVKCGGHJVLNHIFFSQESVYCLACNVRWBBIREPBBVFEXOSCDYGZWPFDTKFQIYCWHJVLNHIQIBTKHJVNPIST");
decodeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (ciphertextArea.getText() != null) {
ciphertext = ciphertextArea.getText();
Friedman();
decodeCipher();
}
}
});
// 5.2 加密按钮注册事件
encodeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (keyField.getText() != null
&& plaintextArea.getText() != null) {
encodePlain(keyField.getText(), plaintextArea.getText());
}
}
});
}
// Friedman测试法确定密钥长度
public void Friedman() {
keyLength = 1; // 密钥长度
double[] IC; // 重合指数
double average; // 平均重合指数
while (true) {
IC = new double[keyLength];
cipherGroup = new ArrayList<String>();
average = 0;
// 1 先根据密钥长度分组
for (int i = 0; i < keyLength; ++i) {
StringBuffer temporaryGroup = new StringBuffer();
for (int j = 0; i + j * keyLength < ciphertext.length(); ++j) {
temporaryGroup.append(ciphertext.charAt(i + j * keyLength));
}
cipherGroup.add(temporaryGroup.toString());
}
// 2 再计算每一组的重合指数
for (int i = 0; i < keyLength; ++i) {
String subCipher = new String(cipherGroup.get(i)); // 子串
HashMap<Character, Integer> occurrenceNumber = new HashMap<Character, Integer>(); // 字母及其出现的次数
// 2.1 初始化字母及其次数键值对
for (int h = 0; h < 26; ++h) {
occurrenceNumber.put((char) (h + 65), 0);
}
// 2.2 统计每个字母出现的次数
for (int j = 0; j < subCipher.length(); ++j) {
occurrenceNumber.put(subCipher.charAt(j),
occurrenceNumber.get(subCipher.charAt(j)) + 1);
}
// 2.3 计算重合指数
double denominator = Math.pow((double) subCipher.length(), 2);
for (int k = 0; k < 26; ++k) {
double o = (double) occurrenceNumber.get((char) (k + 65));
IC[i] += o * (o - 1);
}
IC[i] /= denominator;
}
// 3 判断退出条件,重合指数的平均值是否大于0.065
for (int i = 0; i < keyLength; ++i) {
average += IC[i];
}
average /= (double) keyLength;
if (average >= 0.06) {
break;
} else {
keyLength++;
}
} // while--end
// 打印密钥长度,分组,重合指数,平均重合指数
plaintextArea.append("密钥长度为:");
plaintextArea.append(String.valueOf(keyLength) + "\n\n密文分组及其重合指数为:");
for (int i = 0; i < keyLength; ++i) {
plaintextArea.append("\n" + cipherGroup.get(i) + " 重合指数: "
+ IC[i]);
}
plaintextArea.append("\n\n平均重合指数为: " + String.valueOf(average));
}// Friedman--end
// 再次使用重合指数法确定密钥
public void decodeCipher() {
int[] key = new int[keyLength];
double[] probability = new double[] { 0.082, 0.015, 0.028, 0.043,
0.127, 0.022, 0.02, 0.061, 0.07, 0.002, 0.008, 0.04, 0.024,
0.067, 0.075, 0.019, 0.001, 0.06, 0.063, 0.091, 0.028, 0.01,
0.023, 0.001, 0.02, 0.001 };
// 1 确定密钥
for (int i = 0; i < keyLength; ++i) {
double MG; // 重合指数
int flag; // 移动位置
int g = 0; // 密文移动g个位置
HashMap<Character, Integer> occurrenceNumber; // 字母出现次数
String subCipher; // 子串
while (true) {
MG = 0;
flag = 65 + g;
subCipher = new String(cipherGroup.get(i));
occurrenceNumber = new HashMap<Character, Integer>();
// 1.1 初始化字母及其次数
for (int h = 0; h < 26; ++h) {
occurrenceNumber.put((char) (h + 65), 0);
}
// 1.2 统计字母出现次数
for (int j = 0; j < subCipher.length(); ++j) {
occurrenceNumber.put(subCipher.charAt(j),
occurrenceNumber.get(subCipher.charAt(j)) + 1);
}
// 1.3 计算重合指数
for (int k = 0; k < 26; ++k, ++flag) {
double p = probability[k];
flag = (flag == 91) ? 65 : flag;
double f = (double) occurrenceNumber.get((char) flag)
/ subCipher.length();
MG += p * f;
}
// 1.4 判断退出条件
if (MG >= 0.055) {
key[i] = g;
break;
} else {
++g;
}
} // while--end
} // for--end
// 2 打印密钥
StringBuffer keyString = new StringBuffer();
for (int i = 0; i < keyLength; ++i) {
keyString.append((char) (key[i] + 65));
}
plaintextArea.append("\n\n密钥为: " + keyString.toString());
// 3 解密
StringBuffer plainBuffer = new StringBuffer();
for (int i = 0; i < ciphertext.length(); ++i) {
int keyFlag = i % keyLength;
int change = (int) ciphertext.charAt(i) - 65 - key[keyFlag];
char plainLetter = (char) ((change < 0 ? (change + 26) : change) + 65);
plainBuffer.append(plainLetter);
}
plaintextArea.append("\n\n明文为:\n"
+ plainBuffer.toString().toLowerCase());
}
// 明文加密
public void encodePlain(String key, String plaintext) {
String plaintextUpper = plaintext.toUpperCase(); // 把明文转为大写
String keyUpper = key.toUpperCase(); // 把密钥转为大写
StringBuffer plainToCipher = new StringBuffer(); // 存储密文
int[] move = new int[key.length()]; // 明文移动的位数
// 1 把密钥改为移动的位数
for (int i = 0; i < keyUpper.length(); ++i) {
move[i] = (int) keyUpper.charAt(i) - 65;
}
// 2 明文加密
for (int i = 0; i < plaintext.length(); ++i) {
int letter = (int) plaintextUpper.charAt(i)
+ move[i % keyUpper.length()];
letter = letter > 91 ? (letter - 26) : letter;
char cipherLetter = (char) (letter);
plainToCipher.append(cipherLetter);
}
ciphertextArea.append(plainToCipher.toString());
}
}



