Problems with C++ encryption

Asked

Viewed 102 times

2

I’m making an encryption program that works as follows: It will read a string and then add to each character a respective prime number. Example:

a(+2) b(+3) c(+5) d(+7) e(+11) = c e h k p

In this encryption, characters from the ASCII table from 33 to 125 will be allowed. And when any number passed 125 I’d come back from 33 and continue.

However, I do not know how to do it when it is a very large number, for example, if the character 'z' was at the position of number 150 in a string it would be added to 863, that is, 122 + 863. How can I make this sum stay within the limits of 33 and 125?

#include <iostream>
using std::cout;
using std::cin;
#include <stdio.h>
#include <string>
using std::string;
using std::getline;
#include<cstring>
using namespace std; 

int main ()
{
    string crpt_string;

    string std_string;

    int primos[150] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41...809, 
      811, 821, 823, 827, 829, 839, 853, 857, 859,
      863};


    cout << "Digte a string a ser criptografada: ";
    getline(cin, crpt_string);

    for ( int a = 0; a <= crpt_string.length(); a++)
    {
        std_string[a] = crpt_string[a] + primos[a];
    }

    printf(std_string.c_str());

    return 0;
} 

1 answer

2


I didn’t actually implement it, but I would use the operation % to limit entries by following these steps:

  • converts the character to int (or long, depending on the need) - this to get the code from it
  • subtract 33
  • sum the desired value (let’s call v)
  • do v = (v%92)+33 (92 is the number of valid values you consider, between 125 and 33)
  • takes the character whose code is v
  • Thank you very much friend, doing some tests here I think it worked. And in case how would it be to decrypt? Just do the reverse operation?

  • I can’t tell if the reverse would work - I believe so, but you have to test,,,

Browser other questions tagged

You are not signed in. Login or sign up in order to post.