Search code examples
c++encryptionxorbeep

PC makes beeps when XOR encrypting a string and saving it in a text file


I use XOR to encrypt the options I write to a text file, and decrypt them when I read them in.

Below is the code for encrypting the options and writing them to the file:

Settings settings;
const char key = 'x';

std::stringstream ss;
std::string original = "";
std::string encrypted = "";
std::ofstream file("./data/options.txt");

if (file.good()) {
  file.clear();

  // Build options string
  ss << "limitfps=" << (settings.getLimitFramerate() ? "1" : "0") << std::endl;
  ss << "fps=" << settings.getFramerateLimit();
  // etc...

  // Encrypt
  original = ss.str();
  for (std::size_t temp = 0; temp < original.size(); ++temp) {
    encrypted += original[temp] ^ (static_cast<int>(key) + temp) % 255;
  }

  // Print and write to file
  std::cout << "Saving encrypted data to file:\n" << encrypted << std::endl;
  file << encrypted;
  file.close();
}

Everything works but my PC makes 3 beeps for some reason. How do I make it not make the beeps?

And since it is in the code, another question: I don't need the file.close() at the end, right? I read that close() is automatically called when the end of the scope is reached?

Thanks


Solution

  • encrypted will contain non-printable characters, so when you print them to the console, you'll get some garbage sent to the console.

    Some of that garbage is apparently the ASCII code 0x07/^G/BEL, which causes the console to beep.

    To fix the problem either don't print encrypted, or print it in such a way that non-printable characters get filtered out or formatted as hexadecimal or something.