解密不完整C++和 WCHAR

Incomplete decryption C++ and WCHAR

本文关键字:WCHAR C++ 解密      更新时间:2023-10-16

编写一个用于加密和解密WCHAR的模块C++

static UINT OGL_KEYTABLE_SIZE = 22;
static int oglKeyTable[] = { 10, 71, 45, 13, 16, 19, 49, 55, 78, 125, 325, 
10, 71, 45, 13, 16, 19, 49, 55, 78, 125, 325 };
PCWSTR encryptString(PCWSTR Message)
{
    int size = lstrlenW(Message);
    WCHAR Encrypted[200];
    for (wchar_t i = 0; i < size; i++) {
        if (((Message[i] + oglKeyTable[i%OGL_KEYTABLE_SIZE]) <= 255)
            &&
            ((Message[i] + oglKeyTable[i%OGL_KEYTABLE_SIZE]) != 0)
            )
            Encrypted[i] = (Message[i] + oglKeyTable[i%OGL_KEYTABLE_SIZE]);
        else
            Encrypted[i] = Message[i];
    }
    Encrypted[size]= '';
    int Esize = lstrlenW(Encrypted);
    printf("n%ls", Message);
    printf("n%ls", Encrypted);
    size = lstrlenW(Encrypted);
    WCHAR Decrypted[200];
    for (wchar_t i = 0; i < size; i++) {
        if (Encrypted[i] <= 255 ) {
            Decrypted[i] = (Encrypted[i] - oglKeyTable[i%OGL_KEYTABLE_SIZE]);
        }
    }
    Decrypted[size] = '';
    printf("n%ls", Decrypted);
    return Encrypted;
}

但是逻辑在某处失败,我的解密不完整

  • 原文留言 : Apple tastes good and it__is__very__good__for health !
  • 加密消息:K+¥yu3Ñÿ-±e}gö|¦wQÿ+ß s+îlyåÉû-Grâªît¦éòû¡po|gòrq¦ÑƒnP
  • 解密的消息:苹果品尝

您的密码存在一些严重问题。您只允许 [1, 255] 范围内的密文值,但使用了 325 的两倍密钥组件,然后将其添加到明文中。在加密期间,在这些情况下,您可以决定明文字符也是密文字符。但是在解密过程中,您不会区分加密的两个分支。

WCHAR Decrypted[200];
for (wchar_t i = 0; i < size; i++) {
    if ((Encrypted[i] - oglKeyTable[i%OGL_KEYTABLE_SIZE]) > 0) {
        Decrypted[i] = (Encrypted[i] - oglKeyTable[i%OGL_KEYTABLE_SIZE]);
    } else {
        Decrypted[i] = Encrypted[i];
    }
}

我不确定这是否适用于每个关键组件,但这是问题的正确原因,因为在解密过程中您会得到负字符。缺少的第一个字符是 i == 10 与 325 关键组件一致。

更好的方法是保留键并使用取模运算符保持在正确的范围内:

Encrypted[i] = ((Message[i] + oglKeyTable[i%OGL_KEYTABLE_SIZE]) % 255) + 1;

以及在解密过程中与此等效的相反。如果这样做,您将不再需要这两个分支。它与维吉涅尔密码有一些相似之处。


旧解决方案:

问题是你使用lstrlenW来获取密文的长度,该密文基于空终止返回它。密文看起来是随机的,因此它绑定到密文中任何位置字节。您应该使用size值进行解密,而不是用 lstrlenW(Encrypted) 覆盖它。