密码技术:凯撒密码

凯撒密码(凯撒用过的所以叫做凯撒密码)是一种简单的加密技术,将字母平移,平移后的字母代替原先的意思。

这里平移3个字母以后,D就代表a。

实现:

class caesarCipher
{
public:
    static QByteArray createCipher(const QByteArray & array,int translation)//加密 参数:待加密内容,平移位数
    {
        QMap<signed char,signed char> map;
        auto trsC = static_cast<signed char>(translation);
        for (auto c = 'A';c <= 'Z';++c)
        {
            map[c] = c + trsC;
        }
        for (auto c = 'a';c <= 'z';++c)
        {
            map[c] = c + trsC;
        }

        QByteArray cipher;
        for (auto i = 0;i < array.size();++i)
        {
            cipher.append(map.value(array.at(i)));
        }
        return cipher;
    }

    static QByteArray decrypt(const QByteArray & cipher,int translation)//解密 参数:待解密内容,平移位数
    {
        QMap<signed char,signed char> map;
        auto trsC = static_cast<signed char>(translation);
        for (auto c = 'A';c <= 'Z';++c)
        {
            map[c] = c + trsC;
        }
        for (auto c = 'a';c <= 'z';++c)
        {
            map[c] = c + trsC;
        }

        QByteArray data;
        for (auto i = 0;i < cipher.size();++i)
        {
            data.append(map.key(cipher.at(i)));
        }
        return data;
    }
};

int main(int argc, char *argv[])
{
    QByteArray array = "helloWorld";
    auto cipher = caesarCipher::createCipher(array,8);
    qDebug()<<"加密后:"<<cipher.toHex();
    qDebug()<<"解密后:"<<caesarCipher::decrypt(cipher,8);
}

上面是一种简单的实现,大小写字母平移一定位数。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
密码是一种简单且广为人知的加密技术,它是一种替换加密的技术,将明文中的所有字母按照字母表的顺序向后偏移固定数目后变成密文。在Python中解决密码可以使用以下步骤: 1. 首先,定义一个函数来实现密码的加密和解密操作。该函数需要接收两个参数:明文和偏移量。偏移量可以是正数(向后偏移)或负数(向前偏移)。 2. 在函数内部,使用一个循环来遍历明文中的每个字符。对于每个字符,根据其在字母表中的位置进行偏移。可以使用内置的ord()函数将字符转换为ASCII码,并使用chr()函数将偏移后的ASCII码转换回字符。 3. 注意处理大写字母和小写字母的情况。可以使用内置的isupper()函数和islower()函数来判断字符是否为大写或小写,并根据情况进行相应的处理。 4. 最后,返回加密或解密后的结果。 以下是一个示例的密码加密和解密函数的实现: ```python def caesar_cipher(text, shift): result = "" for char in text: if char.isalpha(): if char.isupper(): result += chr((ord(char) - 65 + shift) % 26 + 65) else: result += chr((ord(char) - 97 + shift) % 26 + 97) else: result += char return result ``` 使用该函数,你可以将明文加密为密码,也可以将密码解密回明文。例如,使用偏移量3对明文"hello"进行加密: ```python plaintext = "hello" shift = 3 ciphertext = caesar_cipher(plaintext, shift) print(ciphertext) # 输出:"khoor" ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值