7.8. Converting Binary Strings to Integers for Use with RSA

Problem

You need to encode a string as a number for use with the RSA encryption algorithm.

Solution

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]

Discussion

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 ...

Get Secure Programming Cookbook for C and C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.