Skip to content

Instantly share code, notes, and snippets.

@davehughes
Created October 28, 2016 23:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davehughes/81d7d741eeea8fc44f04dcf97b1fd257 to your computer and use it in GitHub Desktop.
Save davehughes/81d7d741eeea8fc44f04dcf97b1fd257 to your computer and use it in GitHub Desktop.
Simple example of generating private_key/hostname for tor hidden services.
'''
Based on https://gist.github.com/DonnchaC/d6428881f451097f329e, including
a very helpful comment attached to that gist.
'''
import base64
import hashlib
import os
from Crypto.PublicKey import RSA
def generate_tor_service_keys(directory='.', bytes=2048):
'''
Generate a private key and derived .onion address in the given
`directory` with names corresponding to the ones tor generates for hidden
services.
'''
key_output_path = os.path.join(directory, 'private_key')
hostname_output_path = os.path.join(directory, 'hostname')
key = RSA.generate(bytes)
with open(key_output_path, 'w') as f:
f.write(key.exportKey('PEM'))
onion_address = hashlib.sha1(key.publickey().exportKey('DER')[22:]).digest()[:10]
onion_address = base64.b32encode(onion_address).decode('utf-8').lower()
onion_address = '{}.onion'.format(onion_address)
with open(hostname_output_path, 'w') as f:
f.write(onion_address)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment