File: encoding.rst

package info (click to toggle)
python-nacl 1.5.0-7
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 14,776 kB
  • sloc: ansic: 45,889; python: 7,249; sh: 6,752; asm: 2,974; makefile: 1,011; cs: 35; xml: 30; pascal: 11
file content (57 lines) | stat: -rw-r--r-- 1,256 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
Encoders
========

.. currentmodule:: nacl.encoding

PyNaCl supports a simple method of encoding and decoding messages in different
formats. Encoders are simple classes with staticmethods that encode/decode and
are typically passed as a keyword argument `encoder` to various methods.

For example you can generate a signing key and encode it in hex with:

.. code-block:: python

    hex_key = nacl.signing.SigningKey.generate().encode(encoder=nacl.encoding.HexEncoder)

Then you can later decode it from hex:

.. code-block:: python

    signing_key = nacl.signing.SigningKey(hex_key, encoder=nacl.encoding.HexEncoder)


Built in Encoders
-----------------

.. class:: RawEncoder

.. class:: HexEncoder

.. class:: Base16Encoder

.. class:: Base32Encoder

.. class:: Base64Encoder

.. class:: URLSafeBase64Encoder


Defining your own Encoder
-------------------------

Defining your own encoder is easy. Each encoder is simply a class with 2 static
methods. For example here is the hex encoder:

.. code-block:: python

    import binascii

    class HexEncoder(object):

        @staticmethod
        def encode(data):
            return binascii.hexlify(data)

        @staticmethod
        def decode(data):
            return binascii.unhexlify(data)