LoginSignup
0
0

More than 3 years have passed since last update.

[C++]XORによる1文字の暗号化, 復号

Last updated at Posted at 2020-05-30

環境

  • Ubuntu 18.04.4 LTS
  • g++ 7.5.0
  • GNU Make 4.1

はじめに

自分の知識のC++が旧石器時代のものだったので, C++17の機能を使ってやってみました.
また, 簡単のために, 文字列ではなく, 文字を対象とします.
1文字暗号化(復号)できれば, 文字列にも応用できると思います.

おおまかな流れ

  • aASCIIの2進数で表示
  • 鍵である8bitのkey1でXORによる暗号化, 復号
  • 確認のためにto_integerで整数型へ変換した後, ifで評価

仕組み

8bitの並びAと, 8bitの並びB(ただし, AとBは異なる)をXORしたものをCを,BでXORするとAに戻る.

例)
aはASCIIの2進数で0110 0001.
これを, 鍵1011 0011でXORすると1101 0010.
これを鍵1011 0011でXORすると0110 0001.

ソース

main.cpp

#include <cstddef>
#include <iostream>

using namespace std;

byte encode_xor(byte input, byte encode_key);
byte decode_xor(byte input, byte decode_key);

int main(void){

    byte a_ascii{0b01100001};
    byte key1{0b10110011};

    if(to_integer<uint8_t>(encode_xor(a_ascii, key1)) == 0b11010010){
        cout << "sucsess" << endl;
    }

    byte encoded{0b11010010};

    if(to_integer<uint8_t>(decode_xor(encoded, key1)) == 0b01100001){
        cout << "sucsess" << endl;
    }

return 0;
}

byte encode_xor(byte input, byte encode_key){
    return input ^ encode_key;
}

byte decode_xor(byte input, byte decode_key){
    return input ^ decode_key;
}

Makefile(マークダウンがうまく行かなかった)

build:
    g++ -std=c++17 -g -o main main.cpp

run:
    ./main

参考文献

暗号技術入門 第3版 秘密の国のアリス (結城 浩 著)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0