The Keybase API

Keybase Common Methods

keybase.discover(idtype, ids)[source]

Lookup Keybase accounts using other information like Twitter handles or Github user names. You can pass an iterable of IDs to lookup and you will get back a tuple of Keybase instances for every user found that matches the list. There maybe be more Keybase instances in the list than in the input array if partial matches occured.

>>> users = discover(TWITTER, ['ircri'])
>>> type(users[0])
<class 'keybase.keybase.Keybase'>
>>> users[0].username
u'irc'
>>> users[0].get_public_key().kid
u'0101f56ecf27564e5bec1c50250d09efe963cad3138d4dc7f4646c77f6008c1e23cf0a'

Valid types are:

TWITTER - match on twitter usernames GITHUB - match on github usernames HACKERNEWS - match on hackernews usernames WEB - match on a website domain name COINBASE - match on a coinbase domain KEYFINGERPRINT - match on a PGP key fingerprint

No matches to any of the provided IDs does not result in an error, but an empty tuple being returned:

>>> users = discover(TWITTER, ['jack'])
>>> len(users)
0

If you pass an unrecognized ID type it will raise a KeybaseInvalidIdTypeError:

>>> discover('invalidtype', ['ircri'])
Traceback (most recent call last):
...
KeybaseInvalidIdTypeError
keybase.gpg(binary=None)[source]

Returns the full path to the gpg instance on this machine. It prefers gpg2 but will search for gpg if it cannot find gpg2.

>>> len(gpg()) > 0
True
>>> len(gpg('gpg')) > 0
True

I implemented this because the gnupg.GPG class was having a hard time dealing with the fact that my Homebrew-installed GPG instance was a symlink in the /usr/local/bin directory instead of a real path to a real file.

If you want to use a binary with a specific name, supply the binary=bName option when you call gpg() and it will use your custom binary name instead.

On windows you shouldn’t need to supply an extension to the command like .exe or .cmd – it will figure it out for you.

Returns None if it cannot find a gpg2 or gpg instance in your PATH:

>>> gpg('notagpgbinary')

The Keybase Class – Accessing Public User Data

The Keybase class allows you to find users in the Keybase directory and access their stored public keys. Public keys let you encrypt messages and files for a user; only the person holding the private key from the pair can decrypt a file encrypted with the public key. Public keys also let you verify the signature on data; only the user with the private key can create a signature that can be validated with the specific public key.

class keybase.Keybase(username)[source]

A read-only view of a keybase.io user and their publically available keys. This class allows you to do interesting things with someone’s public key data like encrypt a message for them or verify that a message they signed to you was actually signed by them.

The public information is automatically retrieved when you build a new instance of the class.

>>> kbase = Keybase('irc')
>>> kbase.username
'irc'

If the user cannot be found a keybase.KeybaseUserNotFound exception is raised:

>>> kbase = Keybase('abcdefghijklmno123notauserhahaha')
Traceback (most recent call last):
...
KeybaseUserNotFound: User abcdefghijklmno123notauserhahaha not found

Note

It does not allow you to manipulate the key data in the keybase.io data store in any way.

encrypt(data, **kwargs)[source]

Equivalent to:

kbase = Keybase('irc')
pkey = kbase.get_public_key()
verified = pkey.encrypt(data, **kwargs)
assert verified

It’s a convenience method on the Keybase object to do data verification with the primary key.

For more information see keybase.KeybasePublicKey.encrypt.

get_public_key(keyname='primary')[source]

Returns a key named keyname as a keybase.KeybasePublicKey object if it exists in the current Keybase instance. Defaults to a key named primary if you opt not to supply a keyname when you call the method.

>>> kbase = Keybase('irc')
>>> primary_key = kbase.get_public_key()
>>> primary_key.kid
u'0101f56ecf27564e5bec1c50250d09efe963cad3138d4dc7f4646c77f6008c1e23cf0a'

Otherwise it returns None if a key by the name of keyname doesn’t exist for this user.

>>> kbase.get_public_key('thiskeydoesnotexist')
location

The geographical location of the person associated with this Keybase data.

>>> k = Keybase('irc')
>>> k.location
u'Bay Area, California'
name

The full name of the person associated with this Keybase data.

>>> k = Keybase('irc')
>>> k.name
u'Ian Chesal'
public_keys

A tuple of all the public keys available for this account. An empty tuple is returned if the instance isn’t bound to a user or the user has no keys.

>>> kbase = Keybase('irc')
>>> kbase.public_keys
(u'families', u'primary', u'sibkeys', u'subkeys')
username

The username of the person associated with this Keybase data.

>>> k = Keybase('irc')
>>> k.username
'irc'
verify(data, throw_error=False)[source]

Equivalent to:

kbase = Keybase('irc')
pkey = kbase.get_public_key()
verified = pkey.verify(some_message)
assert verified

It’s a convenience method on the Keybase object to do data verification with the primary key.

For more information see keybase.KeybasePublicKey.verify.

