[openssl-users] conversion of RAND_bytes to rand in fips apporved way
Michael Wojcik
Michael.Wojcik at microfocus.com
Wed Jul 25 20:03:41 UTC 2018
> From: openssl-users [mailto:openssl-users-bounces at openssl.org] On Behalf
> Of William Roberts
> Sent: Wednesday, July 25, 2018 13:00
>
> > unsigned char bytes[2];
> > RAND_bytes(bytes, 2);
> > return (bytes[0] | (bytes[1] << 8)) & 0x7fff;
>
> You can ditch the shift logic. Offhand, i'm not sure what would
> happen on Big Endian machine, would it leave bit 15 high since it's in
> byte 0?
No. Bitwise operators in C work according to value, not representation, regardless of the byte order of multibyte integer types in that implementation.
> int openssl_rand(void) {
> uint16_t x;
> RAND_bytes((unsigned char *)&x, sizeof(x));
> return x & 0x7FFF;
> }
That's OK if you include stdint.h, because you don't care which of the two permissible representations uint15_t has (it has to be pure-binary with no trap representations) - IF your implementation has a 16-bit unsigned integer type. uint16_t won't be defined for an implementation that doesn't. Offhand I don't know of one that is CHAR_BIT 8, though.
Personally, I don't care for your version, because I don't like to see code manipulate the representation of an object without specific reason. My version follows the same pattern that correctly-written integer-marshaling code should use, for example; it has the same behavior regardless of implementation details (assuming, once again, that CHAR_BIT is 8).
By the way, sizeof is an operator. There's no need to parenthesize its operand, unless the operand is a type.
Of course, as Viktor pointed out, this all may be pointless anyway; it's not clear that the OP needs this functionality.
--
Michael Wojcik
Distinguished Engineer, Micro Focus
More information about the openssl-users
mailing list