【原创】Vigenere加密

Vigenere加密的原理:

假设有一Vigenere密钥为(2,4,8,12,7),欲对明文helloworld加密

将明文helloworld的第一个字母移动2个位置,第二个位置移动4个位置,…,第5个字母移动7个位置,然后再从密钥的头部开始循环,直到将明文hellowrold全部转换为密文

 

#include <iostream>
#include <ctime>
#define KEYLEN 10  //密钥的长度 
using namespace std;
 
void Encipher(char* plain,char* cipher,int key[]);
void Cipher(char* cipher,int key[]);
int main()
{
    char* cipher=new char[27]; 
    srand((unsigned)time(0));
    int key[KEYLEN]; //密钥 
    for(int i=0;i<KEYLEN;i++)  key[i]=rand()%15+5; //生成密钥 
    
    Encipher("hellowrold!iamleukotrichia",cipher,key); //生成密文并存储在cipher中 
    cout <<"密文: " <<cipher <<endl;
    Cipher(cipher,key);
    system("pause");
    return 0;
}
 
void Encipher(char* plain,char* cipher,int key[])
{
      int i=0;
      while(*plain)
      {
           if(i>=KEYLEN) i=0;       
           *cipher=(*plain++)+key[i];
           cipher++;  
           i++;     
      }
      *cipher='\0';
      return;   
 
}
void Cipher(char* cipher,int key[])
{
      int i=0;
      cout <<"明文: ";  
      while(*cipher)
      {
           if(i>=KEYLEN) i=0;       
           cout <<(char)((*cipher++)-key[i]); 
           i++;     
      }
      cout <<endl;
      return;   
}
posted @ 2009-11-17 20:16  leukotrichia  阅读(727)  评论(0编辑  收藏  举报