#include <iostream>
#include <bitset>
#include <string>
#include <algorithm>

using namespace std;

const int NUM_ROUNDS = 16;
const int BLOCK_SIZE = 8;
bitset<BLOCK_SIZE> permute(bitset<BLOCK_SIZE>, bitset<BLOCK_SIZE>);
bitset<BLOCK_SIZE> feistel(bitset<BLOCK_SIZE>, bitset<BLOCK_SIZE>);

int main() {
    // Get input message and key
    string message, key;
    cout << 'Enter message (8 bits): ';
    getline(cin, message);
    cout << 'Enter key (8 bits): ';
    getline(cin, key);
    
    // Convert message and key to bitsets
    bitset<BLOCK_SIZE> left_half(message.substr(0, BLOCK_SIZE));
    bitset<BLOCK_SIZE> right_half(message.substr(BLOCK_SIZE, BLOCK_SIZE));
    bitset<BLOCK_SIZE> secret_key(key);
    
    // Perform Feistel rounds
    for (int i = 0; i < NUM_ROUNDS; i++) {
        // Save previous right half in temp variable
        bitset<BLOCK_SIZE> temp = right_half;

        // Calculate new right half using Feistel function
        right_half = left_half ^ feistel(right_half, secret_key);

        // Shift halves
        left_half = temp;
    }

    // Swap halves for final permutation
    swap(left_half, right_half);

    // Combine and output ciphertext
    bitset<BLOCK_SIZE*2> ciphertext(left_half.to_string() + right_half.to_string());
    cout << 'Ciphertext: ' << ciphertext.to_string() << endl;

    // Decrypt ciphertext using same process in reverse
    for (int i = NUM_ROUNDS-1; i >= 0; i--) {
        bitset<BLOCK_SIZE> temp = left_half;
        left_half = right_half;
        right_half = temp ^ feistel(right_half, secret_key);
    }
    swap(left_half, right_half);

    // Output decrypted message
    cout << 'Decrypted message: ' << (left_half.to_string() + right_half.to_string()) << endl;

    return 0;
}

// Feistel function
bitset<BLOCK_SIZE> feistel(bitset<BLOCK_SIZE> right_half, bitset<BLOCK_SIZE> secret_key) {
    return permute(right_half, secret_key);
}

// Permutation function
bitset<BLOCK_SIZE> permute(bitset<BLOCK_SIZE> input, bitset<BLOCK_SIZE> key) {
    string key_string = key.to_string();
    int shift_amount = stoi(key_string.substr(3,5), nullptr, 2);
    bitset<BLOCK_SIZE> result(input.to_string());
    result <<= shift_amount;
    return result;
}

Example Usage:

> Enter message (8 bits): 01101100
> Enter key (8 bits): 10101010
Ciphertext: 0101111101100110
Decrypted message: 01101100
C++ Feistel Cipher Implementation - Simple Encryption and Decryption

原文地址: https://www.cveoy.top/t/topic/ntMN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录