Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <string>
- using namespace std;
- uint32_t cShiftR(uint32_t number)
- {
- uint32_t mask = 0b111;
- return (number >> 3) | ((number & mask) << 29);
- }
- uint32_t cShiftL(uint32_t number)
- {
- uint32_t mask = 0b111;
- mask <<= 29;
- return (number << 3) | ((number & mask) >> 29);
- }
- void decode(vector<uint32_t> data)
- {
- int key;
- cout << "Enter key: ";
- cin >> key;
- if (data.size() == 0) {
- string str;
- cin.ignore();
- getline(cin, str);
- if (str.size() % 4 != 0) {
- cout << "Wrong string" << endl;
- return;
- }
- int length = str.size() / 4;
- data = vector<uint32_t>(length, 0);
- for (int i = 0; i < length * 4; i++) {
- data[i / 4] |= str[i] << 8 * (i % 4);
- }
- }
- int length = data.size();
- srand(key);
- for (int i = 0; i < length; i++) {
- uint32_t gamma = (rand() << 16) | rand();
- data[i] = cShiftR(data[i]) ^ gamma;
- }
- cout << "Decoded: ";
- for (int i = 0; i < length; i++)
- for (int j = 0; j < 4; j++) {
- char c = (char)(data[i] >> 8 * j);
- if (c != '\12')
- cout << c;
- }
- cout << endl;
- }
- void encode()
- {
- int key;
- cout << "Enter key: ";
- cin >> key;
- string str;
- cout << "Enter string: ";
- cin.ignore();
- getline(cin, str);
- int length = str.size() / 4 + (str.size() % 4 != 0);
- vector<uint32_t> encoded(length, 0);
- for (int i = 0; i < length * 4; i++) {
- char c = ((str.size() > i) ? str[i] : '\12');
- encoded[i / 4] |= c << 8 * (i % 4);
- }
- srand(key);
- for (int i = 0; i < length; i++) {
- uint32_t gamma = (rand() << 16) | rand();
- encoded[i] = cShiftL(encoded[i] ^ gamma);
- }
- cout << "Encoded: ";
- for (int i = 0; i < length; i++)
- for (int j = 0; j < 4; j++)
- cout << (char)(encoded[i] >> 8 * j);
- cout << endl;
- decode(encoded);
- }
- int main()
- {
- cout << "Encode (0) or decode (1): ";
- int state;
- cin >> state;
- if (state == 0) {
- encode();
- } else {
- decode({});
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment