-
-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathvigenere.h
More file actions
75 lines (62 loc) · 1.92 KB
/
vigenere.h
File metadata and controls
75 lines (62 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <stdio.h>
#include <string.h>
#include <string>
#include <iostream>
#include <stdio.h>
#include <ctype.h>
using namespace std;
std::string AVAILABLE_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
int index(char c) {
for(int ii = 0; ii < AVAILABLE_CHARS.size(); ii++) {
if(AVAILABLE_CHARS[ii] == c) {
// std::cout << ii << " " << c << std::endl;
return ii;
}
}
return -1;
}
std::string extend_key(std::string& msg, std::string& key) {
//generating new key
int msgLen = msg.size();
std::string newKey(msgLen, 'x');
int keyLen = key.size(), i, j;
for(i = 0, j = 0; i < msgLen; ++i, ++j){
if(j == keyLen)
j = 0;
newKey[i] = key[j];
}
newKey[i] = '\0';
return newKey;
}
std::string encrypt_vigenere(std::string& msg, std::string& key) {
int msgLen = msg.size(), keyLen = key.size(), i, j;
std::string encryptedMsg(msgLen, 'x');
// char newKey[msgLen], encryptedMsg[msgLen], decryptedMsg[msgLen];
std::string newKey = extend_key(msg, key);
//encryption
for(i = 0; i < msgLen; ++i) {
// std::cout << msg[i] << " " << isalnum(msg[i]) << std::endl;
if(isalnum(msg[i]) or msg[i] == ' ') {
encryptedMsg[i] = AVAILABLE_CHARS[((index(msg[i]) + index(newKey[i])) % AVAILABLE_CHARS.size())];
} else {
encryptedMsg[i] = msg[i];
}
}
encryptedMsg[i] = '\0';
return encryptedMsg;
}
std::string decrypt_vigenere(std::string& encryptedMsg, std::string& newKey) {
// decryption
int msgLen = encryptedMsg.size();
std::string decryptedMsg(msgLen, 'x');
int i;
for(i = 0; i < msgLen; ++i) {
if(isalnum(encryptedMsg[i]) or encryptedMsg[i] == ' ') {
decryptedMsg[i] = AVAILABLE_CHARS[(((index(encryptedMsg[i]) - index(newKey[i])) + AVAILABLE_CHARS.size()) % AVAILABLE_CHARS.size())];
} else {
decryptedMsg[i] = encryptedMsg[i];
}
}
decryptedMsg[i] = '\0';
return decryptedMsg;
}