DEV Community

codesharedot
codesharedot

Posted on

Generate digital identity with Python

You can generate a digital identity, as commonly seen in blockchain technology or ssh. This is for the Python language.

Like in blockchain technology, the "username" will be the public key. The code below generates a public and private key.

keys

Key generation

We'll import the module Crypto and use the RSA algorithm. (RSA is not recommended, but this is an example).

#!/usr/bin/python3
from os import chmod                                                            
from Crypto.PublicKey import RSA                                                

Then we use that algorithm to generate a public private key pair:

key = RSA.generate(2048)                                                        
pubkey = key.publickey()                                                        

Finally you can output them. In practice you never output your private key. When was the last time you output your passwords to the terminal?

print(key.exportKey('PEM'))                                                     
print(pubkey.exportKey('OpenSSH'))      

In key.exportKey('PEM'), the parameter is the output format. You can choose these formats:

  • 'DER' - binary encoding
  • 'PEM' - texture encoding
  • 'OpenSSH' - texture encoding according to OpenSSH spec.

Run the program, you now have a digital identity. You can share you public key with anyone.

Related links:

Top comments (0)