7.9. Converting Integers into Binary Strings for Use with RSA
Problem
You have a number as a result of an RSA operation that you’d like to turn into a binary string of a fixed length.
Solution
Use the inverse of the previous recipe, padding the start of the string with zero-bits, if necessary, to reach the desired output length. If the number is too big, return an error.
Discussion
In practice, you should be using a binary representation of very
large integers that stores a value as an array of values of type
unsigned int
or type char
. If
you’re using a little-endian machine and word-sized
storage, each word will need to be byte- swapped before the value can
be treated as a binary string.
Byte swapping can be done with the htonl(
)
macro,
which can be imported by including arpa/inet.h
on Unix or winsock.h on Windows.
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.