verify_file(fname, sigfname=None, throw_error=False)[source]

Equivalent to:

kbase = Keybase('irc')
pkey = kbase.get_public_key()
verified = pkey.verify_file(fname, signame)
assert verified

It’s a convenience method on the Keybase object to do data verification with the primary key.

For more information see keybase.KeybasePublicKey.verify_file.

The KeybasePublicKey Class – Public Key Records from the Keybase.io Data Store

class keybase.KeybasePublicKey(**kwargs)[source]

A class that represents the public key side of a public/private key pair.

It is tied very closely to the keybase.io data that’s stored for public keys in user profiles in the data store. As such, it’s meant to be initialized with a hash that contains the fields seen in a keybase.io public key record.

Under the hood it uses GnupGP’s gnupg.GPG class to do the heavy lifting. It creates a keystore that is unique to this instance of the class and loads the public key in to this keystore.

You won’t be able to decrypt with this class because it only contains a public key, not a private key. But you can encrypt and and sign:

>>> kbase = Keybase('irc')
>>> pkey = kbase.get_public_key()
>>> pkey.key_fingerprint
u'7cc0ce678c37fc27da3ce494f56b7a6f0a32a0b9'

If a valid GPG instance cannot be created when you initialize a KeybasePublicKey a KeybasePublicKeyError will be raised.

ascii

Synonym for bundle property.

bundle

The GPG key bundle. This is the ASCII representation of the public key data associated with the Keybase key.

cipher_algos

Returns a tuple of available cypher algorithms that you can use with this key to encrypt data. The available algorithms depend entirely on the GPG version installed on the machine though most, if not all GPG versions, support AES256.

>>> kbase = Keybase('irc')
>>> pkey = kbase.get_public_key()
>>> 'AES256' in pkey.cipher_algos
True
compress_algos

Returns a tuple of available compression algorithms that you can use with this key to compress encrypted data. The available algorithms depend entirely on the GPG version installed on the machine though most, if not all GPG versions, support ZIP.

>>> kbase = Keybase('irc')
>>> pkey = kbase.get_public_key()
>>> 'ZIP' in pkey.compress_algos
True
ctime

The datetime this key was created in the keybase database.

digest_algos

Returns a tuple of available digest algorithms that you can use with this key to hash data. The available algorithms depend entirely on the GPG version installed on the machine though most, if not all GPG versions, support SHA512.

>>> kbase = Keybase('irc')
>>> pkey = kbase.get_public_key()
>>> 'SHA512' in pkey.digest_algos
True
encrypt(data, armor=True, cipher_algo=None, digest_algo=None, compress_algo=None)[source]

Encrypt the message contained in the string data for the owner of this KeybasePublicKey instance.

If armor=True the output is ASCII armored; otherwise the output will be a gnupg._parsers.Crypt object.

If encryption fails a KeybasePublicKeyEncryptError is raised.

If it succeeds data object is returned. Assuming armor=True the returned data is just plain old ASCII text as a str().

Note

The remaining options are supplied for maximum flexibility with GPG but you can, for the most part, just ignore them and go with the defaults if you want the simpilest (but still secure) path to encrypting data with this API.

If cipher_algo is supplied it should be the name of a cipher algorithm to use. The default algorithm is AES256 and you can get a list of available algorithms from the keybase.KeybasePublicKey.crypto_algos() parameter.

If digest_algo is supplied it should be the name of a digest algorithm to use. The default is SHA512 and you can get a list of available algorithms from the keybase.KeybasePublicKey.digest_algos() parameter.

If compress_algo is supplied it should be the name of a compression algorithm to use. The default is ZIP and you can get a list of available algorithms from the keybase.KeybasePublicKey.compress_algos() parameter.

For more information on how encryption works please see the gnupg.encrypt manual page.

A simple example:

kbase = Keybase('irc')
pkey = kbase.get_public_key()
instring = 'Hello, world!'
encrypted = pkey.encrypt(instring)
assert encrypted
assert not encrypted.isspace()
assert encrypted != instring
key_fingerprint

The GPG fingerprint for the key.

key_type

The Keybase key type for this key (integer).

kid

The Keybase key ID for this key.

mtime

The datetime this key was last modified in the Keybase database.

ukbid

The UKB ID for the key.

verify(data, throw_error=False)[source]

Verify the signature on the contents of the string data. Returns True if the signature was verified with the key, False if it was not. If you supply throw_error=True to the call then it will throw a KeybasePublicKeyVerifyError on verification failure with a status message that tells you more about why verification failed.

Failure status messages are:

  • invalid gpg key
  • signature bad
  • signature error
  • decryption failed
  • no public key
  • key exp
  • key rev

For more information what these messages mean please see the gnupg._parsers.Verify manual page.

