[ Team LiB ] |
7.8 Converting Binary Strings to Integers for Use with RSA7.8.1 ProblemYou need to encode a string as a number for use with the RSA encryption algorithm. 7.8.2 SolutionUse the standard PKCS #1 method for converting a nonnegative integer to a string of a specified length. PKCS #1 is the RSA Security standard for encryption with the RSA encryption algorithm.[2]
7.8.3 DiscussionThe PKCS #1 method for representing binary strings as integers is simple. You simply treat the binary representation of the string directly as the binary representation of the number, where the string is considered a list of bytes from most significant to least significant (big-endian notation). For example, if you have the binary string "Test", you would have a number represented as a list of ASCII values. In decimal, these values are:
This would map to the hexadecimal value:
If you simply treat the hexadecimal value as a number, you'll get the integer representation. In base 10, the previous number would be 1415934836. If, for some reason, you need to calculate this value manually given the ASCII values of the integers, you would compute the following:
In the real world, your arbitrary-precision math library will probably have a way to turn binary strings into numbers that is compatible with the PKCS algorithm. For example, OpenSSL provides BN_bin2bn( ), which is discussed in Recipe 7.4. If you need to perform this conversion yourself, make sure that your numerical representation uses either an array of char values or an array of unsigned int values. If you use the former, you can use the binary string directly as a number. If you use the latter, you will have to byte-swap each word on a little-endian machine before treating the string as a number. On a big-endian machine, you need not perform any swap. 7.8.4 See Also |
[ Team LiB ] |