TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
xor_cipher.cpp
Go to the documentation of this file.
1
29#include <iostream>
30#include <string>
31#include <cassert>
32
36namespace ciphers {
40 namespace XOR {
47 std::string encrypt (const std::string &text, const int &key) {
48 std::string encrypted_text = ""; // Empty string to store encrypted text
49 for (auto &c: text) { // Going through each character
50 char encrypted_char = char(c ^ key); // Applying encyption
51 encrypted_text += encrypted_char; // Appending encrypted character
52 }
53 return encrypted_text; // Returning encrypted text
54 }
61 std::string decrypt (const std::string &text, const int &key) {
62 std::string decrypted_text = ""; // Empty string to store decrypted text
63 for (auto &c : text) { // Going through each character
64 char decrypted_char = char(c ^ key); // Applying decryption
65 decrypted_text += decrypted_char; // Appending decrypted character
66 }
67 return decrypted_text; // Returning decrypted text
68 }
69 } // namespace XOR
70} // namespace ciphers
71
75void test() {
76 // Test 1
77 std::string text1 = "Whipalsh! : Do watch this movie...";
78 std::string encrypted1 = ciphers::XOR::encrypt(text1, 17);
79 std::string decrypted1 = ciphers::XOR::decrypt(encrypted1, 17);
80 assert(text1 == decrypted1);
81 std::cout << "Original text : " << text1;
82 std::cout << " , Encrypted text (with key = 17) : " << encrypted1;
83 std::cout << " , Decrypted text : "<< decrypted1 << std::endl;
84 // Test 2
85 std::string text2 = "->Valar M0rghulis<-";
86 std::string encrypted2 = ciphers::XOR::encrypt(text2, 29);
87 std::string decrypted2 = ciphers::XOR::decrypt(encrypted2, 29);
88 assert(text2 == decrypted2);
89 std::cout << "Original text : " << text2;
90 std::cout << " , Encrypted text (with key = 29) : " << encrypted2;
91 std::cout << " , Decrypted text : "<< decrypted2 << std::endl;
92}
93
95int main() {
96 // Testing
97 test();
98 return 0;
99}
Functions for XOR cipher algorithm.
Algorithms for encryption and decryption.
void test()
int main()