Game Programming 凯撒密码加密
程序员文章站
2024-03-16 18:16:04
...
凯撒密码加密
它使用一种非常简单的算法(凯撒密码)加密或解密流经它的数据。 加密时,它将明文中的每个字符移动由**定义的多个字符。 它在解密时进行相反的操作。 因此,如果**为 2,明文字符为 a,则密文变为 c。 用** 4 解密 z 将产生值 v。
CaesarCipherDevice.h
#ifndef CAESARCIPHERDEVICE_H
#define CAESARCIPHERDEVICE_H
#include <QIODevice>
class CaesarCipherDevice : public QIODevice
{
Q_OBJECT
Q_PROPERTY(int key READ key WRITE setKey)
public:
explicit CaesarCipherDevice(QObject *parent = 0);
void setBaseDevice(QIODevice *dev)
{
m_baseDevice = dev;
}
QIODevice *baseDevice() const
{
return m_baseDevice;
}
void setKey(int k)
{
m_key = k;
}
inline int key() const
{
return m_key;
}
bool open(OpenMode mode);
protected:
qint64 writeData(const char *data, qint64 len);
qint64 readData(char *data, qint64 maxlen);
private:
int m_key;
QIODevice *m_baseDevice;
};
#endif // CAESARCIPHERDEVICE_H
CaesarCipherDevice.cpp
#include "caesarcipherdevice.h"
#include <QDebug>
CaesarCipherDevice::CaesarCipherDevice(QObject *parent) : QIODevice(parent)
{
m_key = 0;
m_baseDevice = 0;
}
bool CaesarCipherDevice::open(OpenMode mode)
{
if(!m_baseDevice)
{
qWarning("CaesarCipherDevice::open: No base device");
setErrorString(tr("No base device"));
return false;
}
if(!m_baseDevice->isOpen())
{
qWarning("CaesarCipherDevice::open: Base device is not open");
setErrorString(tr("Base device is not open"));
return false;
}
if(m_baseDevice->openMode() != mode)
{
qWarning("CaesarCipherDevice::open: Base device has a different openMode()");
setErrorString(tr("Base device has a different openMode()"));
return false;
}
return QIODevice::open(mode);
}
qint64 CaesarCipherDevice::writeData(const char *data, qint64 len)
{
QByteArray byteArray;
byteArray.resize(len);
for(int i = 0; i < len; ++i) {
byteArray[i] = data[i] + m_key;
}
int written = m_baseDevice->write(byteArray);
emit bytesWritten(written);
return written;
}
qint64 CaesarCipherDevice::readData(char *data, qint64 maxlen)
{
QByteArray baseData = m_baseDevice->read(maxlen);
const int size = baseData.size();
for(int i = 0; i < size; ++i)
{
data[i] = baseData[i] - m_key;
}
return size;
}
main.cpp
#include <QByteArray>
#include <QBuffer>
#include <QtDebug>
#include "CaesarCipherDevice.h"
int main(int, char **)
{
QByteArray ba = "plaintext";
QBuffer buf;
buf.open(QIODevice::WriteOnly);
CaesarCipherDevice encrypt;
encrypt.setKey(3);
encrypt.setBaseDevice(&buf);
encrypt.open(buf.openMode());
encrypt.write(ba);
qDebug() << buf.data();
CaesarCipherDevice decrypt;
decrypt.setKey(3);
decrypt.setBaseDevice(&buf);
buf.open(QIODevice::ReadOnly);
decrypt.open(buf.openMode());
qDebug() << decrypt.readAll();
return 0;
}
推荐阅读