Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <limits.h>
- #include <fstream>
- void CheckAsciiPos(short& pos) {
- if (std::numeric_limits<char>::is_signed) {
- if (pos > 127) //if it leaves ascii table :)
- pos -= 256;
- if (pos < -128)
- pos += 256;
- }
- else {
- if (pos > 255) //if it leaves ascii table :)
- pos -= 256;
- if (pos < 0)
- pos += 256;
- }
- }
- //((P XOR((K + KC) XOR K)) + ((K + KC) XOR K))
- std::string encrypt(std::string plaintext, std::string password) {
- int passPos = 0;
- short asciiPosCipher;
- short passCounter = 1;
- short asciiPosPass;
- std::string cipher;
- for (unsigned int i = 0; i < plaintext.length(); i++) { //do for every character in string
- if (passPos >= password.length()) //after password ends start
- passPos = 0; //start from the beginning
- if (passCounter > 255)
- passCounter = 0;
- asciiPosPass = (password[passPos] + passCounter); //shift password char around passCounter
- CheckAsciiPos(asciiPosPass); //checks and corrects position pos in asciitable
- asciiPosPass ^= password[passPos]; //xor shifted password char with original password char
- asciiPosCipher = plaintext[i] ^ asciiPosPass; //xor this with plaintext char
- asciiPosCipher += asciiPosPass; //shift both to result
- CheckAsciiPos(asciiPosCipher);
- cipher += static_cast<char>(asciiPosCipher); //cast them to char an add to cipher-text
- passPos++; //next char in password
- passCounter++;
- }
- return cipher;
- }
- //((C - ((K + KC) XOR K)) XOR ((K + KC) XOR K))
- std::string decrypt(std::string cipher, std::string password) {
- int passPos = 0;
- short asciiPosResult;
- short passCounter = 1;
- short asciiPosPass;
- std::string result;
- for (unsigned int i = 0; i < cipher.length(); i++) {
- if (passPos >= password.length())
- passPos = 0;
- if (passCounter > 255)
- passCounter = 0;
- asciiPosPass = (password[passPos] + passCounter);
- CheckAsciiPos(asciiPosPass);
- asciiPosPass ^= password[passPos];
- asciiPosResult = cipher[i] - asciiPosPass;
- asciiPosResult ^= asciiPosPass;
- CheckAsciiPos(asciiPosResult);
- result += static_cast<char>(asciiPosResult);
- passPos++;
- passCounter++;
- }
- return result;
- }
- int main() {
- std::string fileName = "test.exe";
- std::ifstream input(fileName, std::ios::binary);
- std::string plaintext;
- char byte;
- while (input.get(byte)) {
- plaintext += byte;
- }
- std::string password = "testpass";
- std::string cipher;
- std::string result;
- cipher = encrypt(plaintext, password);
- std::ofstream enc("test_enc.exe", std::ios::app | std::ios::binary);
- enc << cipher;
- enc.close();
- result = decrypt(cipher, password);
- std::ofstream dec("test_dec.exe", std::ios::app | std::ios::binary);
- dec << result;
- dec.close();
- std::cin.get();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement