凯撒密码(凯撒用过的所以叫做凯撒密码)是一种简单的加密技术,将字母平移,平移后的字母代替原先的意思。
这里平移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);
}
上面是一种简单的实现,大小写字母平移一定位数。