>>> message_good = """
... -----BEGIN PGP SIGNED MESSAGE-----
... Hash: SHA1
...
... Hello, world!
... -----BEGIN PGP SIGNATURE-----
... Version: GnuPG v1
...
... iQEcBAEBAgAGBQJTWHSVAAoJEO7zMmcMHMCAYpEH/j2hJApaHXSj0ddgbrmUdJ2z
... vZ5DFDR9syTPHrwtRJLPH7tgdiAtUpyXLozL321JIR7sExzONl7IKdpH1Qn0y1I/
... h6mV0Dm+AAJXWtbn08rDW2WWuW4+EBEy12Cfk2r1rF8KT+g3gcc2wLejSACkf7v+
... jKo5SnvIwIMze+Msqjcz/+hbKRdEEoD2zihe6ilMfbR1tCt8GALQVa8YEoHpgkcL
... MWbXSCgM7Q0gf00kHWa3A8rClW0dzW5kJG+InbymtenaDNwoNlFb6DHUdyF//REx
... YjJ6qHf7qFwtXPBiwrZf+VYt5OnjeWW6ybYasfrJiXi1qnd6IM40QCGlR0UXhII=
... =oUn0
... -----END PGP SIGNATURE-----
... """
>>> message_bad = """
... -----BEGIN PGP SIGNED MESSAGE-----
... Hash: SHA1
...
... Hello, another world!
... -----BEGIN PGP SIGNATURE-----
... Version: GnuPG v1
...
... iQEcBAEBAgAGBQJTWHSVAAoJEO7zMmcMHMCAYpEH/j2hJApaHXSj0ddgbrmUdJ2z
... vZ5DFDR9syTPHrwtRJLPH7tgdiAtUpyXLozL321JIR7sExzONl7IKdpH1Qn0y1I/
... h6mV0Dm+AAJXWtbn08rDW2WWuW4+EBEy12Cfk2r1rF8KT+g3gcc2wLejSACkf7v+
... jKo5SnvIwIMze+Msqjcz/+hbKRdEEoD2zihe6ilMfbR1tCt8GALQVa8YEoHpgkcL
... MWbXSCgM7Q0gf00kHWa3A8rClW0dzW5kJG+InbymtenaDNwoNlFb6DHUdyF//REx
... YjJ6qHf7qFwtXPBiwrZf+VYt5OnjeWW6ybYasfrJiXi1qnd6IM40QCGlR0UXhII=
... =oUn0
... -----END PGP SIGNATURE-----
... """
>>> kbase = Keybase('irc')
>>> pkey = kbase.get_public_key()
>>> verified = pkey.verify(message_good)
>>> assert verified
>>> verified = pkey.verify(message_bad)
>>> assert not verified
>>> pkey.verify(message_bad, throw_error=True)
Traceback (most recent call last):
...
KeybasePublicKeyVerifyError: signature bad

If you want to verify the signature on a file (either embedded or detached) please see keybase.KeybasePublicKey.verify_file() method.

verify_file(fname, sigfname=None, throw_error=False)[source]

Verify the signature on a file named fname. This is a string file name, not a file object. If only a fname is provided the method assumes the signature is embedded in the file itself. An embedded signature is usually produced like so:

gpg -u keybase.io/irc --sign helloworld.txt

If a sigfname argument is prodived it’s assumed to be a path to signature file for a detached signature. A detached signature is usually produced like so:

gpg -u keybase.io/irc --detach-sign helloworld.txt

Returns True if the signature is verifiable with the key, False if it is not verifiable.

If you supply the throw_error=True option to the call then it will throw a KeybasePublicKeyVerifyError on verification failure with a status message that tells you more about why the verification failed.

Failure status messages are:

  • invalid gpg key
  • signature bad
  • signature error
  • decryption failed
  • no public key
  • key exp
  • key rev

For more information what these messages mean please see the gnupg._parsers.Verify manual page.

An embedded signature example:

kbase = Keybase('irc')
pkey = kbase.get_public_key()
verified = pkey.verify_file('helloworld.txt.gpg')
assert verified

A detached signature example:

kbase = Keybase('irc')
pkey = kbase.get_public_key()
fname = 'helloworld.txt'
signame = 'helloworld.txt.sig'
verified = pkey.verify_file(fname, signame)
assert verified

The Keybase Error Classes

class keybase.KeybaseError[source]

General error class for Keybase errors.

class keybase.KeybaseUnboundInstanceError[source]

Thrown when calling a Keybase object method that requires the object be bound to a real user in the keybase store and the instance hasn’t had such a binding established yet.

class keybase.KeybaseUserNotFound[source]

Thrown when calling Keybase.lookup(username) and the username cannot be located in the keybase.io public key repository.

class keybase.KeybaseLookupInvalidError[source]

Thrown when calling Keybase.lookup(username) on an instance that has already been bound to a valid user via another lookup() call.

class keybase.KeybasePublicKeyError[source]

Thrown when a KeybasePublicKey cannot be created successfully.

class keybase.KeybasePublicKeyVerifyError[source]

Thrown when a KeybasePublicKey cannot verify the signature on a data object.

class keybase.KeybasePublicKeyEncryptError[source]

Thrown when a KeybasePublicKey cannot perform encryption on some data object.