<commit_before><commit_msg>add draft for nitrokey<commit_after>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
#  privacyIDEA
#  2016-04-30 <NAME>, <<EMAIL>>
#             initial writeup
#
#  (c) 2016 <NAME>, <EMAIL>
#
# This code is free software; you can redistribute it and/or
# modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
# License as published by the Free Software Foundation; either
# version 3 of the License, or any later version.
#
# This code is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU AFFERO GENERAL PUBLIC LICENSE for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

from ctypes import CDLL, RTLD_GLOBAL
from ctypes.util import find_library
import os
import binascii


class NitroKey(object):

    def __init__(self):
        libs = ["libusb-1.0.so", "linux-vdso.so.1", "libhidapi-libusb.so.0",
                "libstdc++.so.6", "libm.so.6", "libgcc_s.so.1",
                "libc.so.6", "librt.so.1", "libpthread.so.0", "libudev.so.1",
                "libcgmanager.so.0", "libnih.so.1",
                "libdbus-1.so.3"]
        for l in libs:
            CDLL(l, mode = RTLD_GLOBAL)
        lib = find_library("nitrokey")
        print("Using library %s" % lib)
        self.nitrokey = CDLL(lib, mode = RTLD_GLOBAL)

    def init_hotp(self, slot, password, slotname, otp_key=None):
        """
        Initilize the given slot with an HOTP key.

        If otp_key is not specified, then a random key is generated and
        returned.

        :param slot: The slot number, 15-17
        :type slot: int
        :param password: The card password
        :type password: basestring
        :param slotname: The new name of the slot
        :type slotname: basestring
        :param otp_key: The OTP secret key
        :type slotname: A hexstring
        :return: the otp key
        """
        if not otp_key:
            otp_key = binascii.hexlify(os.urandom(20))
        self.nitrokey.initHotp(slot, password, otp_key, slotname)
        return otp_key


if __name__ == "__main__":
    Nk = NitroKey()
    otp_key = Nk.init_hotp(15, "12345678", "pi")
    print otp_key
{'fraction_non_alphanumeric': 0.10566356720202874, 'fraction_numerical': 0.019019442096365174, 'mean_word_length': 2.5755287009063443, 'pattern_counts': {'":': 1, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7221272', 'n_tokens_mistral': 809, 'n_tokens_neox': 765, 'n_words': 255}