Skip to content

Python3 Client

typelogic edited this page Aug 12, 2020 · 12 revisions

ctypes

Python2 still works. However, python3 is used in this documentation.

A python ctypes mapping of the libidpasslite.so API can be crafted by examining the idpass.h header file. We also need to compile api.proto by:

pip3 uninstall protobuf python3-protobuf
pip3 install --upgrade protobuf

cd idpass_lite
export PATH=`pwd`/dependencies/build/desktop/bin:$PATH
mkdir myoutdir
protoc -I=lib/src/proto/ --python_out=myoutdir/ lib/src/proto/api.proto

A successful api.proto compilation should produce myoutdir/api_pb2.py. Give it a try first if api_pb2.py works by importing it:

cd myoutdir
python3
import api_pb2

If the api.proto compilation works, then below is an example python snippet that shows how to use ctypes to map and call the idpass_lite_init function in python. The ctypes find_library method relies on the LD_LIBRARY_PATH environment variable set by:

cd idpass_lite
./build.sh release

export LD_LIBRARY_PATH=`pwd`/build/release/lib/src

Python3 snippet:

import ctypes
import api_pb2
import pysodium

idpasslite = ctypes.util.find_library('idpasslite') or ctypes.util.find_library('libidpasslite')
lib = cypes.cdll.LoadLibrary(idpasslite)

lib.idpass_lite_init.argtypes = [
    ctypes.POINTER(ctypes.c_ubyte),
    ctypes.c_int,
    ctypes.POINTER(ctypes.c_ubyte),
    ctypes.c_int ]

lib.idpass_lite.restype = ctypes.c_void_p

def initialize_snippet():
    keyset = api_pb2.KeySet()

    # Taking shortcut by using pysodium library instead of
    # calling idpass_lite_generate_encryption_key() which does
    # the same thing under the hood
    pk, sk = pysodium.crypto_sign_keypair()
    keyset.encryptionKey = pysodium.randombytes(32)
    keyset.signatureKey = sk
    ks = bytearray(keyset.SerializeToString())

    # call the library's main initialization API
    context = lib.idpass_lite_init((ctypes.c_ubyte*len(ks))(*ks), len(ks), None, 0)

The above snippet took a shortcut by using pysodium to generate the encryption key and signature key instead of calling the library's API as was done in the C++ snippet.

Clone this wiki locally