维吉尼亚密码应用

//Virginia密码
/*理解算法最重要,最好自己动手实现试试看,可以使用MFC写一个简单的交互界面*/
#include<iostream> 
#include<cstring> 

using namespace std; 
#define MINCHAR 32 
#define CHARSUM 94 
char table[CHARSUM][CHARSUM]; 
bool Init(); 
bool Encode(char* key, char* source, char* dest); 
bool Dncode(char* key, char* source, char* dest); 
int main() 
{ //    char keyV1[256]="k1"; 
//  char keyV2[256]="k2";
    if(!Init()) 
    { 
        cout << "初始化错误!" << endl; 
        return 1; 
    } 
    char key[256]; 
    char str1[256];
    char str2[256]; 
    int operation; 
    while(1) 
    { 
        do 
        { 
            cout << "请选择一个操作:1. 加密; 2. 解密; -1. 退出\n"; 
            cin >> operation; 
        }while(operation != -1 && operation != 1 && operation != 2); 

        if(operation == -1) 
            return 0; 
        else if(operation == 1)//加密 
        { 
            cout << "请输入密钥:"; 
            cin >> key; 
            cout << "请输入待加密字符串:"; 
            cin >>str1;
            Encode(key, str1, str2); 

            cout << "加密后的字符串:---" << str2 << endl; 
            for(int index=0;index<strlen(str1);index++)
            {
                printf("0x%0X,",str2[index]);
            }
        } 

        else if(operation == 2)//解密 
        { 
            cout << "请输入密钥:"; 
            cin >> key; 
            cout << "请输入待解密字符串:"; 
            cin >> str1; 
            Dncode(key, str1, str2); 
            cout << "解密后的字符串:" << str2 << endl; 
        } 
        cout << endl; 
    } 
    return 0; 
} 

// 初始化维吉尼亚方阵 
bool Init() 
{ 
    int i, j; 
    for(i = 0; i < CHARSUM; i++) 
    { 
        for(j = 0; j < CHARSUM; j++) 
        { 
            table[i][j] = MINCHAR + (i + j) % CHARSUM; 
        } 
    } 
    return true; 
} 
// 加密 
// key:密钥 
// source:待加密的字符串 
// dest:经过加密后的字符串 
bool Encode(char* key, char* source, char* dest) 
{ 
    char* tempSource = source; 
    char* tempKey = key; 
    char* tempDest = dest; 
    do 
    { 
        *tempDest = table[(*tempKey) - MINCHAR][(*tempSource) - MINCHAR]; 
        tempDest++; 
        if(!(*(++tempKey))) 
            tempKey = key; 
    }while(*tempSource++); 
    dest[strlen(source)] = 0; 
    return true; 
} 

// 解密 
// key:密钥 
// source:待解密的字符串 
// dest:经过解密后的字符串 

bool Dncode(char* key, char* source, char* dest) 
{ 
    char* tempSource = source; 
    char* tempKey = key; 
    char* tempDest = dest; 
    char offset; 
    do 
    { 
        offset = (*tempSource) - (*tempKey); 
        offset = offset >= 0 ? offset : offset + CHARSUM; 
        *tempDest = MINCHAR + offset; 
        tempDest++; 
        if(!(*(++tempKey))) 
            tempKey = key; 
    }while(*++tempSource); 
    dest[strlen(source)] = 0; 
    return true; 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值