fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. const std::string alphabet = "abcdefghijklmnopqrstuvwxyz0123456789 ";
  8.  
  9. std::size_t find_index(char c)
  10. {
  11. return std::distance(alphabet.begin(), std::find(alphabet.begin(), alphabet.end(), c));
  12. }
  13.  
  14. std::string encrypt(const std::string& s, const std::string& passphrase)
  15. {
  16. std::string res;
  17. for (std::size_t i = 0; i != s.size(); ++i) {
  18. auto new_index = (find_index(s[i]) + find_index(passphrase[i % passphrase.size()])) % alphabet.size();
  19.  
  20. res += alphabet[new_index];
  21. }
  22. return res;
  23. }
  24.  
  25. std::string decrypt(const std::string& s, const std::string& passphrase)
  26. {
  27. std::string res;
  28. for (std::size_t i = 0; i != s.size(); ++i) {
  29. auto new_index = (alphabet.size() + find_index(s[i]) - find_index(passphrase[i % passphrase.size()])) % alphabet.size();
  30.  
  31. res += alphabet[new_index];
  32. }
  33. return res;
  34. }
  35.  
  36. std::string create_passphrase(std::size_t n)
  37. {
  38. std::string res;
  39. for (std::size_t i = 0; i != n; ++i) {
  40. res += alphabet[rand() % alphabet.size()];
  41. }
  42. return res;
  43. }
  44.  
  45. int main()
  46. {
  47. string abecedario = "abcdefghijklmnopqrstuvwxyz0123456789 "; //la cadena que almacena el abecedario predeterminado
  48. string mensaje; //la cadena que almacenara el mensaje
  49.  
  50. cout << "Ingrese el mensaje: " << endl;
  51. getline(cin, mensaje); //usamos el comando getline para ingresar el mensaje para tener el espacio tambien
  52.  
  53. srand(time(NULL));
  54.  
  55. const auto& passphrase = create_passphrase(mensaje.length());
  56. cout << "La clave es: " << endl << passphrase << endl;
  57.  
  58. string mensajeCifrado = encrypt(mensaje, passphrase);
  59.  
  60. cout << "El mensaje cifrado es: " << endl;
  61. cout << mensajeCifrado;
  62.  
  63. cout << endl << "Este es el mensaje: " << endl;
  64. cout << decrypt(mensajeCifrado, passphrase);
  65. }
Success #stdin #stdout 0s 4528KB
stdin
text to encode 42
stdout
Ingrese el mensaje: 
La clave es: 
d frhysj3o92nc5wa
El mensaje cifrado es: 
wd2 gg6i71afqg4p2
Este es el mensaje: 
text to encode 42