所以我有一个加密函数
std::string encrypt(std::string text, int s)
{
std::string result = "";
// traverse text
for (int i = 0; i < text.length(); i++)
{
// apply transformation to each character
// Encrypt Uppercase letters
if (isupper(text[i]))
result += char(int(text[i] + s - 65) % 26 + 65);
// Encrypt Lowercase letters
else
result += char(int(text[i] + s - 97) % 26 + 97);
}
// Return the resulting string
return result;
}
可以这样使用:
std::string ans = "AABBCCDDEEFFGGH"
std::time_t result = std::time(nullptr);
DWORD Hours = ((result / 60) / 60) / ans.length();
std::cout << "Output: " << encrypt(ans, Hours) << std::endl;
我试着创建解密函数,但是失败得很惨,结果是:
┐┐ªªºº¿¿⌐⌐¬¬½½¼
有人能帮忙吗?
您在decrypt
中遇到的问题肯定与在encrypt
中遇到的问题相同。
您不能确保int(text[i]+s-65)
中的text[i]+s
溢出,因此对于大的s
,对于某些s
,encrypt
已经失败,而此时decrypt
也会失败。
假设decrypt
除了溢出之外是正确的,您可以使用以下方法来解决该问题:将s
限制在0
到26
:int(text[i]+(s%26)-65)
的范围内,并在decrypt
中执行相应的操作。