简单仿射密码加密 [英] Simple Affine Cipher Encrpytion Decryption

查看:371
本文介绍了简单仿射密码加密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写两个使用仿射密码对消息进行加密和解密的函数。出于某种原因,我的加密和解密过程差几个字母。我认为问题与ASCII码不匹配a = 0,z = 25格式有关。

I am writing two functions that encrypt and decrypt messages using an affine cipher. For some reason, my encryption and decryption are off by a few letters. I feel the issue is related to the ASCII numbers not matching the a=0, z=25 format. Could someone please help me figure out what's going on?

Cleopatra 应该加密为 whkcjilxi

MZDVEZC 应该解密为 anthony

但是,我得到的是

埃及艳后= ZKNFMLOAL

MZDVEZC = NAGUBAL

主要功能:

int main() {
    plaintext = "cleopatra";
    ciphertext = affine_encrypt(plaintext, 7, 8);

    cout << "4. Encryption of the plaintext: " << plaintext << endl;
    cout << "   Key: 7x+8" << endl;
    cout << "   Ciphertext: " << ciphertext;
    cout << endl << endl;

    ciphertext = "MZDVEZC";
    plaintext = affine_decrypt(ciphertext, 5, 12);

    cout << "5. Decryption of the ciphertext: " << ciphertext << endl;
    cout << "   Key: 5x+12" << endl;
    cout << "   Inverse of 5 is " << affineInverse(5) << endl;
    cout << "   Plaintext: " << plaintext << endl << endl;
    return 0;
}



string affine_decrypt(string message, int a, int b)
{
    string dtxt;
    for (int i = 0; i < message.length(); i++)
    {
        dtxt = dtxt + (char)(((affineInverse(a)*(message[i] - b) % 26)) + 65);
    }

    return dtxt;
}

string affine_encrypt(string message, int a, int b)
{
    string ctext = "";

    for (int i = 0; i < message.length(); i++)
    {
        ctext = ctext + (char)((((a * message[i]) + b) % 26) + 65);
    }

    return ctext;
}

int affineInverse(int input)
{
    int check = 0;

    for (int i = 0; i < 26; i++)
    {
        check = (input * i) % 26;

        if (check == 1)
        {
            check = i;
        }
    }

    return check;
}


推荐答案

您忘记减去<$在应用仿射加密之前,先从字符中获取c $ c> a

ctext = ctext + (char)((((a * ( message[i] - 'a' ) ) + b) % 26) + 65);

如果使用大写字母,则应使用 A。通常,将它们全部转换为或< href = http://www.cplusplus.com/reference/locale/tolower/ rel = nofollow noreferrer>小写。通常在古典密码学中首选大写。

If you are using capital letters, you should use 'A'. In general, it is a good idea to convert all of them into upper or lower case. Usually in classical Cryptography upper case is preferred.

检查解密就交给您了。

更新:解密中的陷阱

您忘记了构造'A'消息[i]

You forgot to substruct 'A' from the message[i]

-'A'-26 结果可能为负。

When you substruct message[i] - 'A' - 26 the result can be negative. You have to make sure that it is positive.

此内联函数

inline int positive_modulo(int i, int n) {
    return (i % n + n) % n;
}

来自此答案可帮助您始终从模数中获得肯定的结果。

from this answer helps you to get always a positive result from modulus.

此外,从编程的角度出发,请先尝试对您解密的内容进行解密加密。

Also, from the programmatical way, first try to decrypt what you encrypt.

这篇关于简单仿射密码加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