Exercise: Convert Data between Decimal, Base58, and Hex

Let's practice using the encoding methods we've just covered. In this exercise, we'll convert data including keys between binary, DER, hex, and base58.

Base58 and Hex

Let's convert some data! We'll start by using Python to play with base58. As this is a new data encoding method, created for Bitcoin, it's not standard and we'll need to import a library to work with it. import base58

Now we'll create a string to convert to base58.

mystring = b'hello world'

 

And do the conversion.

mybase58 = base58.b58encode(mystring)

 

And have a look at it.

print('Base58 String:')
print(mybase58)

 

Now let's try the reverse. Below is a base58 string. What does it say?

5QWTsqdM9CC9on

 

Use base58.b58decode() to find out!

Hex is a much more common format than base58. As such, there is a Python function for converting a number into hex format. Let's have a quick look at it.

mynumber = [an integer number]

 

myhexnumber = hex(mynumber)

 

print('Hex number:')
print(myhexnumber)

 

PEM and DER

Now let's play with Pem and DER encoding. First let's use OpenSSL (https://en.wikipedia.org/wiki/OpenSSL) on the command line to generate a key in PEM format.

$ openssl genrsa -out private.pem

 

And take a look at it.

$ cat private.pem

 

You can tell that it's in base64 due to the special characters not found in base58?

Now let's convert the file to the DER format.

$ openssl rsa -in private.pem -out privkey.der -outform der

 

And take a look at it now.

$ cat privkey.der

 

Is it a bunch of gibberish? That's because DER is a binary format and binary doesn't display very well on the command line. So let's try displaying the file in hex.

$ xxd -p privkey.der

 

Can you spot any of the DER tags we covered in section 5.2?


Source: Saylor Academy
Creative Commons License This work is licensed under a Creative Commons Attribution 4.0 License.

Last modified: Tuesday, October 5, 2021, 4:25 PM