Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- #include <string>
- #include <map>
- #include <random>
- using namespace std;
- std::random_device dev;
- std::mt19937 rng(dev());
- const std::string nulls = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- std::uniform_int_distribution<std::mt19937::result_type> dist_nulls(0, nulls.length()-1);
- std::string key = "DBECA";
- std::map<int, int> key_order;
- void set_permutation_order(){
- for(int i = 0; i < key.length(); ++i)
- key_order[key[i]] = i;
- }
- void normalize(std::string& str){
- str.erase(std::remove_if(str.begin(), str.end(), ::isspace), str.end());
- std::transform(str.begin(), str.end(), str.begin(), ::toupper);
- }
- std::string columnar_transpos_encrypt(std::string msg){
- normalize(msg);
- //std::cout << msg << '\n';
- int cols = key.length();
- int rows = msg.length()/cols;
- if(msg.length() % cols)
- ++rows;
- char** matrix = new char*[rows];
- for(int i = 0; i < rows; ++i)
- matrix[i] = new char[cols];
- int ind{0};
- for(int row = 0; row < rows; ++row){
- for(int col = 0; col < cols; ++col){
- if(ind >= msg.length())
- matrix[row][col] = nulls[dist_nulls(rng)];
- else
- matrix[row][col] = msg[ind++];
- }
- }
- //std::cout << rows << " " << cols << '\n';
- std::string encrypted{};
- int col_order{};
- for(auto it = key_order.begin(); it != key_order.end(); ++it){
- col_order = it->second;
- for(int row = 0; row < rows; ++row){
- encrypted += matrix[row][col_order];
- }
- }
- /*
- for debug purpose
- for(int row = 0; row < rows; ++row){
- for(int col = 0; col < cols; ++col){
- std::cout << matrix[row][col] << ' ';
- }
- std::cout << '\n';
- }
- */
- for(int i = 0; i < rows; ++i)
- delete[] matrix[i];
- delete[] matrix;
- return encrypted;
- }
- int main()
- {
- std::string ms = "Which wristwatches are Swiss wristwatches";
- set_permutation_order();
- std::string res = columnar_transpos_encrypt(ms);
- std::cout << res;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement