Search code examples
pythonopenssltor

Generating private_key and hostname for Tor hidden service, in python


#!/usr/bin/env python
import OpenSSL.crypto as crypto
import sha
import base64

KEY_BIT_LENGTH = 1024
ONION_LENGTH = 16
keys = crypto.PKey()
keys.generate_key(crypto.TYPE_RSA, KEY_BIT_LENGTH)

privkey_as_bytes = crypto.dump_privatekey(crypto.FILETYPE_ASN1, keys)
privkey_hash = sha.sha(privkey_as_bytes).digest()
onion = base64.b32encode(privkey_hash)[:ONION_LENGTH].lower() + '.onion'

print onion
print
print crypto.dump_privatekey(crypto.FILETYPE_PEM, keys)

Am I doing something incorrect here? I think my error might be in the alphabet used for the base32 encoding step. Shallot uses "abcdefghijklmnopqrstuvwxyz234567", but I am totally unsure of what python uses, lol.


Solution

  • Your error was using the private key to calculate the hash, you should have used the public key.

    The output of crypto.dump_publickey(crypto.FILETYPE_ASN1, keys) is structured like:

        SEQUENCE (2 elem)
            SEQUENCE (2 elem)
                OBJECT IDENTIFIER 1.2.840.113549.1.1.1 rsaEncryption (PKCS #1)
                NULL
            BIT STRING (1 elem)
                SEQUENCE(2 elem)
                    INTEGER (1024 bit) 1669234523452435234253452...
                    INTEGER 65537
    

    but Tor only uses the last sequence, so you must slice from 22 bytes on:

    pub_key = crypto.dump_publickey(crypto.FILETYPE_ASN1, keys)[22:]
    key_hash = b32(hashlib.sha1(pub_key).digest()[:16])
    print(key_hash[:16].lower() + ".onion")