Package: cryptnoxpy
Cryptnox Python Communication LibraryWarning: This is a beta release of the software.
It is released for development purposes.
Use at your own risk.A Python3 library to use theCryptnox smartcard applet.
It provides high level functions to send instructions with the Cryptnox and to manage its lifecycle.
The core module isCryptnoxPywhich provides aConnectionclass to
establish a channel of communication that can be used to initialize a card instance through the
factory method.To buy NFC enabled cards that are supported by this library go to:https://www.cryptnox.com/LicenseThe library is available under dual licensing. You can use the library under the
conditions ofGNU LESSER GENERAL PUBLIC LICENSE 3.0+orcontact usto ask about commercial licensing.DocumentationAPI documentation can be found in HTML format in thedocs folderIt is generated using Sphynx from the code and can be generated in other formats too.Installation and requirementsRequires :Python 3.6-3.9PCSCd on LinuxUbuntu / Debiansudoapt-getinstallswigpython3-pippython3-setuptoolspcscdlibpcsclite-devpipinstall-UsetuptoolsFedora / CentOS / RHELyuminstallswigpython3-pippython3-setuptoolspcsc-lite-ccidpipinstall-UsetuptoolsOn some Linux, starts PCSCd service(sudo)systemctlstartpcscd(sudo)systemctlenablepcscdMac OSXbrewinstallswigInstallation of this libraryMake sure that you installed the required packages for your system.
See the “Requires” section above.Install with pip:pipinstallcryptnoxpyInstall from source:Download and run in its directory:pipinstall.or:pipinstallgit+ssh://git@github.com/Cryptnox-Software/cryptnoxpy.gitThis might requiresudoon some systems.Remove:pipuninstallcryptnoxpyInstallation issuesIf theLinux system doesn't have Python 3.6, 3.7, 3.8 nor 3.9, install
Python 3.7 with the following recipe (Debian like):sudoapt-getinstall-ymakebuild-essentiallibssl-devzlib1g-devswiglibpcsclite-devsudoapt-getinstall-ylibbz2-devlibreadline-devlibsqlite3-devwgetcurlllvmgitsudoapt-getinstall-ylibncurses5-devlibncursesw5-devxz-utilstk-devpcscdopenscwgethttps://www.python.org/ftp/python/3.7.8/Python-3.7.8.tgztarxfPython-3.7.8.tgzcdPython-3.7.8./configure--enable-optimizationsmake-j8build_allsudomake-j8altinstallsudopip3.7installgit+ssh://git@gitlab.com/cryptnox-phase2/cryptnoxpy.git# or (if issue about agent forwarding with sudo) :cd~gitclonegit@gitlab.com:cryptnox-phase2/cryptnoxpy.gitcdcryptnoxpysudopip3.7install.In case ofpyscard can't be installedautomatically with pip:Try to pip3 install with sudo or root:sudo pip install .If still a failure, install the following packages: Needed if pyscard can't be installed from package managersudo apt installpython3-devswiglibpcsclite-devthen retrysudo pip install ..If you usecontactless readerson Linux, the RFID modules need to be disabled :sudormmodpn533_usbsudormmodpn533sudorm-r/lib/modules/*/kernel/drivers/nfc/pn533Update issuesIn case you just want to update the package, with old pip version on some Linux, it is better to remove and reinstall the package:sudopipuninstallcryptnoxpysudopipinstall.Library useTo get the card a connection has to be established with the reader’s index. The connection can
then be passed to the factory that will initialize an object for the card in the reader from the
correct class for the card type and version.importcryptnoxpytry:connection=cryptnoxpy.Connection(0)exceptcryptnoxpy.ReaderException:print("Reader not found on index")else:try:card=cryptnoxpy.factory.get_card(connection)exceptcryptnoxpy.CryptnoxExceptionaserror:# There is an issue with loading the card# CryptnoxException is the base exception class for moduleprint(error)else:# Card is loaded and can be usedprint(f"Card serial number:{card.serial_number}")The factory will:connect to the cardselect the appletread the applet parametersselect class to handle the cardThe card contains basic information:card.serial_number : Integer : Card/applet instance Unique IDcard.applet_version : 3 integers list : Applet version (ex. 1.2.2)Remote connectionThe connection can also be initialized with a socket connection client in a list, and a True value for the ‘remote’ parameter.
This enables use with a remote client, communicating apdu commands over the socket connection.importcryptnoxpyimportsocketserver=socket.socket(socket.AF_INET,socket.SOCK_STREAM)server.bind((SERVER_IP,SERVER_PORT))server.listen()conn,addr=server.accept()try:connection=cryptnoxpy.Connection(0,False,[conn],True)exceptcryptnoxpy.ReaderException:print("Reader not found on index")else:try:card=cryptnoxpy.factory.get_card(connection)exceptcryptnoxpy.CryptnoxExceptionaserror:# There is an issue with loading the card# CryptnoxException is the base exception class for moduleprint(error)else:# Card is loaded and can be usedprint(f"Card serial number:{card.serial_number}")Initialization and pairingRight after the installation, the applet is not initialized, and the user needs
to send some parameters to use the card. The initialization can be executed once.
Any change of the base parameters requires a full applet reinstallation
(except PIN/PUK change).After the initialization, the card and the PC must share a common secret to be
used as authenticated secure channel. This secret is required any time further,
to communicate with the card (using a secure channel). The registration of this
common secret is done during the init phase.The init parameters required are :Name  (up to 20 chars string)Email (up to 60 chars string)PIN (9 digits string)PUK (15 digits string)optional : the first Paring Secret (32 bytes bytearray)pairing_key=card.init(name,email,pin,puk,pairing_secret)The returned data is the first PairingKey (32 bytes byte-array) and its index (0) :0x00 + ParingKeySlot0During the initialization phase, until the user public key for authentication
registration is allowed, the set_pairing_key command is also allowed.
Then set_pairing_key needs the applet to have the signature unlocked.After getting the pairing_key, the user needs to store it in a safe place.
In the case the client would communicate with several cards, the user needs to
associate the pairing_key with the instance serial number of the card, so that the user
client can keep track of multiple cards, and use the right one with the right
card. The pairing_key must be saved in a file to reconnect the next time to this
card. It should be saved with the serial number of card in order to associate this card with this
key.A common hardcoded PairingKey can be used.After this init phase, the secure channel must be used with all communications
with the card. A secure channel is an encrypted and 2-ways authenticated link
layer with the card using standards APDU messages. Many applet commands require
a secure channel.PINThe PIN chosen during the initialization needs to be provided after each card
reset, and a secure channel is opened.To test a PIN string, simply use:card.verify_pin(pin)Seed administrationThe applet manages a 256 bits master secret called the “seed”. This is the BIP32
Master Seed, and can be externally computed from a mnemonic to a binary seed
using BIP39. The key pairs used for ECDSA are then computationally derived from
this seed using BIP32 derivation scheme.Seed generationThe seed can be generated in the card using the random number generator in the
java chip system (AIS 20 class DRG.3). Doing this way, the seed secret never
escapes the card protection.The method to generate a new seed key is:card.generate_seed(pin)The card can also randomly generate BIP39 mnemonics words list. But in this
case, the query answer is only output and not used internally by the card.
It is administrator responsibility to get a mnemonic using the GENERATE MNEMONIC
command and then eventually compute the corresponding seed, which can be
uploaded in the card using RECOVER KEY command.
We don’t recommend doing so, this is very insecure, as the seed is exposed in
clear and full in the user’s system.RecoveryThe Cryptnox applet can load binary seed.The seed is loaded in the card using this method:card.load_seed(seed,pin)Seed is 32 bytes.Once this seed is loaded in the card using the load_seed method, this card now
behaves like were (or the one) it was backup. Be aware that key derivation
paths are not backup, and must be identical to retrieve the same key pairs.
See derivation and key system just below for more details.For more details about the recovery, see load_seed operation in the API documentation.Derivation and keys systemThe card applet is fully compliant withBIP32,
except the maximum depth of derivation from the master key is 8 levels.
It can be turned on for the card to return extended public keys for use in applications
requiring it.The card stores the present key pair (and its parent), used for signature.
This can be changed using the derive method, and also during a signature
command, giving a relative path (from the present key pair), or in an absolute path
(from the master key pair). See derive method in the API documentation.Any derivation aborts any opened signing sessions and resets the authentications
for signature. The generated key is used for all subsequent sign sessions.The ability to start derivation from the parent keys allows to more efficiently
switch between children of the same key. Note however that only the immediate
parent of the current key is cached so one cannot use this to go back in the
keys hierarchy.For ease of use, the user can derive from the root master node key pair
(absolute path) at each card startup, or even before each signature.
This takes a couple of seconds. So this is better to store intermediate public
keys hash and check the status to observe the current key pair in use.
This off-card complex key management is not needed if the signatures volume
is below one thousand per day.See derive and sign methods in the API documentation.EC SignatureThe derivation of the key pair node can be also possible using the signature
command (relative or absolute).The card applet can sign any 256 bits hash provided, using ECDSA with 256k1 EC
parameters. Most of the blockchain system used SHA2-256 to hash the message,
but this card applet is agnostic from this point, since the signature is performed on
a hash provided by the user. Note that this hash needs to be confirmed by the
users beforehand, when they provide their EC384 signature of this hash.The code to sign with the EC current key node is:signature=card.sign(data_hash,cryptnoxpy.Derivation.CURRENT_KEY)data_hash is a byte-array containing the EC hash to sign using ECDSA ecp256k1:The signature a byte array, encoded as an ASN1 DER sequence of two INTEGER values, r and s.See the sign method in the API documentation for more information.ChangelogAll notable changes to this project will be documented in this file.The format is based onKeep a Changelog,
and this project adheres toSemantic Versioning.Unreleased2.4.0- 2023-01-31ChangedRemote connection message format, not compatible with previous version2.3.0- 2022-11-28AddedAbility to write and read custom bytes from select command2.2.1- 2022-07-14FixedInstallation for Python 3.102.2.0- 2022-07-13AddedSupport for Python 3.10RemovedSupport for Python 3.6Fixedget_public_keyraises an unhandled exception when asking for current key with a derivation path2.1.1- 2022-06-13AddedAdd optional “hexed” parameter in get_public_key of cards2.1.0- 2022-06-01AddedAdd option for cards from remote connection2.0.3- 2022-03-14ChangedInstallation instructions added missing instructionsFixedgenerate_seedcommand allowed without previously verifying PIN code2.0.2- 2022-03-14Fixedunblock_pincommand shows “PIN code wasn’t authorized” when card is not locked2.0.1- 2022-01-03FixedPrinting debug data during requests call for certificates2.0.0- 2022-01-03AddedNew cad type, NFT, with limited functionality intended for keeping one NFTMethod for checking private key validityChangedUser data read and write property to listpyscard on windows fixed to version 2.0.1, in pipenv all OSes.1.1.6- 2021-11-03FixedDebug parameter not passed when creating card class1.1.5- 2021-10-29FixedGenuineness check made more resilient to exceptions1.1.4- 2021-10-21FixedOpening secure channel with G0 card throws exception1.1.3- 2021-10-20Fixedsign operation throws error if PIN code is not provided when user key is used for authentication.1.1.2- 2021-10-07FixedHandling of error response from the card for not authenticated1.1.1- 2021-10-06ChangedUser data size increased to 3600 bytesFixedSet PIN-less path didn’t convert input path to correct values for cardSetting PIN-less path and PIN authentication doesn’t set flags for indicationSign method doesn’t fill up given PIN code with 0s up to 9 characters1.1.0- 2021-09-24AddedOrigin property for indicating if the card is original or not or check can’t be done.ChangedPyScard updated to 2.0.2FixedWhen card is not initialized seed_source property throws exception. ReturnSeedSource.NO_SEEDinsteadWhen seed is generated in the card the flag for it stays the sameOperation unlock_pin doesn’t raise exception when card is not locked1.0.4- 2021-09-09ChangedImprovements in setup1.0.3- 2021-09-07ChangedDocumentation changed to rstVersion number stored in the module instead of getting it from pbrRemovedPBR dependencyFixedPyPI doesn’t install dependencies1.0.0- 2021-08-20AddedCard operationsPipfile and requirements for setting up environmentSetup file to install the library