103 lines
2.8 KiB
C++
103 lines
2.8 KiB
C++
#include <iostream>
|
|
#include <cstring>
|
|
using namespace std;
|
|
|
|
string XOR(string data, string key) {
|
|
// Dividend is data
|
|
// Divisor is the primary key, i.e. the key
|
|
string result = "";
|
|
int dataLen = data.length();
|
|
int keyLen = key.length();
|
|
|
|
// Perform XOR operation
|
|
for (int i=0; i<keyLen; i++) {
|
|
if (i < dataLen) {
|
|
// Only perform XOR if within the length of data
|
|
if (data[i] == key[i]) {
|
|
result += '0';
|
|
}
|
|
else {
|
|
result += '1';
|
|
}
|
|
} else {
|
|
// If data length exceeded, append the key
|
|
result += key[i];
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
string encoder(string data, string key) {
|
|
int keyLen = key.length();
|
|
|
|
// Append n-1 zeroes to the data
|
|
string dataWithZeroes = data + string(keyLen-1, '0');
|
|
|
|
// Perform XOR operation with the key
|
|
string remainder = XOR(dataWithZeroes, key);
|
|
|
|
// Get the remainder (last n-1 bits)
|
|
string crc = remainder.substr(remainder.length() - (keyLen-1));
|
|
|
|
// Append the CRC to the original data
|
|
return data + crc;
|
|
}
|
|
|
|
string performDivision(string data, string key) {
|
|
int keyLen = key.length();
|
|
|
|
// Initialize with the data to be divided
|
|
string temp = data.substr(0, keyLen);
|
|
|
|
// Perform XOR operations on each segment
|
|
for (int i = keyLen; i < data.length(); i++) {
|
|
if (temp[0] == '1') { // Only perform XOR if the leading bit is 1
|
|
temp = XOR(temp, key);
|
|
}
|
|
temp = temp.substr(1) + data[i]; // Shift left and add the next bit
|
|
}
|
|
|
|
// Perform the final XOR operation
|
|
if (temp[0] == '1') {
|
|
temp = XOR(temp, key);
|
|
}
|
|
|
|
// Extract the remainder (last keyLen-1 bits)
|
|
return temp.substr(temp.length() - (keyLen - 1));
|
|
}
|
|
|
|
// Function to check the correctness of received data
|
|
bool checkData(string data, string key) {
|
|
string remainder = performDivision(data, key);
|
|
return (remainder.find('1') == string::npos); // No '1' means remainder is all zeros
|
|
}
|
|
|
|
int main() {
|
|
string data, key;
|
|
|
|
cout << endl << "Enter data:\t";
|
|
getline(cin, data);
|
|
cout << "Enter primary key:\t";
|
|
getline(cin, key);
|
|
|
|
cout<<endl<<"Original data:\t"<<data;
|
|
cout<<endl<<"Key:\t"<<key;
|
|
string messageToSend = encoder(data, key);
|
|
cout<<endl<<"----------------------------------------"<<endl;
|
|
cout<<"Message to be sent:\t"<<messageToSend;
|
|
cout<<endl<<"----------------------------------------"<<endl;
|
|
|
|
string receivedData;
|
|
cout<<endl<<"HINT: Received data should be the same as message to be sent.";
|
|
cout<<endl<<"Enter received data:\t";
|
|
getline(cin, receivedData);
|
|
|
|
if (receivedData == messageToSend) {
|
|
cout<<"The received data is correct."<<endl;
|
|
} else {
|
|
cout<<"The received data appears to be tampered."<<endl;
|
|
}
|
|
|
|
return 0;
|
|
}
|