Problem 59 : XOR decryption
Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.
A modern encryption method is to take a text file, convert the bytes to ASCII, then XOR each byte with a given value, taken from a secret key. The advantage with the XOR function is that using the same encryption key on the cipher text, restores the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65.
For unbreakable encryption, the key is the same length as the plain text message, and the key is made up of random bytes. The user would keep the encrypted message and the encryption key in different locations, and without both “halves”, it is impossible to decrypt the message.
Unfortunately, this method is impractical for most users, so the modified method is to use a password as a key. If the password is shorter than the message, which is likely, the key is repeated cyclically throughout the message. The balance for this method is using a sufficiently long password key for security, but short enough to be memorable.
Your task has been made easy, as the encryption key consists of three lower case characters. Using cipher.txt (right click and ‘Save Link/Target As…’), a file containing the encrypted ASCII codes, and the knowledge that the plain text must contain common English words, decrypt the message and find the sum of the ASCII values in the original text.
C++ 11 代码
#include <iostream>
#include <fstream>
#include <sstream>
#include <string> // stoi()
#include <vector>
#include <array>
#include <cassert> // assert()
using namespace std;
typedef unsigned char u8;
class PE0059
{
private:
static const int max_size = 2000;
array<u8, max_size> m_encryptedMsg_chars = { 0 };
int m_encryptedMsg_chars_size;
u8 encryptOrDecryptChar(u8 char_ASCII_value, u8 encryption_key);
void readCipherFile();
public:
PE0059() { readCipherFile(); };
void findSumOfASCIIvaluesInOriginalText();
};
//#define UNIT_TEST
void PE0059::readCipherFile()
{
ifstream ifp("p059_cipher.txt");
string raw_data, digits_str;
ifp >> raw_data;
stringstream ss(raw_data);
m_encryptedMsg_chars_size = 0;
while (getline(ss, digits_str, ','))
{
m_encryptedMsg_chars[m_encryptedMsg_chars_size++] = stoi(digits_str);
}
ifp.close();
}
u8 PE0059::encryptOrDecryptChar(u8 char_ASCII_value, u8 encryption_key_value)
{
u8 result = char_ASCII_value ^ encryption_key_value;
return result;
}
void PE0059::findSumOfASCIIvaluesInOriginalText()
{
assert(107 == encryptOrDecryptChar((u8)'A', 42));
assert(65 == encryptOrDecryptChar(107, 42));
vector<string> key_vec;
string key(3, '0');
// the encryption key consists of three lower case characters
for (u8 c1 = 'a'; c1 <= 'z'; c1++)
{
for (u8 c2 = 'a'; c2 <= 'z'; c2++)
{
for (u8 c3 = 'a'; c3 <= 'z'; c3++)
{
key[0] = (char)c1;
key[1] = (char)c2;
key[2] = (char)c3;
key_vec.push_back(key);
}
}
}
int sumOfASCIIvalues;
int numOfReadableChars;
u8 decrypted_c_value;
char *originalMsg = new char[m_encryptedMsg_chars_size + 1];
for (auto &key : key_vec)
{
numOfReadableChars = 0;
sumOfASCIIvalues = 0;
for (int i = 0; i < m_encryptedMsg_chars_size; i++)
{
decrypted_c_value = encryptOrDecryptChar(m_encryptedMsg_chars[i],
(u8)key[i % 3]);
originalMsg[i] = (char)decrypted_c_value;
sumOfASCIIvalues += decrypted_c_value;
// check each character and find common used characters
if ((decrypted_c_value >= (u8)'a' && decrypted_c_value <= (u8)'z') ||
(decrypted_c_value >= (u8)'A' && decrypted_c_value <= (u8)'Z') ||
(decrypted_c_value >= (u8)'0' && decrypted_c_value <= (u8)'9') ||
decrypted_c_value == (u8)'.' || decrypted_c_value == (u8)'\'' ||
decrypted_c_value == (u8)',' || decrypted_c_value == (u8)';' ||
decrypted_c_value == (u8)'(' || decrypted_c_value == (u8)')' ||
decrypted_c_value == (u8)' ' || decrypted_c_value == (u8)'!')
{
numOfReadableChars++;
}
else
{
break;
}
}
if (numOfReadableChars == m_encryptedMsg_chars_size)
{
cout << "The sum of the ASCII values in the original text is ";
cout << sumOfASCIIvalues << endl;
#ifdef UNIT_TEST
originalMsg[m_encryptedMsg_chars_size] = 0;
cout << "decryptedMsg (key = " << key << "): " << originalMsg<<endl;
#endif
break;
}
}
delete[] originalMsg;
}
int main()
{
PE0059 pe0059;
pe0059.findSumOfASCIIvaluesInOriginalText();
return 0;
}
Python
import itertools
def readCipherTextFromFile():
encryptedMsg_char_list = []
for line in open('p059_cipher.txt'):
line = line.rstrip().split(',')
encryptedMsg_char_list += [int(ch) for ch in line]
return encryptedMsg_char_list
def encryptOrDecryptChar(char_ASCII_value, encryption_key_value):
return char_ASCII_value ^ encryption_key_value
def findSumOfASCIIvaluesInOriginalText(encryptedMsg_char_list):
originalMsg_char_list = ['\0'] * (1+len(encryptedMsg_char_list))
# the encryption key consists of three lower case characters
key_set = range(ord('a'), ord('z')+1)
key_length = 3
for key in itertools.product(key_set, repeat=key_length):
numOfReadableChars, sumOfASCIIvalues = 0, 0
originalMsg_char_list = []
for i, char_value in enumerate(encryptedMsg_char_list, 0):
decrypted_c = encryptOrDecryptChar(char_value, key[i % 3])
sumOfASCIIvalues += decrypted_c
originalMsg_char_list += [ decrypted_c ]
if decrypted_c >= ord('a') and decrypted_c <= ord('z') or \
decrypted_c >= ord('A') and decrypted_c <= ord('Z') or \
decrypted_c >= ord('0') and decrypted_c <= ord('9') or \
decrypted_c == ord('.') or decrypted_c == ord('\'') or \
decrypted_c == ord(',') or decrypted_c == ord(';') or \
decrypted_c == ord('(') or decrypted_c == ord(')') or \
decrypted_c == ord(' ') or decrypted_c == ord('!'):
numOfReadableChars += 1
else:
break
if numOfReadableChars == len(encryptedMsg_char_list):
print("The sum of the ASCII values in the original text is ",end='')
print(sumOfASCIIvalues,".")
#originalMsg = ''.join(map(chr, originalMsg_char_list))
#keyStr = ''.join(map(chr, key))
#print("decryptedMsg (key = %3s):" %keyStr, originalMsg)
break
def main():
assert 107 == encryptOrDecryptChar(ord('A'), 42)
assert 65 == encryptOrDecryptChar(107, 42)
encryptedMsg_char_list = readCipherTextFromFile()
findSumOfASCIIvaluesInOriginalText(encryptedMsg_char_list)
if __name__ == '__main__':
main()