How do I use Nettle from Python?

119 Views Asked by At

The package description shown in Synaptic Package Manager tells about nettle:

Nettle is a cryptographic library that is designed to fit easily in more or less any context: In crypto toolkits for object-oriented languages (C++, Python, Pike, ...), in applications like LSH or GNUPG, or even in kernel space.

but I was not able to find a Python wrapper for it on Internet. How do I control it from Python?

1

There are 1 best solutions below

2
On

Thanks to Vandan Revanur for the comment and the link to github python-nettle where you can download the .zip archive with the module.

The installation of the module can be done as described in README.md file and requires running of two python scripts. Below an excerpt from an IDLE session showing what the modules comes with:

Python 3.11.2 (main, Feb 11 2023, 10:33:12) [GCC 9.5.0] on linux
import nettle
dir(nettle)
['ASN1Error', 'BaseException', 'CBC', 'CCM', 'CTR', 'DataLenError', 'EAX', 'GCM', 'KeyLenError', 'LenMismatch', 'NotInitializedError', 'RSAError', 'RSAKeyPair', 'RSAPubKey', 'RandomError', 'Yarrow', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'aes128', 'aes192', 'aes256', 'arcfour', 'arctwo', 'autogen', 'base64', 'blowfish', 'camellia128', 'camellia192', 'camellia256', 'cast128', 'chacha', 'ciphers', 'des', 'des3', 'gosthash94', 'hashes', 'hmac_sha1', 'hmac_sha256', 'io', 'md2', 'md4', 'md5', 'poly1305_aes', 'pubkey', 're', 'ripemd160', 'salsa20', 'serpent', 'sha1', 'sha224', 'sha256', 'sha384', 'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512', 'sha512', 'sha512_224', 'sha512_256', 'twofish', 'umac128', 'umac32', 'umac64', 'umac96']
nettle.md2.__doc__
'MD2 is another hash function of Ronald Rivest’s, described in RFC 1319. It outputs message digests of 128 bits, or 16 octets.'
nettle.md5.__doc__
'MD5 is a message digest function constructed by Ronald Rivest, and described in RFC 1321. It outputs message digests of 128 bits, or 16 octets.'
nettle.blowfish.__doc__
'BLOWFISH is a block cipher designed by Bruce Schneier. It uses a block size of 64 bits (8 octets), and a variable key size, up to 448 bits. It has some weak keys. '
nettle.sha1.__doc__
'SHA1 is a hash function specified by NIST (The U.S. National Institute for Standards and Technology).'

It seems that there is no documentation coming with the module, but it is easy to find out how to work with it. Below an example of creating of MD5:

import nettle
ntte_md5obj = nettle.md5(b"some Text")  # expects a BYTE type object
ntte_md5obj.hexdigest() # gives '5B0989DEE5DA04D42D588B5B39578F35'
ntte_md5obj.digest_size # gives 16
ntte_md5obj.digest()    # gives b'[\t\x89\xde\xe5\xda\x04\xd4-X\x8b[9W\x8f5'

Update 2023-02-21: the nettle URL does in between list the available Python wrapper module.