其他分享
首页 > 其他分享> > 多表代换密码的加密与解密

多表代换密码的加密与解密

作者:互联网

#include <iostream>
#include <vector>

#define rap(a,b) for(int a=0;a<b;++a)
using namespace std;
string encypt(string m, double a[][4], double b[]) {
    string ans;
    for (int i = 0; i < 4; ++i) {
        int tmp = 0;
        for (int j = 0; j < 4; ++j) {
            tmp += a[i][j] * (m[j] - 'A');
        }
        tmp += b[i];
        ans += tmp % 26 + 'A';
    }
    return ans;
}
string decypt(string c, double a[][4], double b[]) {
    string ans;
    int cc[4];
    for (int i = 0; i < 4; ++i)cc[i] = (int)(c[i] - 'A' - b[i] + 26) % 26;
    for (int i = 0; i < 4; ++i) {
        int tmp = 0;
        for (int j = 0; j < 4; ++j) {
            tmp += a[i][j] * cc[j];
        }
        ans += tmp % 26 + 'A';
    }
    return ans;
}
int main() {
    double a[4][4] = {
    3,13,21,9,
    15,10,6,25,
    10,17,4,8,
    1,23,7,2
    };
    double b[4] = { 1,21,8,17 };
    string c = "PLEASE SEND ME TWO BOOKS MY CREDIT CARD NO IS SIX ONE TWO ONE THREE EIGHT SIX ZERO ONE SIX EIGHT FOUR NINE SEVEN ZERO TWO";
    //记录空格位置并去空格 
    vector<int>pos;
    int tmp = c.find(' ');
    while (tmp != -1)
    {
        pos.push_back(tmp);
        c.erase(tmp, 1);
        tmp = c.find(' ');
    }
    //加密 
    int i = 0;
    string m;
    while (i != c.size()) {
        m += encypt(c.substr(i, 4), a, b);
        i += 4;
    }
    //解密 
    double a2[4][4] = {
    23,13,20,5,
    0,10,11,0,
    9,11,15,22,
    9,22,6,25
    };
    string c2;
    i = 0;
    while (i != m.size()) {
        c2 += decypt(m.substr(i, 4), a2, b);
        i += 4;
    }
    //还原空格 
    for (i = pos.size() - 1; i >= 0; --i)c.insert(pos[i], " ");
    for (i = pos.size() - 1; i >= 0; --i)m.insert(pos[i], " ");
    for (i = pos.size() - 1; i >= 0; --i)c2.insert(pos[i], " ");
    cout << c << endl;
    cout << m << endl;
    cout << c2 << endl;
    return 0;
}

标签:tmp,多表,string,int,代换,解密,pos,ans,size
来源: https://blog.csdn.net/cwindyc/article/details/123611854