凯撒加密解密C++
Caesar Encryption and decryption C++
我想知道如何将加密的 ASCII 范围限制在 32 - 126 之间。
对于我们的任务,我们应该将字符串转换为字符,并且 encrypt/decrypt 每个单独的字符。
我目前正在使用它进行加密
int value = (value-32+shift)%95+32 //value is the current ascii value of a
//character
//the first shift is given by the user with regards
//to how many shifts he wants to do to the right
这个用于解密
int value = (value-32-shift)%95+32
我的加密工作正常(当我引用解密函数时)但我的解密没有按预期工作。
补充说明:我们只需要在编码的时候右移一下,就给了一个字符串给我们整个程序加解密("This is C++")
Give shift: 3
Wklv#lv#F..
DECODE
Wklv#lv#F.. //must be 'THIS is C++'
ENCODE //shift=15
This is C++ //must be 'cwx#/x#/R::'
DECODE
EYZdpZdp4{{ //must be 'THIS is C++'
ENCODE //shift=66
cwx#/x#/R:: //must be "8LMWbMWb'mm"
DECODE
This is C++
ENCODE //shift=94
cwx#/x#/R:: //must be 'SGHR~hr~B**'
DECODE
This is C++
注意:正在添加更多代码说明
您的问题在 Modulo operator with negative values 中有解释。我不确定这是否完全相同。问题是解码像“!”这样的密码字符移动多于一个(例如“3”)
int value = (value-32-shift)%95+32
= ('!'-32-3)%95+32
= (33-32-3)%95+32
= (-2)%95 + 32
= -2 + 32
= 30
糟糕。您需要使用:
int value = (value-32+(95-shift))%95+32
问题是 (value-32-shift)
可能会变成负数。模运算不 'wrap around',但实际上 'mirrors' 在零附近(如果您想知道原因,请参阅 this question and answer)。
为确保您的值保持正值,请在进行模运算之前添加 95:
int value = (value-32-shift+95)%95+32
我想知道如何将加密的 ASCII 范围限制在 32 - 126 之间。
对于我们的任务,我们应该将字符串转换为字符,并且 encrypt/decrypt 每个单独的字符。
我目前正在使用它进行加密
int value = (value-32+shift)%95+32 //value is the current ascii value of a
//character
//the first shift is given by the user with regards
//to how many shifts he wants to do to the right
这个用于解密
int value = (value-32-shift)%95+32
我的加密工作正常(当我引用解密函数时)但我的解密没有按预期工作。
补充说明:我们只需要在编码的时候右移一下,就给了一个字符串给我们整个程序加解密("This is C++")
Give shift: 3
Wklv#lv#F..
DECODE
Wklv#lv#F.. //must be 'THIS is C++'
ENCODE //shift=15
This is C++ //must be 'cwx#/x#/R::'
DECODE
EYZdpZdp4{{ //must be 'THIS is C++'
ENCODE //shift=66
cwx#/x#/R:: //must be "8LMWbMWb'mm"
DECODE
This is C++
ENCODE //shift=94
cwx#/x#/R:: //must be 'SGHR~hr~B**'
DECODE
This is C++
注意:正在添加更多代码说明
您的问题在 Modulo operator with negative values 中有解释。我不确定这是否完全相同。问题是解码像“!”这样的密码字符移动多于一个(例如“3”)
int value = (value-32-shift)%95+32
= ('!'-32-3)%95+32
= (33-32-3)%95+32
= (-2)%95 + 32
= -2 + 32
= 30
糟糕。您需要使用:
int value = (value-32+(95-shift))%95+32
问题是 (value-32-shift)
可能会变成负数。模运算不 'wrap around',但实际上 'mirrors' 在零附近(如果您想知道原因,请参阅 this question and answer)。
为确保您的值保持正值,请在进行模运算之前添加 95:
int value = (value-32-shift+95)%95+32