密码学原理_Crypto++实现一次性密码本(OTP)

来源:互联网 发布:淘宝卖家论坛首页 编辑:程序博客网 时间:2024/06/06 13:02

Requirements

请用 Crypto++实现一个 One Time Pad。请提交全部源代码,以及把“hello world” 加密后产生的密文。

Compilation Options

g++ -g3 -O2 -Wall -Wextra -o opt opt.cpp -lcryptopp -std=c++11

Example

Welcome to Sunny's One Time Pad.Wish you a good trip.Please input you plaintext:Hello, WorldThe length of plaintext is 12.plaintext:    48 65 6c 6c 6f 2c 20 57 6f 72 6c 64key:          E7 5A D3 FE 8B 4B 84 6A 5B 28 E6 60ciphertext:   af 3f bf 92 e4 67 a4 3d 34 5a 8a 04

Description

Since some asciis are invisible, ciphertexts are expressed by hex.

Source Code

#include <iostream>#include <sstream>#include <iomanip>#include <cryptopp/osrng.h>#include <cryptopp/hex.h>#include <cryptopp/filters.h>using namespace std;using namespace CryptoPP;void print_hex(string, int);int main() {    string prologue = "Welcome to Sunny's One Time Pad.\nWish you a good trip.";    cout << prologue << endl;    cout << "Please input you plaintext:" << endl;    string plaintext;    getline(cin, plaintext);    int lengthOfText = plaintext.length();    cout << "The length of plaintext is " << lengthOfText << "." << endl;    RandomPool prng;    SecByteBlock seed(lengthOfText);    OS_GenerateRandomBlock(false, seed, seed.size());    prng.IncorporateEntropy(seed, seed.size());    string key;    HexEncoder keystring(new StringSink(key));    keystring.Put(seed, seed.size());    keystring.MessageEnd();    stringstream ss;    for (auto &it: plaintext)        ss << hex << (int)it;    string mystr = ss.str();    cout << "plaintext: " << '\t';    print_hex(mystr, lengthOfText);    cout << "key: " << '\t' << '\t';    print_hex(key, lengthOfText);    string ciphertext;    int *i1 = new int[lengthOfText * 2];    int *i2 = new int[lengthOfText * 2];    int *i3 = new int[lengthOfText * 2];    /*     * Core Operation: XOR operation     * XOR plaintext and key by bit     */    for (int i = 0; i < lengthOfText * 2; i++) {        if (key[i] >= 'A')            i1[i] = key[i] - 'A' + 10;        else            i1[i] = key[i] - '0';        if (mystr[i] >= 'a')            i2[i] = mystr[i] - 'a' + 10;        else            i2[i] = mystr[i] - '0';        i3[i] = i1[i] ^ i2[i];    }    int *i4 = new int[lengthOfText];    for (int i = 0; i < lengthOfText; i++) {        i4[i] = i3[i * 2] * 16 + i3[i * 2 + 1];    }    cout << "ciphertext: " << '\t';    for (int i = 0; i < lengthOfText; i++) {        cout << setfill('0') << setw(2) << hex << i4[i] << ' ';    }    cout << endl;    return 0;}void print_hex(string str, int length) {    for (int i = 0; i < length * 2; i++) {        cout << hex << str[i];        if (i % 2) cout << ' ';    }    cout << endl;}