TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
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
36
namespace
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
}
55
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
75
void
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
95
int
main
() {
96
// Testing
97
test
();
98
return
0;
99
}
test
void test()
Definition
caesar_cipher.cpp:100
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
XOR
Functions for XOR cipher algorithm.
ciphers
Algorithms for encryption and decryption.
ciphers::XOR::decrypt
std::string decrypt(const std::string &text, const int &key)
Definition
xor_cipher.cpp:61
ciphers::XOR::encrypt
std::string encrypt(const std::string &text, const int &key)
Definition
xor_cipher.cpp:47
ciphers
xor_cipher.cpp
Generated by
1.18.0