Binary values of cryptographic keys

Viewed 66

I'm using Python 3.7 and the NaCl cryptography library. I'm trying to print the binary values of the public and private keys. So far I can only print the hex values with this code:

import nacl.utils
from nacl.public import PrivateKey, Box

skbob = PrivateKey.generate()
print( bytes(skbob).hex() )

Can someone tell me how to print the keys binary value?

1 Answers

So you can print the actual 1's and 0's of the secret key using this code:

import nacl.utils
from nacl.public import PrivateKey, Box

def access_bit(data, num):
    base = int(num // 8)
    shift = int(num % 8)
    return (data[base] & (1<<shift)) >> shift

skbob = PrivateKey.generate()

print( bytes(skbob).hex())

print([access_bit(bytes(skbob),i) for i in range(len(bytes(skbob))*8)])

You will see an output like this:

b32965d39933fc447a5c3bcdb00b73ef5de0b9cd88aba35a1743e38d88c8bec1
[1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1]

And as you will see, this is 256-bits of entropy, just as expected.

FWIW, I did the same when I was learning about cryptography, there is something really nice in seeing the raw data, and getting your hands dirty with the low level stuff.

Best, Woodstock

Related