문제

I'm using the NTL library to implement ElGamal encryption/decryption algorithm. I've got it to the point that it's working but the algorithm wants the message to be converted to integers so it can be encrypted.
So if i input a number like 1234 everything works ok but how would i go to be able to convert a C++ string (std::string) to a ZZ number and then back from that ZZ number to a string?

LE:

ZZ it's a class that represent a large number.
Ex: 18287348238476283658234881728316274273671623781254124517353

So basically i'm looking to take "Hello World" for example and run it char by char and get the ascii code of the chars so i'll get a number: "72 101 108 108 111 32 87 111 114 108 100"
And then i need to convert this number back to string "Hello World"

Or maybe there's a better way.

도움이 되었습니까?

해결책

Here is an easy way to do it:

std::string str("1234567890");
NTL::ZZ number(NTL::INIT_VAL, str.c_str());

Now notice that:

std::cout << str << std::endl; // prints 1234567890
std::cout << number << std::endl; // prints 1234567890

다른 팁

Here is an answer from the NTL author's website:

In addition to the conversions listed, there is a generic conversion from a C-strings (i.e., const char *) to any type T, which is implemented using templates using the input operator >> for type T. So, for example, you can write

    ZZ x = conv<ZZ>("99999999999999999999999");

Source: http://www.shoup.net/ntl/doc/conversions.txt

I tried it, and it worked perfectly.

By far the easiest solution is to realize that you can convert chars to unsigned ints, and unsigned ints to ZZ numbers. Then treat the string as a base-256 number. For instance, "abc" would be 256*"ab" + "c", or 65536 * "a" + 256 * "b" + "c", or ((ZZ(unsigned('a')*256) + ZZ(unsigned('b'))*256) + ZZ(unsigned('c')),

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top