Use 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]
The 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:
84, 101, 115, 116 |
This would map to the hexadecimal value:
0x54657374 |
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:
84×2563 + 101×2562 + 115×2561 + 116×2560 |
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.
PKCS #1 page: http://www.rsasecurity.com/rsalabs/pkcs/pkcs-1/