././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1729078230.139738 pykcs11-1.5.17/0000755000076500000240000000000014703721726012702 5ustar00rousseaustaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1548190164.0 pykcs11-1.5.17/COPYING0000644000076500000240000004310313421700724013725 0ustar00rousseaustaff GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729077752.0 pykcs11-1.5.17/Changes.txt0000644000076500000240000002164414703720770015020 0ustar00rousseaustaffHistory ======= 1.5.17 - October 2024, Ludovic Rousseau - Add AES in counter mode support (CKM_AES_CTR) - Add simple derivation mechanisms support (CMK_CONCATENATE_*) - Fix reference counting in PyKCS11Lib.load() - remove python 2 support from ckbytelist - minor improvements 1.5.16 - May 2024, Ludovic Rousseau - add support of CKA_MODIFIABLE and CKA_DESTROYABLE attributes - minor improvements 1.5.15 - April 2024, Ludovic Rousseau - fix problems when PYKCS11LIB has incorrect values - fix a problem with swig and "pip install ..." - minor improvements 1.5.14 - February 2024, Ludovic Rousseau - fix build using swig 4.2.0 1.5.13 - January 2024, Ludovic Rousseau - fix issue between Python 3.12 garbage collector and C_Finalize() - Modernize use of setup.py - Check swig is installed - remove unused files - minor improvements 1.5.12 - April 2023, Ludovic Rousseau - add setAttributeValue() - minor improvements 1.5.11 - Septembre 2022, Ludovic Rousseau - add deriveKey() with CKM_ECDH1_DERIVE and CK_ECDH1_DERIVE_PARAMS - support pSourceData in OAEP params - remove use of (deprecated) distutils - samples: port to Python 3 - fix code coverage generation 1.5.10 - December 2020, Ludovic Rousseau - Add CKH_* constants - CKA_HW_FEATURE_TYPE attribute value is a number - Makefile: use python3 by default - minor improvements 1.5.9 - July 2020, Ludovic Rousseau - call C_GetSlotList() with a NULL parameter to correctly initialize some PKCS#11 lib conforming to PKCS#11 version 2.40. 1.5.8 - May 2020, Ludovic Rousseau - CKA_ALWAYS_AUTHENTICATE is boolean - CKM_VENDOR_DEFINED_... . Fix name: use CKM_ instead of CKR_ prefix . Use an explicit hex prefix: CKM_VENDOR_DEFINED_0x45 - Add missing CKM_*, CKA_*, CKF_*, CKD_*, CKK_*, CKN_*, CKO_*, CKR_* from PKCS#11 v3.0 - fix test_asymetric.py for RSA_PSS_Mechanism 1.5.7 - December 2019, Ludovic Rousseau - add missing files in the .tar.gz 1.5.6 - December 2019, Ludovic Rousseau - AppVeyor: . generate bdist_wheel . add Python 3.7 and 3.8 - Sample events.py: add a -f/--full argument - Add support of CKM_AES_GCM mechanism - CPKCS11Lib::Load(): return different error codes - minor improvements 1.5.5 - April 2019, Ludovic Rousseau - fix source package generation 1.5.4 - April 2019, Ludovic Rousseau - getTokenInfo: replace NUL char by ' ' in utcTime - dumpit: . print hardwareVersion and firmwareVersion . print slot flags . move to next slot if token not present - add support of CKA_WRAP_TEMPLATE/CKA_UNWRAP_TEMPLATE - add samples for ECC key generation and use - move from distutils to setuptools - upload of wheels to pypi on "make dist" 1.5.3 - October 2018, Ludovic Rousseau - Do not fail when converting a UTF-8 string - Documentation: convert from Epydoc to Sphinx - some minor improvements 1.5.2 - April 2018, Ludovic Rousseau - Fix initPin() - add tests for initPin(), setPin(), initToken() 1.5.1 - March 2018, Ludovic Rousseau - Fix "pip install" 1.5.0 - March 2018, Ludovic Rousseau - Python 3: use strings instead of binary buffers for CK_UTF8CHAR PKCS#11 types. The behavior is now the same as with Python 2 - allow non string PIN values (binary PIN) for login(), initToken(), initPin(), setPin() - fix support of RSA PKCS PSS mechanism The mechanism object now uses a parameter "mechanism" instead of hard coding the mechanism value to CKM_RSA_PKCS_PSS. - add support of Python 2.7 on Windows - add AppVeyor configuration (automatic Windows builds) - ckbytelist: remove possibility to give a initial size - samples/getinfo: do not list the mechanisms by default - samples/events: . do not list the mechanisms by default . add support of pinpad readers - some minor improvements 1.4.4 - October 2017, Ludovic Rousseau - getAttributeValue(): handle CKR_ARGUMENTS_BAD error - seedRandom: fix the seed convertion - Add vendor errors support to PyKCS11Error - samples/getinfo & dumpit: list only slots with a token present by default - run_test: add support of OpenSC PKCS#11 spy - ckbytelist: update __repr__() - include tests files in the archive - dumpit: display the error if getAttributeValue() fails - some minor improvements 1.4.3 - June 2017, Ludovic Rousseau - Add support of CKM_RSA_PKCS_PSS mechanism - fix CKM_AES_CBC issue with Python 3 - add Unitary Tests (make tests) - add tox support (automate and standardize testing in Python) - add coverage support (measuring code coverage of Python programs) - add Travis-CI configuration (automatic build and tests) - some minor improvements 1.4.2 - May 2017, Ludovic Rousseau - Moved the project from https://bitbucket.org/PyKCS11/pykcs11 to https://github.com/LudovicRousseau/PyKCS11 - Makefile: use a better default value for PREFIX - Fix PyKCS11.__del__(): test that every module is accessible - getSlotList(): add optional tokenPresent parameter By default the method returns all the slots (like before the change). - Always call C_Initialize() in ::Load() to work with some bogus PKCS#11 library (like libCryptoki2 from Safenet Luna SA HSM) - LowLevel samples: use PYKCS11LIB environment variable - some minor improvements 1.4.1 - February 2017, Ludovic Rousseau - fix compilation under Python 3 - add rsa encryption sample program 1.4.0 - February 2017, Ludovic Rousseau - fix closeAllSessions() and move it Session to PKCS11Lib - add RSAOAEPMechanism to support RSA Encryption - add DigestSession which enables multi-part digesting - add Elliptic curve keypair generating mechanism - fix bug in Templates using booleans CK_TRUE/CK_FALSE Templates are used by generateKey(), generateKeyPair(), findObjects() createObject(), unwrapKey() - fix dumpit.py sample for Python 3 1.3.3 - November 2016, Ludovic Rousseau - PKCS#11 definitions: sync with Cryptoki version 2.40 . add missing CKM_* and CKP_* defines - Add generateKey() with default mechanism CKM_AES_KEY_GEN - Make sure the PyKCS11Lib is referenced as long as Session object is live - Fix OverflowError on Windows - Attribute CKA_WRAP_WITH_TRUSTED is bool - samples - dumpit: ask to enter the PIN on the pinpad if needed - getinfo & dumpit: add --slot= parameter - some minor improvements 1.3.2 - January 2016, Ludovic Rousseau - Add wrappers for C_Verify, C_WrapKey, C_UnwrapKey - PKCS#11 definitions: sync with Cryptoki version 2.30 - Generate CKM[CKM_VENDOR_DEFINED+x] values on the fly - Fix use of a pinpad reader CKF_PROTECTED_AUTHENTICATION_PATH - dumpit.py: lots of small fixes - Setup call make to build pykcs11_wrap.cpp using SWIG - Fix build on Windows - Small bugs fixed 1.3.1 - October 2015, Ludovic Rousseau - PKCS#11 definitions: sync with Cryptoki version 2.30 - Add user type CK_CONTEXT_SPECIFIC - Fixes #9, incorrect assignment of pParameter for CK_MECHANISMs. - CKA_DERIVE is a CK_BBOOL and not byte array - Add digest() and encrypt method to Session class - Add samples: - key-pair generation - key-pair generation + certificate import - printing public key modulus - computing signature - small bugs fixed 1.3.0 - July 2014, Ludovic Rousseau - add Python3 support 1.2.4 - April 2012, Ludovic Rousseau - improve epydoc documentation - add pinpad support in C_Login() using pin=None - add pinpad support in samples getinfo.py and dumpit.py - add createObject() 1.2.3 - December 2010, Ludovic Rousseau - Add new classes CK_SLOT_INFO, CK_INFO, CK_SESSION_INFO, CK_MECHANISM_INFO and CK_TOKEN_INFO instead of the low level ones to have a __repr__() method. It is now possible to just print an object of these classes and have a human readable version. - Add a new class CK_OBJECT_HANDLE() to replace the low level one and have a __repr__() method for objects returned by findObjects() - Move initToken() from class Session to class PyKCS11Lib and add a slot parameter. - Add generateKeyPair and destoryObject support in high level interface 1.2.2 - June 2010, Ludovic Rousseau - Debug low level C_GenerateRandom - Add seedRandom() and generateRandom() in the high level API 1.2.1 - November 2008, Ludovic Rousseau - Use src/opensc/pkcs11.h instead of src/rsaref/* files since the files from RSA are not free enough (no right to distribute modified versions for example) - improve samples/getinfo.py script - bug fixes 1.2.0 - August 2008, Ludovic Rousseau - add getMechanismList() and getMechanismInfo() - add Session().getSessionInfo() - bug fixes 1.1.1 - December 2006, Giuseppe Amato (Midori) - bug fixes 1.1.0 - August 2006, Ludovic Rousseau - Introduce high level API 1.0.2 - July 2006, Ludovic Rousseau - port to Unix (tested on GNU/Linux only) - explicit call to SWIG to generate the wrapper 1.0.1 - 2004 Giuseppe Amato (Midori) - first version - Windows only ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1705848331.0 pykcs11-1.5.17/MANIFEST.in0000644000076500000240000000034214553227013014430 0ustar00rousseaustaffinclude src/* include src/opensc/* recursive-include samples *.py include Changes.txt include Makefile* include run_test.py include tox.ini include dev-requirements.txt include docs/* include COPYING include get_PYKCS11LIB.py ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1704624376.0 pykcs11-1.5.17/Makefile0000644000076500000240000000167014546500370014341 0ustar00rousseaustaff# give some default values ifeq (, $(PYTHON)) PYTHON=python3 endif COVERAGE ?= python3-coverage build: $(PYTHON) -m build install: $(PYTHON) -m pip install --editable . clean distclean: $(PYTHON) setup.py clean rm -f src/pykcs11_wrap.cpp rm -f src/LowLevel.py rm -rf build rm -f *.pyc PyKCS11/*.pyc rm -f PyKCS11/LowLevel.py rm -f PyKCS11/_LowLevel* rm -f build-stamp rm -f test/*.pyc src/pykcs11.i: src/opensc/pkcs11.h src/pkcs11lib.h src/pykcs11string.h src/ck_attribute_smart.h touch $@ pypi: clean rm -rf dist $(PYTHON) -m build $(PYTHON) -m twine upload dist/* test: $(PYTHON) run_test.py coverage: $(COVERAGE) erase $(COVERAGE) run run_test.py $(COVERAGE) report $(COVERAGE) html tox: ./get_PYKCS11LIB.py > tox.env tox doc: cd docs ; ./generate.sh doc-upload: doc rm -rf api mv docs/_build/html api scp -r api ludov@web.sourceforge.net:/home/project-web/pkcs11wrap/htdocs .PHONY: build install clean doc test ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1729078230.139344 pykcs11-1.5.17/PKG-INFO0000644000076500000240000000251114703721726013776 0ustar00rousseaustaffMetadata-Version: 2.1 Name: PyKCS11 Version: 1.5.17 Summary: A Full PKCS#11 wrapper for Python Home-page: https://github.com/LudovicRousseau/PyKCS11 Download-URL: http://sourceforge.net/projects/pkcs11wrap/files/pykcs11/ Author: Giuseppe Amato (Midori) Author-email: paipai@tiscali.it Maintainer: Ludovic Rousseau Maintainer-email: ludovic.rousseau@free.fr License: GPL Keywords: crypto,pki,pkcs11,c++ Platform: Win32 Unix Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License (GPL) Classifier: Natural Language :: English Classifier: Operating System :: Microsoft :: Windows Classifier: Operating System :: OS Independent Classifier: Operating System :: Unix Classifier: Programming Language :: C Classifier: Programming Language :: C++ Classifier: Programming Language :: Python Classifier: Topic :: Security :: Cryptography Classifier: Topic :: Software Development :: Libraries :: Python Modules License-File: COPYING A complete PKCS#11 wrapper for Python. You can use any PKCS#11 (aka CryptoKi) module such as the PSM which comes as part of mozilla or the various modules supplied by vendors of hardware crypto tokens, and almost all PKCS#11 functions and data types. The wrapper has been generated with the help of the SWIG compiler. ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1729078230.1052566 pykcs11-1.5.17/PyKCS11/0000755000076500000240000000000014703721726013775 5ustar00rousseaustaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1724417671.0 pykcs11-1.5.17/PyKCS11/__init__.py0000644000076500000240000016544214662103207016112 0ustar00rousseaustaff# Copyright (C) 2006-2015 Ludovic Rousseau (ludovic.rousseau@free.fr) # Copyright (C) 2010 Giuseppe Amato (additions to original interface) # # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import print_function import PyKCS11.LowLevel import os import sys # redefine PKCS#11 constants CK_TRUE = PyKCS11.LowLevel.CK_TRUE CK_FALSE = PyKCS11.LowLevel.CK_FALSE CK_UNAVAILABLE_INFORMATION = PyKCS11.LowLevel.CK_UNAVAILABLE_INFORMATION CK_EFFECTIVELY_INFINITE = PyKCS11.LowLevel.CK_EFFECTIVELY_INFINITE CK_INVALID_HANDLE = PyKCS11.LowLevel.CK_INVALID_HANDLE CKA = {} CKC = {} CKD = {} CKF = {} CKG = {} CKH = {} CKK = {} CKM = {} CKO = {} CKR = {} CKS = {} CKU = {} CKZ = {} # redefine PKCS#11 constants using well known prefixes for x in PyKCS11.LowLevel.__dict__.keys(): if x[:4] == 'CKA_' \ or x[:4] == 'CKC_' \ or x[:4] == 'CKD_' \ or x[:4] == 'CKF_' \ or x[:4] == 'CKG_' \ or x[:4] == 'CKH_' \ or x[:4] == 'CKK_' \ or x[:4] == 'CKM_' \ or x[:4] == 'CKO_' \ or x[:4] == 'CKR_' \ or x[:4] == 'CKS_' \ or x[:4] == 'CKU_' \ or x[:4] == 'CKZ_': a = "{}=PyKCS11.LowLevel.{}".format(x, x) exec(a) if x[3:] != "_VENDOR_DEFINED": eval(x[:3])[eval(x)] = x # => CKM[CKM_RSA_PKCS] = 'CKM_RSA_PKCS' eval(x[:3])[x] = eval(x) # => CKM['CKM_RSA_PKCS'] = CKM_RSA_PKCS # special CKR[] values CKR[-4] = "C_GetFunctionList() not found" CKR[-3] = "Unknown format" CKR[-2] = "Unkown PKCS#11 type" CKR[-1] = "Load" class ckbytelist(PyKCS11.LowLevel.ckbytelist): """ add a __repr__() method to the LowLevel equivalent """ def __init__(self, data=None): if data is None: data = 0 elif isinstance(data, str): data = data.encode("utf-8") elif isinstance(data, (bytes, list, ckbytelist)): data = bytes(data) else: raise PyKCS11.PyKCS11Error(-3, text=str(type(data))) super(ckbytelist, self).__init__(data) def __repr__(self): """ return the representation of a tuple the __str__ method will use it also """ rep = [int(elt) for elt in self] return repr(rep) class CK_OBJECT_HANDLE(PyKCS11.LowLevel.CK_OBJECT_HANDLE): """ add a __repr__() method to the LowLevel equivalent """ def __init__(self, session): PyKCS11.LowLevel.CK_OBJECT_HANDLE.__init__(self) self.session = session pass def to_dict(self): """ convert the fields of the object into a dictionnary """ # all the attibutes defined by PKCS#11 all_attributes = PyKCS11.CKA.keys() # only use the integer values and not the strings like 'CKM_RSA_PKCS' all_attributes = [attr for attr in all_attributes if isinstance(attr, int)] # all the attributes of the object attributes = self.session.getAttributeValue(self, all_attributes) dico = dict() for key, attr in zip(all_attributes, attributes): if attr is None: continue if key == CKA_CLASS: dico[PyKCS11.CKA[key]] = PyKCS11.CKO[attr] elif key == CKA_CERTIFICATE_TYPE: dico[PyKCS11.CKA[key]] = PyKCS11.CKC[attr] elif key == CKA_KEY_TYPE: dico[PyKCS11.CKA[key]] = PyKCS11.CKK[attr] else: dico[PyKCS11.CKA[key]] = attr return dico def __repr__(self): """ text representation of the object """ dico = self.to_dict() lines = list() for key in sorted(dico.keys()): lines.append("{}: {}".format(key, dico[key])) return "\n".join(lines) class CkClass(object): """ Base class for CK_* classes """ # dictionnary of integer_value: text_value for the flags bits flags_dict = dict() # dictionnary of fields names and types # type can be "pair", "flags" or "text" fields = dict() flags = 0 def flags2text(self): """ parse the `self.flags` field and create a list of `CKF_*` strings corresponding to bits set in flags :return: a list of strings :rtype: list """ r = [] for v in self.flags_dict.keys(): if self.flags & v: r.append(self.flags_dict[v]) return r def to_dict(self): """ convert the fields of the object into a dictionnary """ dico = dict() for field in self.fields.keys(): if field == "flags": dico[field] = self.flags2text() elif field == "state": dico[field] = self.state2text() else: dico[field] = eval("self." + field) return dico def __str__(self): """ text representation of the object """ dico = self.to_dict() lines = list() for key in sorted(dico.keys()): type = self.fields[key] if type == "flags": lines.append("{}: {}".format(key, ", ".join(dico[key]))) elif type == "pair": lines.append("%s: " % key + "%d.%d" % dico[key]) else: lines.append("{}: {}".format(key, dico[key])) return "\n".join(lines) class CK_SLOT_INFO(CkClass): """ matches the PKCS#11 CK_SLOT_INFO structure :ivar slotDescription: blank padded :type slotDescription: string :ivar manufacturerID: blank padded :type manufacturerID: string :ivar flags: See :func:`CkClass.flags2text` :type flags: integer :ivar hardwareVersion: 2 elements list :type hardwareVersion: list :ivar firmwareVersion: 2 elements list :type firmwareVersion: list """ flags_dict = { CKF_TOKEN_PRESENT: "CKF_TOKEN_PRESENT", CKF_REMOVABLE_DEVICE: "CKF_REMOVABLE_DEVICE", CKF_HW_SLOT: "CKF_HW_SLOT"} fields = {"slotDescription": "text", "manufacturerID": "text", "flags": "flags", "hardwareVersion": "text", "firmwareVersion": "text"} class CK_INFO(CkClass): """ matches the PKCS#11 CK_INFO structure :ivar cryptokiVersion: Cryptoki interface version :type cryptokiVersion: integer :ivar manufacturerID: blank padded :type manufacturerID: string :ivar flags: must be zero :type flags: integer :ivar libraryDescription: blank padded :type libraryDescription: string :var libraryVersion: 2 elements list :type libraryVersion: list """ fields = {"cryptokiVersion": "pair", "manufacturerID": "text", "flags": "flags", "libraryDescription": "text", "libraryVersion": "pair"} class CK_SESSION_INFO(CkClass): """ matches the PKCS#11 CK_SESSION_INFO structure :ivar slotID: ID of the slot that interfaces with the token :type slotID: integer :ivar state: state of the session :type state: integer :ivar flags: bit flags that define the type of session :type flags: integer :ivar ulDeviceError: an error code defined by the cryptographic token :type ulDeviceError: integer """ flags_dict = { CKF_RW_SESSION: "CKF_RW_SESSION", CKF_SERIAL_SESSION: "CKF_SERIAL_SESSION", } def state2text(self): """ parse the `self.state` field and return a `CKS_*` string corresponding to the state :return: a string :rtype: string """ return CKS[self.state] fields = {"slotID": "text", "state": "text", "flags": "flags", "ulDeviceError": "text"} class CK_TOKEN_INFO(CkClass): """ matches the PKCS#11 CK_TOKEN_INFO structure :ivar label: blank padded :type label: string :ivar manufacturerID: blank padded :type manufacturerID: string :ivar model: string blank padded :type model: string :ivar serialNumber: string blank padded :type serialNumber: string :ivar flags: :type flags: integer :ivar ulMaxSessionCount: :type ulMaxSessionCount: integer :ivar ulSessionCount: :type ulSessionCount: integer :ivar ulMaxRwSessionCount: :type ulMaxRwSessionCount: integer :ivar ulRwSessionCount: :type ulRwSessionCount: integer :ivar ulMaxPinLen: :type ulMaxPinLen: integer :ivar ulMinPinLen: :type ulMinPinLen: integer :ivar ulTotalPublicMemory: :type ulTotalPublicMemory: integer :ivar ulFreePublicMemory: :type ulFreePublicMemory: integer :ivar ulTotalPrivateMemory: :type ulTotalPrivateMemory: integer :ivar ulFreePrivateMemory: :type ulFreePrivateMemory: integer :ivar hardwareVersion: 2 elements list :type hardwareVersion: list :ivar firmwareVersion: 2 elements list :type firmwareVersion: list :ivar utcTime: string :type utcTime: string """ flags_dict = { CKF_RNG: "CKF_RNG", CKF_WRITE_PROTECTED: "CKF_WRITE_PROTECTED", CKF_LOGIN_REQUIRED: "CKF_LOGIN_REQUIRED", CKF_USER_PIN_INITIALIZED: "CKF_USER_PIN_INITIALIZED", CKF_RESTORE_KEY_NOT_NEEDED: "CKF_RESTORE_KEY_NOT_NEEDED", CKF_CLOCK_ON_TOKEN: "CKF_CLOCK_ON_TOKEN", CKF_PROTECTED_AUTHENTICATION_PATH: "CKF_PROTECTED_AUTHENTICATION_PATH", CKF_DUAL_CRYPTO_OPERATIONS: "CKF_DUAL_CRYPTO_OPERATIONS", CKF_TOKEN_INITIALIZED: "CKF_TOKEN_INITIALIZED", CKF_SECONDARY_AUTHENTICATION: "CKF_SECONDARY_AUTHENTICATION", CKF_USER_PIN_COUNT_LOW: "CKF_USER_PIN_COUNT_LOW", CKF_USER_PIN_FINAL_TRY: "CKF_USER_PIN_FINAL_TRY", CKF_USER_PIN_LOCKED: "CKF_USER_PIN_LOCKED", CKF_USER_PIN_TO_BE_CHANGED: "CKF_USER_PIN_TO_BE_CHANGED", CKF_SO_PIN_COUNT_LOW: "CKF_SO_PIN_COUNT_LOW", CKF_SO_PIN_FINAL_TRY: "CKF_SO_PIN_FINAL_TRY", CKF_SO_PIN_LOCKED: "CKF_SO_PIN_LOCKED", CKF_SO_PIN_TO_BE_CHANGED: "CKF_SO_PIN_TO_BE_CHANGED", } fields = {"label": "text", "manufacturerID": "text", "model": "text", "serialNumber": "text", "flags": "flags", "ulMaxSessionCount": "text", "ulSessionCount": "text", "ulMaxRwSessionCount": "text", "ulRwSessionCount": "text", "ulMaxPinLen": "text", "ulMinPinLen": "text", "ulTotalPublicMemory": "text", "ulFreePublicMemory": "text", "ulTotalPrivateMemory": "text", "ulFreePrivateMemory": "text", "hardwareVersion": "pair", "firmwareVersion": "pair", "utcTime": "text"} class CK_MECHANISM_INFO(CkClass): """ matches the PKCS#11 CK_MECHANISM_INFO structure :ivar ulMinKeySize: minimum size of the key :type ulMinKeySize: integer :ivar ulMaxKeySize: maximum size of the key :type ulMaxKeySize: integer :ivar flags: bit flags specifying mechanism capabilities :type flags: integer """ flags_dict = { CKF_HW: "CKF_HW", CKF_ENCRYPT: "CKF_ENCRYPT", CKF_DECRYPT: "CKF_DECRYPT", CKF_DIGEST: "CKF_DIGEST", CKF_SIGN: "CKF_SIGN", CKF_SIGN_RECOVER: "CKF_SIGN_RECOVER", CKF_VERIFY: "CKF_VERIFY", CKF_VERIFY_RECOVER: "CKF_VERIFY_RECOVER", CKF_GENERATE: "CKF_GENERATE", CKF_GENERATE_KEY_PAIR: "CKF_GENERATE_KEY_PAIR", CKF_WRAP: "CKF_WRAP", CKF_UNWRAP: "CKF_UNWRAP", CKF_DERIVE: "CKF_DERIVE", CKF_EXTENSION: "CKF_EXTENSION", } fields = {"ulMinKeySize": "text", "ulMaxKeySize": "text", "flags": "flags"} class PyKCS11Error(Exception): """ define the possible PyKCS11 exceptions """ def __init__(self, value, text=""): self.value = value self.text = text def __str__(self): """ The text representation of a PKCS#11 error is something like: "CKR_DEVICE_ERROR (0x00000030)" """ if self.value in CKR: if self.value < 0: return CKR[self.value] + " (%s)" % self.text else: return CKR[self.value] + " (0x%08X)" % self.value elif self.value & CKR_VENDOR_DEFINED: return "Vendor error (0x%08X)" % (self.value & 0xffffffff & ~CKR_VENDOR_DEFINED) else: return "Unknown error (0x%08X)" % self.value class PyKCS11Lib(object): """ high level PKCS#11 binding """ # shared by all instances _loaded_libs = dict() def __init__(self): self.lib = PyKCS11.LowLevel.CPKCS11Lib() def __del__(self): if PyKCS11 and PyKCS11.__name__ and \ PyKCS11.LowLevel and PyKCS11.LowLevel.__name__ and \ PyKCS11.LowLevel._LowLevel and \ PyKCS11.LowLevel._LowLevel.__name__: # unload the library self.unload() def load(self, pkcs11dll_filename=None, *init_string): """ load a PKCS#11 library :type pkcs11dll_filename: string :param pkcs11dll_filename: the library name. If this parameter is not set then the environment variable `PYKCS11LIB` is used instead :returns: a :class:`PyKCS11Lib` object :raises: :class:`PyKCS11Error` (-1): when the load fails """ if pkcs11dll_filename is None: pkcs11dll_filename = os.getenv("PYKCS11LIB") if pkcs11dll_filename is None: raise PyKCS11Error(-1, "No PKCS11 library specified (set PYKCS11LIB env variable)") if hasattr(self, "pkcs11dll_filename"): self.unload() # unload the previous library # if the instance was previously initialized, # create a new low level library object for it self.lib = PyKCS11.LowLevel.CPKCS11Lib() # if the lib is already in use: reuse it if pkcs11dll_filename in PyKCS11Lib._loaded_libs: self.lib.Duplicate(PyKCS11Lib._loaded_libs[pkcs11dll_filename]["ref"]) else: # else load it rv = self.lib.Load(pkcs11dll_filename) if rv != CKR_OK: raise PyKCS11Error(rv, pkcs11dll_filename) PyKCS11Lib._loaded_libs[pkcs11dll_filename] = { "ref": self.lib, "nb_users": 0 } # remember the lib file name self.pkcs11dll_filename = pkcs11dll_filename # increase user number PyKCS11Lib._loaded_libs[pkcs11dll_filename]["nb_users"] += 1 return self def unload(self): """ unload the current instance of a PKCS#11 library """ # in case NO library was found and used if not hasattr(self, "pkcs11dll_filename"): return if self.pkcs11dll_filename not in PyKCS11Lib._loaded_libs: raise PyKCS11Error(PyKCS11.LowLevel.CKR_GENERAL_ERROR, "invalid PyKCS11Lib state") # decrease user number PyKCS11Lib._loaded_libs[self.pkcs11dll_filename]["nb_users"] -= 1 if PyKCS11Lib._loaded_libs[self.pkcs11dll_filename]["nb_users"] == 0: # unload only if no more used self.lib.Unload() # remove unused entry # the case < 0 happens if lib loading failed if PyKCS11Lib._loaded_libs[self.pkcs11dll_filename]["nb_users"] <= 0: del PyKCS11Lib._loaded_libs[self.pkcs11dll_filename] delattr(self, "pkcs11dll_filename") def initToken(self, slot, pin, label): """ C_InitToken :param slot: slot number returned by :func:`getSlotList` :type slot: integer :param pin: Security Officer's initial PIN :param label: new label of the token """ pin1 = ckbytelist(pin) rv = self.lib.C_InitToken(slot, pin1, label) if rv != CKR_OK: raise PyKCS11Error(rv) def getInfo(self): """ C_GetInfo :return: a :class:`CK_INFO` object """ info = PyKCS11.LowLevel.CK_INFO() rv = self.lib.C_GetInfo(info) if rv != CKR_OK: raise PyKCS11Error(rv) i = CK_INFO() i.cryptokiVersion = (info.cryptokiVersion.major, info.cryptokiVersion.minor) i.manufacturerID = info.GetManufacturerID() i.flags = info.flags i.libraryDescription = info.GetLibraryDescription() i.libraryVersion = (info.libraryVersion.major, info.libraryVersion.minor) return i def getSlotList(self, tokenPresent=False): """ C_GetSlotList :param tokenPresent: `False` (default) to list all slots, `True` to list only slots with present tokens :type tokenPresent: bool :return: a list of available slots :rtype: list """ slotList = PyKCS11.LowLevel.ckintlist() rv = self.lib.C_GetSlotList(CK_TRUE if tokenPresent else CK_FALSE, slotList) if rv != CKR_OK: raise PyKCS11Error(rv) s = [] for x in range(len(slotList)): s.append(slotList[x]) return s def getSlotInfo(self, slot): """ C_GetSlotInfo :param slot: slot number returned by :func:`getSlotList` :type slot: integer :return: a :class:`CK_SLOT_INFO` object """ slotInfo = PyKCS11.LowLevel.CK_SLOT_INFO() rv = self.lib.C_GetSlotInfo(slot, slotInfo) if rv != CKR_OK: raise PyKCS11Error(rv) s = CK_SLOT_INFO() s.slotDescription = slotInfo.GetSlotDescription() s.manufacturerID = slotInfo.GetManufacturerID() s.flags = slotInfo.flags s.hardwareVersion = slotInfo.GetHardwareVersion() s.firmwareVersion = slotInfo.GetFirmwareVersion() return s def getTokenInfo(self, slot): """ C_GetTokenInfo :param slot: slot number returned by :func:`getSlotList` :type slot: integer :return: a :class:`CK_TOKEN_INFO` object """ tokeninfo = PyKCS11.LowLevel.CK_TOKEN_INFO() rv = self.lib.C_GetTokenInfo(slot, tokeninfo) if rv != CKR_OK: raise PyKCS11Error(rv) t = CK_TOKEN_INFO() t.label = tokeninfo.GetLabel() t.manufacturerID = tokeninfo.GetManufacturerID() t.model = tokeninfo.GetModel() t.serialNumber = tokeninfo.GetSerialNumber() t.flags = tokeninfo.flags t.ulMaxSessionCount = tokeninfo.ulMaxSessionCount if t.ulMaxSessionCount == CK_UNAVAILABLE_INFORMATION: t.ulMaxSessionCount = -1 t.ulSessionCount = tokeninfo.ulSessionCount if t.ulSessionCount == CK_UNAVAILABLE_INFORMATION: t.ulSessionCount = -1 t.ulMaxRwSessionCount = tokeninfo.ulMaxRwSessionCount if t.ulMaxRwSessionCount == CK_UNAVAILABLE_INFORMATION: t.ulMaxRwSessionCount = -1 t.ulRwSessionCount = tokeninfo.ulRwSessionCount if t.ulRwSessionCount == CK_UNAVAILABLE_INFORMATION: t.ulRwSessionCount = -1 t.ulMaxPinLen = tokeninfo.ulMaxPinLen t.ulMinPinLen = tokeninfo.ulMinPinLen t.ulTotalPublicMemory = tokeninfo.ulTotalPublicMemory if t.ulTotalPublicMemory == CK_UNAVAILABLE_INFORMATION: t.ulTotalPublicMemory = -1 t.ulFreePublicMemory = tokeninfo.ulFreePublicMemory if t.ulFreePublicMemory == CK_UNAVAILABLE_INFORMATION: t.ulFreePublicMemory = -1 t.ulTotalPrivateMemory = tokeninfo.ulTotalPrivateMemory if t.ulTotalPrivateMemory == CK_UNAVAILABLE_INFORMATION: t.ulTotalPrivateMemory = -1 t.ulFreePrivateMemory = tokeninfo.ulFreePrivateMemory if t.ulFreePrivateMemory == CK_UNAVAILABLE_INFORMATION: t.ulFreePrivateMemory = -1 t.hardwareVersion = (tokeninfo.hardwareVersion.major, tokeninfo.hardwareVersion.minor) t.firmwareVersion = (tokeninfo.firmwareVersion.major, tokeninfo.firmwareVersion.minor) t.utcTime = tokeninfo.GetUtcTime().replace('\000', ' ') return t def openSession(self, slot, flags=0): """ C_OpenSession :param slot: slot number returned by :func:`getSlotList` :type slot: integer :param flags: 0 (default), `CKF_RW_SESSION` for RW session :type flags: integer :return: a :class:`Session` object """ se = PyKCS11.LowLevel.CK_SESSION_HANDLE() flags |= CKF_SERIAL_SESSION rv = self.lib.C_OpenSession(slot, flags, se) if rv != CKR_OK: raise PyKCS11Error(rv) return Session(self, se) def closeAllSessions(self, slot): """ C_CloseAllSessions :param slot: slot number :type slot: integer """ rv = self.lib.C_CloseAllSessions(slot) if rv != CKR_OK: raise PyKCS11Error(rv) def getMechanismList(self, slot): """ C_GetMechanismList :param slot: slot number returned by :func:`getSlotList` :type slot: integer :return: the list of available mechanisms for a slot :rtype: list """ mechanismList = PyKCS11.LowLevel.ckintlist() rv = self.lib.C_GetMechanismList(slot, mechanismList) if rv != CKR_OK: raise PyKCS11Error(rv) m = [] for x in range(len(mechanismList)): mechanism = mechanismList[x] if mechanism >= CKM_VENDOR_DEFINED: k = 'CKM_VENDOR_DEFINED_0x%X' % (mechanism - CKM_VENDOR_DEFINED) CKM[k] = mechanism CKM[mechanism] = k m.append(CKM[mechanism]) return m def getMechanismInfo(self, slot, type): """ C_GetMechanismInfo :param slot: slot number returned by :func:`getSlotList` :type slot: integer :param type: a `CKM_*` type :type type: integer :return: information about a mechanism :rtype: a :class:`CK_MECHANISM_INFO` object """ info = PyKCS11.LowLevel.CK_MECHANISM_INFO() rv = self.lib.C_GetMechanismInfo(slot, CKM[type], info) if rv != CKR_OK: raise PyKCS11Error(rv) i = CK_MECHANISM_INFO() i.ulMinKeySize = info.ulMinKeySize i.ulMaxKeySize = info.ulMaxKeySize i.flags = info.flags return i def waitForSlotEvent(self, flags=0): """ C_WaitForSlotEvent :param flags: 0 (default) or `CKF_DONT_BLOCK` :type flags: integer :return: slot :rtype: integer """ tmp = 0 (rv, slot) = self.lib.C_WaitForSlotEvent(flags, tmp) if rv != CKR_OK: raise PyKCS11Error(rv) return slot class Mechanism(object): """Wraps CK_MECHANISM""" def __init__(self, mechanism, param=None): """ :param mechanism: the mechanism to be used :type mechanism: integer, any `CKM_*` value :param param: data to be used as crypto operation parameter (i.e. the IV for some algorithms) :type param: string or list/tuple of bytes :see: :func:`Session.decrypt`, :func:`Session.sign` """ self._mech = PyKCS11.LowLevel.CK_MECHANISM() self._mech.mechanism = mechanism self._param = None if param: self._param = ckbytelist(param) self._mech.pParameter = self._param self._mech.ulParameterLen = len(param) def to_native(self): return self._mech MechanismSHA1 = Mechanism(CKM_SHA_1, None) MechanismRSAPKCS1 = Mechanism(CKM_RSA_PKCS, None) MechanismRSAGENERATEKEYPAIR = Mechanism(CKM_RSA_PKCS_KEY_PAIR_GEN, None) MechanismECGENERATEKEYPAIR = Mechanism(CKM_EC_KEY_PAIR_GEN, None) MechanismAESGENERATEKEY = Mechanism(CKM_AES_KEY_GEN, None) class AES_GCM_Mechanism(object): """CKM_AES_GCM warpping mechanism""" def __init__(self, iv, aad, tagBits): """ :param iv: initialization vector :param aad: additional authentication data :param tagBits: length of authentication tag in bits """ self._param = PyKCS11.LowLevel.CK_GCM_PARAMS() self._source_iv = ckbytelist(iv) self._param.pIv = self._source_iv self._param.ulIvLen = len(self._source_iv) self._source_aad = ckbytelist(aad) self._param.pAAD = self._source_aad self._param.ulAADLen = len(self._source_aad) self._param.ulTagBits = tagBits self._mech = PyKCS11.LowLevel.CK_MECHANISM() self._mech.mechanism = CKM_AES_GCM self._mech.pParameter = self._param self._mech.ulParameterLen = PyKCS11.LowLevel.CK_GCM_PARAMS_LENGTH def to_native(self): return self._mech class AES_CTR_Mechanism(object): """CKM_AES_CTR encryption mechanism""" def __init__(self, counterBits, counterBlock): """ :param counterBits: the number of incremented bits in the counter block :param counterBlock: a 16-byte initial value of the counter block """ self._param = PyKCS11.LowLevel.CK_AES_CTR_PARAMS() self._source_cb = ckbytelist(counterBlock) self._param.ulCounterBits = counterBits self._param.cb = self._source_cb self._mech = PyKCS11.LowLevel.CK_MECHANISM() self._mech.mechanism = CKM_AES_CTR self._mech.pParameter = self._param self._mech.ulParameterLen = PyKCS11.LowLevel.CK_AES_CTR_PARAMS_LENGTH def to_native(self): return self._mech class RSAOAEPMechanism(object): """RSA OAEP Wrapping mechanism""" def __init__(self, hashAlg, mgf, label=None): """ :param hashAlg: the hash algorithm to use (like `CKM_SHA256`) :param mgf: the mask generation function to use (like `CKG_MGF1_SHA256`) :param label: the (optional) label to use """ self._param = PyKCS11.LowLevel.CK_RSA_PKCS_OAEP_PARAMS() self._param.hashAlg = hashAlg self._param.mgf = mgf self._source = None self._param.src = CKZ_DATA_SPECIFIED if label: self._source = ckbytelist(label) self._param.ulSourceDataLen = len(self._source) else: self._param.ulSourceDataLen = 0 self._param.pSourceData = self._source self._mech = PyKCS11.LowLevel.CK_MECHANISM() self._mech.mechanism = CKM_RSA_PKCS_OAEP self._mech.pParameter = self._param self._mech.ulParameterLen = PyKCS11.LowLevel.CK_RSA_PKCS_OAEP_PARAMS_LENGTH def to_native(self): return self._mech class RSA_PSS_Mechanism(object): """RSA PSS Wrapping mechanism""" def __init__(self, mecha, hashAlg, mgf, sLen): """ :param mecha: the mechanism to use (like `CKM_SHA384_RSA_PKCS_PSS`) :param hashAlg: the hash algorithm to use (like `CKM_SHA384`) :param mgf: the mask generation function to use (like `CKG_MGF1_SHA384`) :param sLen: length, in bytes, of the salt value used in the PSS encoding (like 0 or the message length) """ self._param = PyKCS11.LowLevel.CK_RSA_PKCS_PSS_PARAMS() self._param.hashAlg = hashAlg self._param.mgf = mgf self._param.sLen = sLen self._mech = PyKCS11.LowLevel.CK_MECHANISM() self._mech.mechanism = mecha self._mech.pParameter = self._param self._mech.ulParameterLen = PyKCS11.LowLevel.CK_RSA_PKCS_PSS_PARAMS_LENGTH def to_native(self): return self._mech class ECDH1_DERIVE_Mechanism(object): """CKM_ECDH1_DERIVE key derivation mechanism""" def __init__(self, publicData, kdf = CKD_NULL, sharedData = None): """ :param publicData: Other party public key which is EC Point [PC || coord-x || coord-y]. :param kdf: Key derivation function. OPTIONAL. Defaults to CKD_NULL :param sharedData: additional shared data. OPTIONAL """ self._param = PyKCS11.LowLevel.CK_ECDH1_DERIVE_PARAMS() self._param.kdf = kdf if sharedData: self._shared_data = ckbytelist(sharedData) self._param.pSharedData = self._shared_data self._param.ulSharedDataLen = len(self._shared_data) else: self._source_shared_data = None self._param.ulSharedDataLen = 0 self._public_data = ckbytelist(publicData) self._param.pPublicData = self._public_data self._param.ulPublicDataLen = len(self._public_data) self._mech = PyKCS11.LowLevel.CK_MECHANISM() self._mech.mechanism = CKM_ECDH1_DERIVE self._mech.pParameter = self._param self._mech.ulParameterLen = PyKCS11.LowLevel.CK_ECDH1_DERIVE_PARAMS_LENGTH def to_native(self): return self._mech class CONCATENATE_BASE_AND_KEY_Mechanism(object): """CKM_CONCATENATE_BASE_AND_KEY key derivation mechanism""" def __init__(self, encKey): """ :param encKey: a handle of encryption key """ self._mech = PyKCS11.LowLevel.CK_MECHANISM() self._mech.mechanism = CKM_CONCATENATE_BASE_AND_KEY self._mech.pParameter = encKey self._mech.ulParameterLen = PyKCS11.LowLevel.CK_OBJECT_HANDLE_LENGTH def to_native(self): return self._mech class KEY_DERIVATION_STRING_DATA_MechanismBase(object): """Base class for mechanisms using derivation string data""" def __init__(self, data, mechType): """ :param data: a byte array to concatenate the key with :param mechType: mechanism type """ self._param = PyKCS11.LowLevel.CK_KEY_DERIVATION_STRING_DATA() self._data = ckbytelist(data) self._param.pData = self._data self._param.ulLen = len(self._data) self._mech = PyKCS11.LowLevel.CK_MECHANISM() self._mech.mechanism = mechType self._mech.pParameter = self._param self._mech.ulParameterLen = PyKCS11.LowLevel.CK_KEY_DERIVATION_STRING_DATA_LENGTH def to_native(self): return self._mech class CONCATENATE_BASE_AND_DATA_Mechanism(KEY_DERIVATION_STRING_DATA_MechanismBase): """CKM_CONCATENATE_BASE_AND_DATA key derivation mechanism""" def __init__(self, data): """ :param data: a byte array to concatenate the key with """ super().__init__(data, CKM_CONCATENATE_BASE_AND_DATA) class CONCATENATE_DATA_AND_BASE_Mechanism(KEY_DERIVATION_STRING_DATA_MechanismBase): """CKM_CONCATENATE_DATA_AND_BASE key derivation mechanism""" def __init__(self, data): """ :param data: a byte array to concatenate the key with """ super().__init__(data, CKM_CONCATENATE_DATA_AND_BASE) class XOR_BASE_AND_DATA_Mechanism(KEY_DERIVATION_STRING_DATA_MechanismBase): """CKM_XOR_BASE_AND_DATA key derivation mechanism""" def __init__(self, data): """ :param data: a byte array to xor the key with """ super().__init__(data, CKM_XOR_BASE_AND_DATA) class DigestSession(object): def __init__(self, lib, session, mecha): self._lib = lib self._session = session self._mechanism = mecha.to_native() rv = self._lib.C_DigestInit(self._session, self._mechanism) if rv != CKR_OK: raise PyKCS11Error(rv) def update(self, data): """ C_DigestUpdate :param data: data to add to the digest :type data: bytes or string """ data1 = ckbytelist(data) rv = self._lib.C_DigestUpdate(self._session, data1) if rv != CKR_OK: raise PyKCS11Error(rv) return self def digestKey(self, handle): """ C_DigestKey :param handle: key handle :type handle: CK_OBJECT_HANDLE """ rv = self._lib.C_DigestKey(self._session, handle) if rv != CKR_OK: raise PyKCS11Error(rv) return self def final(self): """ C_DigestFinal :return: the digest :rtype: ckbytelist """ digest = ckbytelist() # Get the size of the digest rv = self._lib.C_DigestFinal(self._session, digest) if rv != CKR_OK: raise PyKCS11Error(rv) # Get the actual digest rv = self._lib.C_DigestFinal(self._session, digest) if rv != CKR_OK: raise PyKCS11Error(rv) return digest class Session(object): """ Manage :func:`PyKCS11Lib.openSession` objects """ def __init__(self, pykcs11, session): """ :param pykcs11: PyKCS11 library object :type pykcs11: PyKCS11Lib :param session: session handle :type session: instance of :class:`CK_SESSION_HANDLE` """ if not isinstance(pykcs11, PyKCS11Lib): raise TypeError("pykcs11 must be a PyKCS11Lib") if not isinstance(session, LowLevel.CK_SESSION_HANDLE): raise TypeError("session must be a CK_SESSION_HANDLE") # hold the PyKCS11Lib reference, so that it's not Garbage Collection'd self.pykcs11 = pykcs11 self.session = session @property def lib(self): """ Get the low level lib of the owning PyKCS11Lib """ return self.pykcs11.lib def closeSession(self): """ C_CloseSession """ rv = self.lib.C_CloseSession(self.session) if rv != CKR_OK: raise PyKCS11Error(rv) def getSessionInfo(self): """ C_GetSessionInfo :return: a :class:`CK_SESSION_INFO` object """ sessioninfo = PyKCS11.LowLevel.CK_SESSION_INFO() rv = self.lib.C_GetSessionInfo(self.session, sessioninfo) if rv != CKR_OK: raise PyKCS11Error(rv) s = CK_SESSION_INFO() s.slotID = sessioninfo.slotID s.state = sessioninfo.state s.flags = sessioninfo.flags s.ulDeviceError = sessioninfo.ulDeviceError return s def login(self, pin, user_type=CKU_USER): """ C_Login :param pin: the user's PIN or None for CKF_PROTECTED_AUTHENTICATION_PATH :type pin: string :param user_type: the user type. The default value is CKU_USER. You may also use CKU_SO :type user_type: integer """ pin1 = ckbytelist(pin) rv = self.lib.C_Login(self.session, user_type, pin1) if rv != CKR_OK: raise PyKCS11Error(rv) def logout(self): """ C_Logout """ rv = self.lib.C_Logout(self.session) if rv != CKR_OK: raise PyKCS11Error(rv) del self def initPin(self, pin): """ C_InitPIN :param pin: new PIN """ new_pin1 = ckbytelist(pin) rv = self.lib.C_InitPIN(self.session, new_pin1) if rv != CKR_OK: raise PyKCS11Error(rv) def setPin(self, old_pin, new_pin): """ C_SetPIN :param old_pin: old PIN :param new_pin: new PIN """ old_pin1 = ckbytelist(old_pin) new_pin1 = ckbytelist(new_pin) rv = self.lib.C_SetPIN(self.session, old_pin1, new_pin1) if rv != CKR_OK: raise PyKCS11Error(rv) def createObject(self, template): """ C_CreateObject :param template: object template """ attrs = self._template2ckattrlist(template) handle = PyKCS11.LowLevel.CK_OBJECT_HANDLE() rv = self.lib.C_CreateObject(self.session, attrs, handle) if rv != PyKCS11.CKR_OK: raise PyKCS11.PyKCS11Error(rv) return handle def destroyObject(self, obj): """ C_DestroyObject :param obj: object ID """ rv = self.lib.C_DestroyObject(self.session, obj) if rv != CKR_OK: raise PyKCS11Error(rv) def digestSession(self, mecha=MechanismSHA1): """ C_DigestInit/C_DigestUpdate/C_DigestKey/C_DigestFinal :param mecha: the digesting mechanism to be used (use `MechanismSHA1` for `CKM_SHA_1`) :type mecha: :class:`Mechanism` :return: A :class:`DigestSession` object :rtype: DigestSession """ return DigestSession(self.lib, self.session, mecha) def digest(self, data, mecha=MechanismSHA1): """ C_DigestInit/C_Digest :param data: the data to be digested :type data: (binary) sring or list/tuple of bytes :param mecha: the digesting mechanism to be used (use `MechanismSHA1` for `CKM_SHA_1`) :type mecha: :class:`Mechanism` :return: the computed digest :rtype: list of bytes :note: the returned value is an istance of :class:`ckbytelist`. You can easly convert it to a binary string with: ``bytes(ckbytelistDigest)`` or, for Python 2: ``''.join(chr(i) for i in ckbytelistDigest)`` """ digest = ckbytelist() m = mecha.to_native() data1 = ckbytelist(data) rv = self.lib.C_DigestInit(self.session, m) if rv != CKR_OK: raise PyKCS11Error(rv) # first call get digest size rv = self.lib.C_Digest(self.session, data1, digest) if rv != CKR_OK: raise PyKCS11Error(rv) # second call get actual digest data rv = self.lib.C_Digest(self.session, data1, digest) if rv != CKR_OK: raise PyKCS11Error(rv) return digest def sign(self, key, data, mecha=MechanismRSAPKCS1): """ C_SignInit/C_Sign :param key: a key handle, obtained calling :func:`findObjects`. :type key: integer :param data: the data to be signed :type data: (binary) string or list/tuple of bytes :param mecha: the signing mechanism to be used (use `MechanismRSAPKCS1` for `CKM_RSA_PKCS`) :type mecha: :class:`Mechanism` :return: the computed signature :rtype: list of bytes :note: the returned value is an instance of :class:`ckbytelist`. You can easly convert it to a binary string with: ``bytes(ckbytelistSignature)`` or, for Python 2: ``''.join(chr(i) for i in ckbytelistSignature)`` """ m = mecha.to_native() signature = ckbytelist() data1 = ckbytelist(data) rv = self.lib.C_SignInit(self.session, m, key) if rv != CKR_OK: raise PyKCS11Error(rv) # first call get signature size rv = self.lib.C_Sign(self.session, data1, signature) if rv != CKR_OK: raise PyKCS11Error(rv) # second call get actual signature data rv = self.lib.C_Sign(self.session, data1, signature) if rv != CKR_OK: raise PyKCS11Error(rv) return signature def verify(self, key, data, signature, mecha=MechanismRSAPKCS1): """ C_VerifyInit/C_Verify :param key: a key handle, obtained calling :func:`findObjects`. :type key: integer :param data: the data that was signed :type data: (binary) string or list/tuple of bytes :param signature: the signature to be verified :type signature: (binary) string or list/tuple of bytes :param mecha: the signing mechanism to be used (use `MechanismRSAPKCS1` for `CKM_RSA_PKCS`) :type mecha: :class:`Mechanism` :return: True if signature is valid, False otherwise :rtype: bool """ m = mecha.to_native() data1 = ckbytelist(data) rv = self.lib.C_VerifyInit(self.session, m, key) if rv != CKR_OK: raise PyKCS11Error(rv) rv = self.lib.C_Verify(self.session, data1, signature) if rv == CKR_OK: return True elif rv == CKR_SIGNATURE_INVALID: return False else: raise PyKCS11Error(rv) def encrypt(self, key, data, mecha=MechanismRSAPKCS1): """ C_EncryptInit/C_Encrypt :param key: a key handle, obtained calling :func:`findObjects`. :type key: integer :param data: the data to be encrypted :type data: (binary) string or list/tuple of bytes :param mecha: the encryption mechanism to be used (use `MechanismRSAPKCS1` for `CKM_RSA_PKCS`) :type mecha: :class:`Mechanism` :return: the encrypted data :rtype: list of bytes :note: the returned value is an instance of :class:`ckbytelist`. You can easly convert it to a binary string with: ``bytes(ckbytelistEncrypted)`` or, for Python 2: ``''.join(chr(i) for i in ckbytelistEncrypted)`` """ encrypted = ckbytelist() m = mecha.to_native() data1 = ckbytelist(data) rv = self.lib.C_EncryptInit(self.session, m, key) if rv != CKR_OK: raise PyKCS11Error(rv) # first call get encrypted size rv = self.lib.C_Encrypt(self.session, data1, encrypted) if rv != CKR_OK: raise PyKCS11Error(rv) # second call get actual encrypted data rv = self.lib.C_Encrypt(self.session, data1, encrypted) if rv != CKR_OK: raise PyKCS11Error(rv) return encrypted def decrypt(self, key, data, mecha=MechanismRSAPKCS1): """ C_DecryptInit/C_Decrypt :param key: a key handle, obtained calling :func:`findObjects`. :type key: integer :param data: the data to be decrypted :type data: (binary) string or list/tuple of bytes :param mecha: the decrypt mechanism to be used :type mecha: :class:`Mechanism` instance or :class:`MechanismRSAPKCS1` for CKM_RSA_PKCS :return: the decrypted data :rtype: list of bytes :note: the returned value is an instance of :class:`ckbytelist`. You can easly convert it to a binary string with: ``bytes(ckbytelistData)`` or, for Python 2: ``''.join(chr(i) for i in ckbytelistData)`` """ m = mecha.to_native() decrypted = ckbytelist() data1 = ckbytelist(data) rv = self.lib.C_DecryptInit(self.session, m, key) if rv != CKR_OK: raise PyKCS11Error(rv) # first call get decrypted size rv = self.lib.C_Decrypt(self.session, data1, decrypted) if rv != CKR_OK: raise PyKCS11Error(rv) # second call get actual decrypted data rv = self.lib.C_Decrypt(self.session, data1, decrypted) if rv != CKR_OK: raise PyKCS11Error(rv) return decrypted def wrapKey(self, wrappingKey, key, mecha=MechanismRSAPKCS1): """ C_WrapKey :param wrappingKey: a wrapping key handle :type wrappingKey: integer :param key: a handle of the key to be wrapped :type key: integer :param mecha: the encrypt mechanism to be used (use `MechanismRSAPKCS1` for `CKM_RSA_PKCS`) :type mecha: :class:`Mechanism` :return: the wrapped key bytes :rtype: list of bytes :note: the returned value is an instance of :class:`ckbytelist`. You can easily convert it to a binary string with: ``bytes(ckbytelistData)`` or, for Python 2: ``''.join(chr(i) for i in ckbytelistData)`` """ wrapped = ckbytelist() native = mecha.to_native() # first call get wrapped size rv = self.lib.C_WrapKey(self.session, native, wrappingKey, key, wrapped) if rv != CKR_OK: raise PyKCS11Error(rv) # second call get actual wrapped key data rv = self.lib.C_WrapKey(self.session, native, wrappingKey, key, wrapped) if rv != CKR_OK: raise PyKCS11Error(rv) return wrapped def unwrapKey(self, unwrappingKey, wrappedKey, template, mecha=MechanismRSAPKCS1): """ C_UnwrapKey :param unwrappingKey: the unwrapping key handle :type unwrappingKey: integer :param wrappedKey: the bytes of the wrapped key :type wrappedKey: (binary) string or list/tuple of bytes :param template: template for the unwrapped key :param mecha: the decrypt mechanism to be used (use `MechanismRSAPKCS1` for `CKM_RSA_PKCS`) :type mecha: :class:`Mechanism` :return: the unwrapped key object :rtype: integer """ m = mecha.to_native() data1 = ckbytelist(wrappedKey) handle = PyKCS11.LowLevel.CK_OBJECT_HANDLE() attrs = self._template2ckattrlist(template) rv = self.lib.C_UnwrapKey(self.session, m, unwrappingKey, data1, attrs, handle) if rv != CKR_OK: raise PyKCS11Error(rv) return handle def deriveKey(self, baseKey, template, mecha): """ C_DeriveKey :param baseKey: the base key handle :type baseKey: integer :param template: template for the unwrapped key :param mecha: the decrypt mechanism to be used (use `ECDH1_DERIVE_Mechanism(...)` for `CKM_ECDH1_DERIVE`) :type mecha: :class:`Mechanism` :return: the unwrapped key object :rtype: integer """ m = mecha.to_native() handle = PyKCS11.LowLevel.CK_OBJECT_HANDLE() attrs = self._template2ckattrlist(template) rv = self.lib.C_DeriveKey(self.session, m, baseKey, attrs, handle) if rv != CKR_OK: raise PyKCS11Error(rv) return handle def isNum(self, type): """ is the type a numerical value? :param type: PKCS#11 type like `CKA_CERTIFICATE_TYPE` :rtype: bool """ if type in (CKA_CERTIFICATE_TYPE, CKA_CLASS, CKA_HW_FEATURE_TYPE, CKA_KEY_GEN_MECHANISM, CKA_KEY_TYPE, CKA_MODULUS_BITS, CKA_VALUE_BITS, CKA_VALUE_LEN): return True return False def isString(self, type): """ is the type a string value? :param type: PKCS#11 type like `CKA_LABEL` :rtype: bool """ if type in (CKA_LABEL, CKA_APPLICATION): return True return False def isBool(self, type): """ is the type a boolean value? :param type: PKCS#11 type like `CKA_ALWAYS_SENSITIVE` :rtype: bool """ if type in (CKA_ALWAYS_AUTHENTICATE, CKA_ALWAYS_SENSITIVE, CKA_DECRYPT, CKA_DERIVE, CKA_ENCRYPT, CKA_EXTRACTABLE, CKA_HAS_RESET, CKA_LOCAL, CKA_MODIFIABLE, CKA_COPYABLE, CKA_DESTROYABLE, CKA_NEVER_EXTRACTABLE, CKA_PRIVATE, CKA_RESET_ON_INIT, CKA_SECONDARY_AUTH, CKA_SENSITIVE, CKA_SIGN, CKA_SIGN_RECOVER, CKA_TOKEN, CKA_TRUSTED, CKA_UNWRAP, CKA_VERIFY, CKA_VERIFY_RECOVER, CKA_WRAP, CKA_WRAP_WITH_TRUSTED): return True return False def isBin(self, type): """ is the type a byte array value? :param type: PKCS#11 type like `CKA_MODULUS` :rtype: bool """ return (not self.isBool(type)) \ and (not self.isString(type)) \ and (not self.isNum(type)) def isAttributeList(self, type): """ is the type a attribute list value? :param type: PKCS#11 type like `CKA_WRAP_TEMPLATE` :rtype: bool """ if type in (CKA_WRAP_TEMPLATE, CKA_UNWRAP_TEMPLATE): return True return False def _template2ckattrlist(self, template): t = PyKCS11.LowLevel.ckattrlist(len(template)) for x in range(len(template)): attr = template[x] if self.isNum(attr[0]): t[x].SetNum(attr[0], int(attr[1])) elif self.isString(attr[0]): t[x].SetString(attr[0], str(attr[1])) elif self.isBool(attr[0]): t[x].SetBool(attr[0], attr[1] == CK_TRUE) elif self.isAttributeList(attr[0]): t[x].SetList(attr[0], self._template2ckattrlist(attr[1])) elif self.isBin(attr[0]): attrBin = attr[1] attrStr = attr[1] if isinstance(attr[1], int): attrStr = str(attr[1]) if isinstance(attr[1], bytes): attrBin = ckbytelist(attrStr) t[x].SetBin(attr[0], attrBin) else: raise PyKCS11Error(-2) return t def generateKey(self, template, mecha=MechanismAESGENERATEKEY): """ generate a secret key :param template: template for the secret key :param mecha: mechanism to use :return: handle of the generated key :rtype: PyKCS11.LowLevel.CK_OBJECT_HANDLE """ t = self._template2ckattrlist(template) ck_handle = PyKCS11.LowLevel.CK_OBJECT_HANDLE() m = mecha.to_native() rv = self.lib.C_GenerateKey(self.session, m, t, ck_handle) if rv != CKR_OK: raise PyKCS11Error(rv) return ck_handle def generateKeyPair(self, templatePub, templatePriv, mecha=MechanismRSAGENERATEKEYPAIR): """ generate a key pair :param templatePub: template for the public key :param templatePriv: template for the private key :param mecha: mechanism to use :return: a tuple of handles (pub, priv) :rtype: tuple """ tPub = self._template2ckattrlist(templatePub) tPriv = self._template2ckattrlist(templatePriv) ck_pub_handle = PyKCS11.LowLevel.CK_OBJECT_HANDLE() ck_prv_handle = PyKCS11.LowLevel.CK_OBJECT_HANDLE() m = mecha.to_native() rv = self.lib.C_GenerateKeyPair(self.session, m, tPub, tPriv, ck_pub_handle, ck_prv_handle) if rv != CKR_OK: raise PyKCS11Error(rv) return ck_pub_handle, ck_prv_handle def findObjects(self, template=()): """ find the objects matching the template pattern :param template: list of attributes tuples (attribute,value). The default value is () and all the objects are returned :type template: list :return: a list of object ids :rtype: list """ t = self._template2ckattrlist(template) # we search for 10 objects by default. speed/memory tradeoff result = PyKCS11.LowLevel.ckobjlist(10) rv = self.lib.C_FindObjectsInit(self.session, t) if rv != CKR_OK: raise PyKCS11Error(rv) res = [] while True: rv = self.lib.C_FindObjects(self.session, result) if rv != CKR_OK: raise PyKCS11Error(rv) for x in result: # make a copy of the handle: the original value get # corrupted (!!) a = CK_OBJECT_HANDLE(self) a.assign(x.value()) res.append(a) if len(result) == 0: break rv = self.lib.C_FindObjectsFinal(self.session) if rv != CKR_OK: raise PyKCS11Error(rv) return res def getAttributeValue(self, obj_id, attr, allAsBinary=False): """ C_GetAttributeValue :param obj_id: object ID returned by :func:`findObjects` :type obj_id: integer :param attr: list of attributes :type attr: list :param allAsBinary: return all values as binary data; default is False. :type allAsBinary: Boolean :return: a list of values corresponding to the list of attributes :rtype: list :see: :func:`getAttributeValue_fragmented` :note: if allAsBinary is True the function do not convert results to Python types (i.e.: CKA_TOKEN to Bool, CKA_CLASS to int, ...). Binary data is returned as :class:`ckbytelist` type, usable as a list containing only bytes. You can easly convert it to a binary string with: ``bytes(ckbytelistVariable)`` or, for Python 2: ``''.join(chr(i) for i in ckbytelistVariable)`` """ valTemplate = PyKCS11.LowLevel.ckattrlist(len(attr)) for x in range(len(attr)): valTemplate[x].SetType(attr[x]) # first call to get the attribute size and reserve the memory rv = self.lib.C_GetAttributeValue(self.session, obj_id, valTemplate) if rv in (CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_SENSITIVE, CKR_ARGUMENTS_BAD): return self.getAttributeValue_fragmented(obj_id, attr, allAsBinary) if rv != CKR_OK: raise PyKCS11Error(rv) # second call to get the attribute value rv = self.lib.C_GetAttributeValue(self.session, obj_id, valTemplate) if rv != CKR_OK: raise PyKCS11Error(rv) res = [] for x in range(len(attr)): if allAsBinary: res.append(valTemplate[x].GetBin()) elif valTemplate[x].IsNum(): res.append(valTemplate[x].GetNum()) elif valTemplate[x].IsBool(): res.append(valTemplate[x].GetBool()) elif valTemplate[x].IsString(): res.append(valTemplate[x].GetString()) elif valTemplate[x].IsBin(): res.append(valTemplate[x].GetBin()) else: raise PyKCS11Error(-2) return res def getAttributeValue_fragmented(self, obj_id, attr, allAsBinary=False): """ Same as :func:`getAttributeValue` except that when some attribute is sensitive or unknown an empty value (None) is returned. Note: this is achived by getting attributes one by one. :see: :func:`getAttributeValue` """ # some attributes does not exists or is sensitive # but we don't know which ones. So try one by one valTemplate = PyKCS11.LowLevel.ckattrlist(1) res = [] for x in range(len(attr)): valTemplate[0].Reset() valTemplate[0].SetType(attr[x]) # first call to get the attribute size and reserve the memory rv = self.lib.C_GetAttributeValue(self.session, obj_id, valTemplate) if rv in (CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_SENSITIVE, CKR_ARGUMENTS_BAD): # append an empty value res.append(None) continue if rv != CKR_OK: raise PyKCS11Error(rv) # second call to get the attribute value rv = self.lib.C_GetAttributeValue(self.session, obj_id, valTemplate) if rv != CKR_OK: raise PyKCS11Error(rv) if allAsBinary: res.append(valTemplate[0].GetBin()) elif valTemplate[0].IsNum(): res.append(valTemplate[0].GetNum()) elif valTemplate[0].IsBool(): res.append(valTemplate[0].GetBool()) elif valTemplate[0].IsString(): res.append(valTemplate[0].GetString()) elif valTemplate[0].IsBin(): res.append(valTemplate[0].GetBin()) elif valTemplate[0].IsAttributeList(): res.append(valTemplate[0].GetBin()) else: raise PyKCS11Error(-2) return res def setAttributeValue(self, obj_id, template): """ C_SetAttributeValue :param obj_id: object ID returned by :func:`findObjects` :type obj_id: integer :param template: list of (attribute, value) pairs :type template: list :return: Nothing :rtype: None """ templ = self._template2ckattrlist(template) rv = self.lib.C_SetAttributeValue(self.session, obj_id, templ) if rv != CKR_OK: raise PyKCS11Error(rv) return None def seedRandom(self, seed): """ C_SeedRandom :param seed: seed material :type seed: iterable """ low_seed = ckbytelist(seed) rv = self.lib.C_SeedRandom(self.session, low_seed) if rv != CKR_OK: raise PyKCS11Error(rv) def generateRandom(self, size=16): """ C_GenerateRandom :param size: number of random bytes to get :type size: integer :note: the returned value is an instance of :class:`ckbytelist`. You can easly convert it to a binary string with: ``bytes(random)`` or, for Python 2: ``''.join(chr(i) for i in random)`` """ low_rand = ckbytelist([0] * size) rv = self.lib.C_GenerateRandom(self.session, low_rand) if rv != CKR_OK: raise PyKCS11Error(rv) return low_rand if __name__ == "__main__": # sample test/debug code p = PyKCS11Lib() p.load() print("getInfo") print(p.getInfo()) print() print("getSlotList") s = p.getSlotList() print("slots:", s) slot = s[0] print("using slot:", slot) print() print("getSlotInfo") print(p.getSlotInfo(slot)) print() print("getTokenInfo") print(p.getTokenInfo(slot)) print() print("openSession") se = p.openSession(slot) print() print("sessionInfo") print(se.getSessionInfo()) print() print("seedRandom") try: se.seedRandom([1, 2, 3, 4]) except PyKCS11Error as e: print(e) print("generateRandom") print(se.generateRandom()) print() print("login") se.login(pin="0000") print() print("sessionInfo") print(se.getSessionInfo()) print() print("findObjects") objs = se.findObjects([(CKA_CLASS, CKO_CERTIFICATE)]) print("Nb objetcs:", len(objs)) print(objs) print() print("getAttributeValue") for o in objs: attr = se.getAttributeValue(o, [CKA_LABEL, CKA_CLASS]) print(attr) print() print("logout") se.logout() print() print("closeSession") se.closeSession() ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1729078230.1387758 pykcs11-1.5.17/PyKCS11.egg-info/0000755000076500000240000000000014703721726015467 5ustar00rousseaustaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729078230.0 pykcs11-1.5.17/PyKCS11.egg-info/PKG-INFO0000644000076500000240000000251114703721726016563 0ustar00rousseaustaffMetadata-Version: 2.1 Name: PyKCS11 Version: 1.5.17 Summary: A Full PKCS#11 wrapper for Python Home-page: https://github.com/LudovicRousseau/PyKCS11 Download-URL: http://sourceforge.net/projects/pkcs11wrap/files/pykcs11/ Author: Giuseppe Amato (Midori) Author-email: paipai@tiscali.it Maintainer: Ludovic Rousseau Maintainer-email: ludovic.rousseau@free.fr License: GPL Keywords: crypto,pki,pkcs11,c++ Platform: Win32 Unix Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License (GPL) Classifier: Natural Language :: English Classifier: Operating System :: Microsoft :: Windows Classifier: Operating System :: OS Independent Classifier: Operating System :: Unix Classifier: Programming Language :: C Classifier: Programming Language :: C++ Classifier: Programming Language :: Python Classifier: Topic :: Security :: Cryptography Classifier: Topic :: Software Development :: Libraries :: Python Modules License-File: COPYING A complete PKCS#11 wrapper for Python. You can use any PKCS#11 (aka CryptoKi) module such as the PSM which comes as part of mozilla or the various modules supplied by vendors of hardware crypto tokens, and almost all PKCS#11 functions and data types. The wrapper has been generated with the help of the SWIG compiler. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729078230.0 pykcs11-1.5.17/PyKCS11.egg-info/SOURCES.txt0000644000076500000240000000270514703721726017357 0ustar00rousseaustaffCOPYING Changes.txt MANIFEST.in Makefile README.md dev-requirements.txt get_PYKCS11LIB.py pyproject.toml run_test.py setup.py tox.ini PyKCS11/__init__.py PyKCS11.egg-info/PKG-INFO PyKCS11.egg-info/SOURCES.txt PyKCS11.egg-info/dependency_links.txt PyKCS11.egg-info/top_level.txt docs/Makefile docs/api.rst docs/conf.py docs/generate.sh docs/index.rst docs/license.rst docs/samples.rst samples/destroy_by_ID.py samples/dumpit.py samples/ec_generate.py samples/ec_signature.py samples/encrypt.py samples/events.py samples/generate.py samples/genkeypair_import_cert.py samples/getinfo.py samples/modulus.py samples/rsa_encrypt.py samples/signature.py samples/unblock.py samples/LowLevel/InitTokenPin.py samples/LowLevel/dumpit.py samples/LowLevel/rand.py samples/LowLevel/test.py samples/LowLevel/test1.py src/.DS_Store src/ck_attribute_smart.cpp src/ck_attribute_smart.h src/dyn_generic.h src/dyn_unix.c src/dyn_win32.c src/pkcs11lib.cpp src/pkcs11lib.h src/pykcs11.cpp src/pykcs11.i src/pykcs11string.cpp src/pykcs11string.h src/stdafx.h src/utility.cpp src/utility.h src/opensc/.DS_Store src/opensc/pkcs11.h test/test_CK.py test/test_LowLevel.py test/test_asymetric.py test/test_asymetric_ECC.py test/test_asymetric_gost.py test/test_ckbytelist.py test/test_derive.py test/test_digest.py test/test_exception.py test/test_gc.py test/test_info.py test/test_init.py test/test_load.py test/test_objects.py test/test_pin.py test/test_random.py test/test_symetric.py test/test_wrap.py././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729078230.0 pykcs11-1.5.17/PyKCS11.egg-info/dependency_links.txt0000644000076500000240000000000114703721726021535 0ustar00rousseaustaff ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729078230.0 pykcs11-1.5.17/PyKCS11.egg-info/top_level.txt0000644000076500000240000000001014703721726020210 0ustar00rousseaustaffPyKCS11 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1704624376.0 pykcs11-1.5.17/README.md0000644000076500000240000000334214546500370014156 0ustar00rousseaustaffPyKCS11 - PKCS#11 Wrapper for Python - Project Overview ======================================================= Authors ======= - Copyright (C) 2004 Midori (midori -- a-t -- paipai dot net) - Copyright (C) 2006-2018 Ludovic Rousseau (ludovic.rousseau@free.fr) Licence ======= This file is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Status ====== [![Coverage Status](https://coveralls.io/repos/github/LudovicRousseau/PyKCS11/badge.svg?branch=master)](https://coveralls.io/github/LudovicRousseau/PyKCS11?branch=master) API === The API documentation is available at https://pkcs11wrap.sourceforge.io/api/ Installation ============ pip install pykcs11 Unix build Howto ================ To build: python3 -m venv temp source temp/bin/activate pip3 install -r dev-requirements.txt make To install in editable mode: make install Windows build Howto =================== Prerequisites * Install python3 (and add "C:\Python34;C:\Python34\Scripts" to PATH environment variable) * Install swig (and add swig install folder to PATH environment variable) * Install Visual studio 2010 SDK To install: nmake install ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1704624376.0 pykcs11-1.5.17/dev-requirements.txt0000644000076500000240000000005714546500370016737 0ustar00rousseaustaffcoverage coveralls asn1crypto build setuptools ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1729078230.1087651 pykcs11-1.5.17/docs/0000755000076500000240000000000014703721726013632 5ustar00rousseaustaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1680989591.0 pykcs11-1.5.17/docs/Makefile0000644000076500000240000000113414414356627015274 0ustar00rousseaustaff# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SPHINXPROJ = PyKCS11 SOURCEDIR = . BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1548190635.0 pykcs11-1.5.17/docs/api.rst0000644000076500000240000000013613421701653015126 0ustar00rousseaustaffAPI documentation ***************** .. automodule:: PyKCS11 :members: :undoc-members: ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729077598.0 pykcs11-1.5.17/docs/conf.py0000644000076500000240000001206614703720536015134 0ustar00rousseaustaff# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- Project information ----------------------------------------------------- project = 'PyKCS11' copyright = '2018, Giuseppe Amato (Midori), Ludovic Rousseau' author = 'Giuseppe Amato (Midori), Ludovic Rousseau' # The short X.Y version version = '1.5' # The full version, including alpha/beta/rc tags release = '1.5.17' # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.coverage', 'sphinx.ext.viewcode', 'sphinx.ext.githubpages', 'sphinx.ext.autosummary', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = 'en' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path . exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # Both the class’ and the __init__ method’s docstring are concatenated # and inserted. autoclass_content = 'both' # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'bizstyle' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = [] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # The default sidebars (for documents that don't match any pattern) are # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # # html_sidebars = {} # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = 'PyKCS11doc' # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'PyKCS11.tex', 'PyKCS11 Documentation', 'Giuseppe Amato (Midori), Ludovic Rousseau', 'manual'), ] # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'pykcs11', 'PyKCS11 Documentation', [author], 1) ] # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'PyKCS11', 'PyKCS11 Documentation', author, 'PyKCS11', 'One line description of project.', 'Miscellaneous'), ] # -- Extension configuration ------------------------------------------------- ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1704624376.0 pykcs11-1.5.17/docs/generate.sh0000755000076500000240000000043014546500370015753 0ustar00rousseaustaff#!/bin/bash set -e cd $(dirname $0) # Enable a virtualenv before running the script to avoid modifying # the system Python libraries python3 -m venv tmp source tmp/bin/activate pip3 install sphinx setuptools (cd .. ; python3 -m pip install .) make html deactivate rm -r tmp ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1714833130.0 pykcs11-1.5.17/docs/index.rst0000644000076500000240000000163614615443352015477 0ustar00rousseaustaff.. PyKCS11 documentation master file, created by sphinx-quickstart on Sat Jun 23 14:56:45 2018. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to PyKCS11's documentation ================================== Download ******** The PyKCS11 project is available from different sources: * pypi https://pypi.org/project/pykcs11/ * github https://github.com/LudovicRousseau/PyKCS11 * sourceforge https://sourceforge.net/projects/pkcs11wrap/ Bug reports *********** Report bugs or issues on `github issues `_ Report patches as `github pull requests `_ API Documentation ***************** .. toctree:: :maxdepth: 4 :caption: Contents: api samples license Indices and tables ================== * :ref:`genindex` * :ref:`search` ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1548190635.0 pykcs11-1.5.17/docs/license.rst0000644000076500000240000000132513421701653016000 0ustar00rousseaustaffLicense ####### PyKCS11 is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. .. literalinclude:: ../COPYING ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1548190635.0 pykcs11-1.5.17/docs/samples.rst0000644000076500000240000000133713421701653016025 0ustar00rousseaustaffPyKCS11 samples codes ===================== Unblock a user PIN """""""""""""""""" .. literalinclude:: ../samples/unblock.py Generate a key pair """"""""""""""""""" .. literalinclude:: ../samples/generate.py Encrypt and decrypt """"""""""""""""""" .. literalinclude:: ../samples/encrypt.py Get token events """""""""""""""" .. literalinclude:: ../samples/events.py Get a public key modulus """""""""""""""""""""""" .. literalinclude:: ../samples/modulus.py RSA sign & verify """"""""""""""""" .. literalinclude:: ../samples/signature.py Get token information """"""""""""""""""""" .. literalinclude:: ../samples/getinfo.py Dump all the token objects """""""""""""""""""""""""" .. literalinclude:: ../samples/dumpit.py ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1714838638.0 pykcs11-1.5.17/get_PYKCS11LIB.py0000755000076500000240000000311314615456156015502 0ustar00rousseaustaff#!/usr/bin/env python3 import os import sys def get_PYKCS11LIB(): # already configured if "PYKCS11LIB" in os.environ: return os.environ["PYKCS11LIB"] if "PKCS11SPY" in os.environ: # use OpenSC PKCS#11 spy if PKCS11SPY is defined as the PKCS#11 lib # to use LIBS = [ "/usr/local/lib/pkcs11-spy.so", # macOS or local build "/usr/lib/x86_64-linux-gnu/pkcs11-spy.so", # Debian amd64 "/usr/lib64/pkcs11/pkcs11-spy.so", # Fedora Linux ] else: if sys.maxsize > 2 ** 32: # 64-bits WINDOWS_SOFTHSM = "c:/SoftHSM2/lib/softhsm2-x64.dll" else: # 32-bits WINDOWS_SOFTHSM = "c:/SoftHSM2/lib/softhsm2.dll" # use SoftHSM2 or SoftHSM1 LIBS = [ "/usr/local/lib/softhsm/libsofthsm2.so", # macOS or local build "/opt/homebrew/lib/softhsm/libsofthsm2.so", # macOS arm64 "/usr/lib/softhsm/libsofthsm2.so", # Debian libsofthsm2 "/usr/lib/softhsm/libsofthsm.so", # Debian libsofthsm "/usr/lib/libsofthsm.so", # Ubuntu 12.04 libsofthsm "/usr/lib/x86_64-linux-gnu/softhsm/libsofthsm2.so", # Ubuntu 16.04 libsofthsm2 "/usr/lib64/pkcs11/libsofthsm2.so", # Fedora Linux WINDOWS_SOFTHSM, # Windows ] for lib in LIBS: if os.path.isfile(lib): return lib raise Exception("PYKCS11LIB is not defined. No SoftHSM library found?") if __name__ == "__main__": lib = get_PYKCS11LIB() print("PYKCS11LIB={}".format(lib)) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1713358390.0 pykcs11-1.5.17/pyproject.toml0000644000076500000240000000013114607743066015615 0ustar00rousseaustaff[build-system] requires = ["setuptools", "swig"] build-backend = "setuptools.build_meta" ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1680987959.0 pykcs11-1.5.17/run_test.py0000755000076500000240000000101114414353467015115 0ustar00rousseaustaff#!/usr/bin/env python3 # use: # ./run_test.py # ./run_test.py test_ckbytelist.py import unittest import os import sys import get_PYKCS11LIB pattern = "test*.py" if len(sys.argv) > 1: pattern = sys.argv[1] if __name__ == "__main__": lib = get_PYKCS11LIB.get_PYKCS11LIB() os.environ["PYKCS11LIB"] = lib tl = unittest.TestLoader() suite = tl.discover("test", pattern=pattern) result = unittest.TextTestRunner(verbosity=2).run(suite) if result.errors or result.failures: sys.exit(1) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1729078230.1171212 pykcs11-1.5.17/samples/0000755000076500000240000000000014703721726014346 5ustar00rousseaustaff././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1729078230.1192718 pykcs11-1.5.17/samples/LowLevel/0000755000076500000240000000000014703721726016077 5ustar00rousseaustaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1662305708.0 pykcs11-1.5.17/samples/LowLevel/InitTokenPin.py0000755000076500000240000000756714305142654021041 0ustar00rousseaustaff#!/usr/bin/env python3 # Copyright (C) 2004 Midori (midori -- a-t -- paipai dot net) # Copyright (C) 2018 Ludovic Rousseau (ludovic.rousseau@free.fr) # # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. import PyKCS11.LowLevel from PyKCS11 import ckbytelist import os a = PyKCS11.LowLevel.CPKCS11Lib() info = PyKCS11.LowLevel.CK_INFO() slotInfo = PyKCS11.LowLevel.CK_SLOT_INFO() lib = os.getenv("PYKCS11LIB") if lib is None: raise (Exception("Define PYKCS11LIB")) session = PyKCS11.LowLevel.CK_SESSION_HANDLE() sessionInfo = PyKCS11.LowLevel.CK_SESSION_INFO() tokenInfo = PyKCS11.LowLevel.CK_TOKEN_INFO() slotList = PyKCS11.LowLevel.ckintlist() pin = ckbytelist("123456") puk = ckbytelist("12345678") Label = "PyKCS#11 Initialized Token " print("Load of " + lib + ": " + str(a.Load(lib))) print("C_GetInfo: " + hex(a.C_GetInfo(info))) print("Library manufacturerID: " + info.GetManufacturerID()) del info print("C_GetSlotList(NULL): " + hex(a.C_GetSlotList(1, slotList))) print("\tAvailable Slots: " + str(len(slotList))) if len(slotList) != 0: print("\tC_SlotInfo(): " + hex(a.C_GetSlotInfo(slotList[0], slotInfo))) print("\tC_GetTokenInfo(): " + hex(a.C_GetTokenInfo(slotList[0], tokenInfo))) print( "\t\tTokenInfo: Label=" + tokenInfo.GetLabel() + ", ManufacturerID=" + tokenInfo.GetManufacturerID() ) print( "\t\tTokenInfo: flags=" + hex(tokenInfo.flags) + ", Model=" + tokenInfo.GetModel() ) print("\tC_InitToken(): " + hex(a.C_InitToken(slotList[0], puk, Label))) print("\tC_GetTokenInfo(): " + hex(a.C_GetTokenInfo(slotList[0], tokenInfo))) print( "\t\tTokenInfo: Label=" + tokenInfo.GetLabel() + ", ManufacturerID=" + tokenInfo.GetManufacturerID() ) print( "\t\tTokenInfo: flags=" + hex(tokenInfo.flags) + ", Model=" + tokenInfo.GetModel() ) print( "\tC_OpenSession(): " + hex( a.C_OpenSession( slotList[0], PyKCS11.LowLevel.CKF_SERIAL_SESSION | PyKCS11.LowLevel.CKF_RW_SESSION, session, ) ) ) print("\t\tSession:" + str(session)) print("\tC_GetSessionInfo(): " + hex(a.C_GetSessionInfo(session, sessionInfo))) print( "\t\tSessionInfo: state=" + hex(sessionInfo.state) + ", flags=" + hex(sessionInfo.flags) ) print("\tC_Login(SO): " + hex(a.C_Login(session, PyKCS11.LowLevel.CKU_SO, puk))) print("\tC_InitPIN(): " + hex(a.C_InitPIN(session, pin))) print("\tC_Logout(SO): " + hex(a.C_Logout(session))) print("\tC_GetTokenInfo(): " + hex(a.C_GetTokenInfo(slotList[0], tokenInfo))) print( "\t\tTokenInfo: Label=" + tokenInfo.GetLabel() + ", ManufacturerID=" + tokenInfo.GetManufacturerID() ) print( "\t\tTokenInfo: flags=" + hex(tokenInfo.flags) + ", Model=" + tokenInfo.GetModel() ) print("C_Login(USER): " + hex(a.C_Login(session, PyKCS11.LowLevel.CKU_USER, pin))) print("C_Logout(USER): " + hex(a.C_Logout(session))) print("C_CloseSession(): " + hex(a.C_CloseSession(session))) print("C_Finalize(): " + hex(a.C_Finalize())) print(a.Unload()) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1662305708.0 pykcs11-1.5.17/samples/LowLevel/dumpit.py0000755000076500000240000001376714305142654017767 0ustar00rousseaustaff#!/usr/bin/env python3 # Copyright (C) 2004 Midori (midori -- a-t -- paipai dot net) # Copyright (C) 2006-2018 Ludovic Rousseau (ludovic.rousseau@free.fr) # # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. from PyKCS11.LowLevel import * from PyKCS11 import ckbytelist import os a = CPKCS11Lib() info = CK_INFO() slotInfo = CK_SLOT_INFO() lib = os.getenv("PYKCS11LIB") if lib is None: raise (Exception("Define PYKCS11LIB")) session = CK_SESSION_HANDLE() sessionInfo = CK_SESSION_INFO() tokenInfo = CK_TOKEN_INFO() slotList = ckintlist() pin = ckbytelist("1234") print("Load of " + lib + ": " + str(a.Load(lib))) print("C_GetInfo:", hex(a.C_GetInfo(info))) print("Library manufacturerID:", info.GetManufacturerID()) del info print("C_GetSlotList(NULL): " + hex(a.C_GetSlotList(0, slotList))) print("\tAvailable Slots: " + str(len(slotList))) for x in range(len(slotList)): print("\tC_SlotInfo(): " + hex(a.C_GetSlotInfo(slotList[x], slotInfo))) print( "\t\tSlot N." + str(x) + ": ID=" + str(slotList[x]) + ", name='" + slotInfo.GetSlotDescription() + "'" ) print( "\tC_OpenSession(): " + hex( a.C_OpenSession(slotList[x], CKF_SERIAL_SESSION | CKF_RW_SESSION, session) ) ) print("\t\tSession:" + str(session)) print("\tC_GetSessionInfo(): " + hex(a.C_GetSessionInfo(session, sessionInfo))) print( "\t\tSessionInfo: state=" + hex(sessionInfo.state) + ", flags=" + hex(sessionInfo.flags) ) print("\tC_GetTokenInfo(): " + hex(a.C_GetTokenInfo(slotList[x], tokenInfo))) print( "\t\tTokenInfo: Label=" + tokenInfo.GetLabel() + ", ManufacturerID=" + tokenInfo.GetManufacturerID() ) print( "\t\tTokenInfo: flags=" + hex(tokenInfo.flags) + ", Model=" + tokenInfo.GetModel() ) print("\tC_Login(): " + hex(a.C_Login(session, CKU_USER, pin))) print("\tC_Logout(): " + hex(a.C_Logout(session))) print("\tC_CloseSession(): " + hex(a.C_CloseSession(session))) print( "C_OpenSession(): " + hex(a.C_OpenSession(slotList[0], CKF_SERIAL_SESSION, session)) ) print("C_Login(): " + hex(a.C_Login(session, CKU_USER, pin))) SearchResult = ckobjlist(10) SearchTemplate = ckattrlist(0) # SearchTemplate[0].SetNum(CKA_CLASS, CKO_CERTIFICATE) # SearchTemplate[1].SetBool(CKA_TOKEN, True) print("C_FindObjectsInit: " + hex(a.C_FindObjectsInit(session, SearchTemplate))) print("C_FindObjects: " + hex(a.C_FindObjects(session, SearchResult))) print("C_FindObjectsFinal: " + hex(a.C_FindObjectsFinal(session))) attributes = [ ["CKA_CLASS", CKA_CLASS], ["CKA_TOKEN", CKA_TOKEN], ["CKA_PRIVATE", CKA_PRIVATE], ["CKA_LABEL", CKA_LABEL], ["CKA_APPLICATION", CKA_APPLICATION], ["CKA_VALUE", CKA_VALUE], ["CKA_CERTIFICATE_TYPE", CKA_CERTIFICATE_TYPE], ["CKA_ISSUER", CKA_ISSUER], ["CKA_SERIAL_NUMBER", CKA_SERIAL_NUMBER], ["CKA_KEY_TYPE", CKA_KEY_TYPE], ["CKA_SUBJECT", CKA_SUBJECT], ["CKA_ID", CKA_ID], ["CKA_SENSITIVE", CKA_SENSITIVE], ["CKA_ENCRYPT", CKA_ENCRYPT], ["CKA_DECRYPT", CKA_DECRYPT], ["CKA_WRAP", CKA_WRAP], ["CKA_UNWRAP", CKA_UNWRAP], ["CKA_SIGN", CKA_SIGN], ["CKA_SIGN_RECOVER", CKA_SIGN_RECOVER], ["CKA_VERIFY", CKA_VERIFY], ["CKA_VERIFY_RECOVER", CKA_VERIFY_RECOVER], ["CKA_DERIVE", CKA_DERIVE], ["CKA_START_DATE", CKA_START_DATE], ["CKA_END_DATE", CKA_END_DATE], ["CKA_MODULUS", CKA_MODULUS], ["CKA_MODULUS_BITS", CKA_MODULUS_BITS], ["CKA_PUBLIC_EXPONENT", CKA_PUBLIC_EXPONENT], ["CKA_PRIVATE_EXPONENT", CKA_PRIVATE_EXPONENT], ["CKA_PRIME_1", CKA_PRIME_1], ["CKA_PRIME_2", CKA_PRIME_2], ["CKA_EXPONENT_1", CKA_EXPONENT_1], ["CKA_EXPONENT_2", CKA_EXPONENT_2], ["CKA_COEFFICIENT", CKA_COEFFICIENT], ["CKA_PRIME", CKA_PRIME], ["CKA_SUBPRIME", CKA_SUBPRIME], ["CKA_BASE", CKA_BASE], ["CKA_VALUE_BITS", CKA_VALUE_BITS], ["CKA_VALUE_LEN", CKA_VALUE_LEN], ["CKA_EXTRACTABLE", CKA_EXTRACTABLE], ["CKA_LOCAL", CKA_LOCAL], ["CKA_NEVER_EXTRACTABLE", CKA_NEVER_EXTRACTABLE], ["CKA_ALWAYS_SENSITIVE", CKA_ALWAYS_SENSITIVE], ["CKA_MODIFIABLE", CKA_MODIFIABLE], ["CKA_ECDSA_PARAMS", CKA_ECDSA_PARAMS], ["CKA_EC_POINT", CKA_EC_POINT], ] for x in SearchResult: print("object: " + hex(x.value())) valTemplate = ckattrlist(1) for attr in attributes: valTemplate[0].Reset() valTemplate[0].SetType(attr[1]) # first call to get the attribute size and reserve the memory a.C_GetAttributeValue(session, x, valTemplate) # second call to get the attribute value rv = a.C_GetAttributeValue(session, x, valTemplate) if rv == CKR_OK: print("\t" + attr[0] + ": ", end=" ") if valTemplate[0].IsNum(): print(valTemplate[0].GetNum()) if valTemplate[0].IsBool(): print(valTemplate[0].GetBool()) if valTemplate[0].IsString(): print(valTemplate[0].GetString()) if valTemplate[0].IsBin(): print("(" + str(valTemplate[0].GetLen()) + " bytes)", end=" ") print(list(map(hex, valTemplate[0].GetBin()))) print("C_Logout(): " + hex(a.C_Logout(session))) print("C_CloseSession(): " + hex(a.C_CloseSession(session))) print("C_Finalize(): " + hex(a.C_Finalize())) print(a.Unload()) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1662305708.0 pykcs11-1.5.17/samples/LowLevel/rand.py0000755000076500000240000000377414305142654017406 0ustar00rousseaustaff#!/usr/bin/env python3 # Copyright (C) 2010-2014 Ludovic Rousseau # # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 # USA. import PyKCS11.LowLevel import os a = PyKCS11.LowLevel.CPKCS11Lib() info = PyKCS11.LowLevel.CK_INFO() slotInfo = PyKCS11.LowLevel.CK_SLOT_INFO() lib = os.getenv("PYKCS11LIB") if lib is None: raise (Exception("Define PYKCS11LIB")) session = PyKCS11.LowLevel.CK_SESSION_HANDLE() slotList = PyKCS11.LowLevel.ckintlist() rand = PyKCS11.LowLevel.ckbytelist(20) seed = PyKCS11.LowLevel.ckbytelist(5) print("Load of " + lib + ": " + str(a.Load(lib))) print("C_GetInfo: " + hex(a.C_GetInfo(info))) print("Library manufacturerID: " + info.GetManufacturerID()) del info print("C_GetSlotList(NULL): " + hex(a.C_GetSlotList(0, slotList))) print("\tAvailable Slots: " + str(len(slotList))) print( "C_OpenSession(): " + hex( a.C_OpenSession( slotList[0], PyKCS11.LowLevel.CKF_RW_SESSION | PyKCS11.LowLevel.CKF_SERIAL_SESSION, session, ) ) ) print(" ".join("%02X" % i for i in seed)) print("C_SeedRandom(): " + hex(a.C_SeedRandom(session, seed))) print("C_GenerateRandom(): " + hex(a.C_GenerateRandom(session, rand))) print(" ".join("%02X" % i for i in rand)) print("C_CloseSession(): " + hex(a.C_CloseSession(session))) print("C_Finalize(): " + hex(a.C_Finalize())) print(a.Unload()) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1662305708.0 pykcs11-1.5.17/samples/LowLevel/test.py0000755000076500000240000001074514305142654017435 0ustar00rousseaustaff#!/usr/bin/env python3 # Copyright (C) 2004 Midori (midori -- a-t -- paipai dot net) # Copyright (C) 2018 Ludovic Rousseau (ludovic.rousseau@free.fr) # # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. import PyKCS11.LowLevel from PyKCS11 import ckbytelist import os a = PyKCS11.LowLevel.CPKCS11Lib() info = PyKCS11.LowLevel.CK_INFO() slotInfo = PyKCS11.LowLevel.CK_SLOT_INFO() lib = os.getenv("PYKCS11LIB") if lib is None: raise (Exception("Define PYKCS11LIB")) session = PyKCS11.LowLevel.CK_SESSION_HANDLE() sessionInfo = PyKCS11.LowLevel.CK_SESSION_INFO() tokenInfo = PyKCS11.LowLevel.CK_TOKEN_INFO() slotList = PyKCS11.LowLevel.ckintlist() pin = ckbytelist("1234") print("Load of " + lib + ": " + str(a.Load(lib))) print("C_GetInfo: " + hex(a.C_GetInfo(info))) print("Library manufacturerID: " + info.GetManufacturerID()) del info print("C_GetSlotList(NULL): " + hex(a.C_GetSlotList(0, slotList))) print("\tAvailable Slots: " + str(len(slotList))) for x in range(len(slotList)): print("\tC_SlotInfo(): " + hex(a.C_GetSlotInfo(slotList[x], slotInfo))) print( "\t\tSlot N." + str(x) + ": ID=" + str(slotList[x]) + ", name='" + slotInfo.GetSlotDescription() + "'" ) print( "\tC_OpenSession(): " + hex( a.C_OpenSession( slotList[x], PyKCS11.LowLevel.CKF_SERIAL_SESSION | PyKCS11.LowLevel.CKF_RW_SESSION, session, ) ) ) print("\t\tSession:" + str(session)) print("\tC_GetSessionInfo(): " + hex(a.C_GetSessionInfo(session, sessionInfo))) print( "\t\tSessionInfo: state=" + hex(sessionInfo.state) + ", flags=" + hex(sessionInfo.flags) ) print("\tC_GetTokenInfo(): " + hex(a.C_GetTokenInfo(slotList[x], tokenInfo))) print( "\t\tTokenInfo: Label=" + tokenInfo.GetLabel() + ", ManufacturerID=" + tokenInfo.GetManufacturerID() ) print( "\t\tTokenInfo: flags=" + hex(tokenInfo.flags) + ", Model=" + tokenInfo.GetModel() ) print("\tC_Login(): " + hex(a.C_Login(session, PyKCS11.LowLevel.CKU_USER, pin))) print("\tC_Logout(): " + hex(a.C_Logout(session))) print("\tC_CloseSession(): " + hex(a.C_CloseSession(session))) print( "C_OpenSession(): " + hex(a.C_OpenSession(slotList[0], PyKCS11.LowLevel.CKF_SERIAL_SESSION, session)) ) print("C_Login(): " + hex(a.C_Login(session, PyKCS11.LowLevel.CKU_USER, pin))) SearchResult = PyKCS11.LowLevel.ckobjlist(10) SearchTemplate = PyKCS11.LowLevel.ckattrlist(2) SearchTemplate[0].SetNum(PyKCS11.LowLevel.CKA_CLASS, PyKCS11.LowLevel.CKO_CERTIFICATE) SearchTemplate[1].SetBool(PyKCS11.LowLevel.CKA_TOKEN, True) print("C_FindObjectsInit: " + hex(a.C_FindObjectsInit(session, SearchTemplate))) print("C_FindObjects: " + hex(a.C_FindObjects(session, SearchResult))) print("C_FindObjectsFinal: " + hex(a.C_FindObjectsFinal(session))) for x in SearchResult: print("object: " + hex(x.value())) valTemplate = PyKCS11.LowLevel.ckattrlist(2) valTemplate[0].SetType(PyKCS11.LowLevel.CKA_LABEL) # valTemplate[0].Reserve(128) valTemplate[1].SetType(PyKCS11.LowLevel.CKA_CLASS) # valTemplate[1].Reserve(4) print( "C_GetAttributeValue(): " + hex(a.C_GetAttributeValue(session, x, valTemplate)) ) print( "CKA_LABEL Len: ", valTemplate[0].GetLen(), " CKA_CLASS Len: ", valTemplate[1].GetLen(), ) print( "C_GetAttributeValue(): " + hex(a.C_GetAttributeValue(session, x, valTemplate)) ) print("\tCKO_CERTIFICATE: " + valTemplate[0].GetString()) print("\tCKA_TOKEN: " + str(valTemplate[1].GetNum())) print("C_Logout(): " + hex(a.C_Logout(session))) print("C_CloseSession(): " + hex(a.C_CloseSession(session))) print("C_Finalize(): " + hex(a.C_Finalize())) print(a.Unload()) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1662305708.0 pykcs11-1.5.17/samples/LowLevel/test1.py0000755000076500000240000001124014305142654017505 0ustar00rousseaustaff#!/usr/bin/env python3 # Copyright (C) 2004 Midori (midori -- a-t -- paipai dot net) # Copyright (C) 2018 Ludovic Rousseau (ludovic.rousseau@free.fr) # # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. import PyKCS11.LowLevel from PyKCS11 import ckbytelist import os a = PyKCS11.LowLevel.CPKCS11Lib() info = PyKCS11.LowLevel.CK_INFO() slotInfo = PyKCS11.LowLevel.CK_SLOT_INFO() lib = os.getenv("PYKCS11LIB") if lib is None: raise (Exception("Define PYKCS11LIB")) session = PyKCS11.LowLevel.CK_SESSION_HANDLE() sessionInfo = PyKCS11.LowLevel.CK_SESSION_INFO() tokenInfo = PyKCS11.LowLevel.CK_TOKEN_INFO() slotList = PyKCS11.LowLevel.ckintlist() pin = ckbytelist("1234") print("Load of " + lib + ": " + str(a.Load(lib))) print("C_GetInfo: " + hex(a.C_GetInfo(info))) print("Library manufacturerID: " + info.GetManufacturerID()) del info print("C_GetSlotList(NULL): " + hex(a.C_GetSlotList(0, slotList))) print("\tAvailable Slots: " + str(len(slotList))) for x in range(len(slotList)): print("\tC_SlotInfo(): " + hex(a.C_GetSlotInfo(slotList[x], slotInfo))) print( "\t\tSlot N." + str(x) + ": ID=" + str(slotList[x]) + ", name='" + slotInfo.GetSlotDescription() + "'" ) print( "\tC_OpenSession(): " + hex( a.C_OpenSession( slotList[x], PyKCS11.LowLevel.CKF_SERIAL_SESSION | PyKCS11.LowLevel.CKF_RW_SESSION, session, ) ) ) print("\t\tSession:" + str(session)) print("\tC_GetSessionInfo(): " + hex(a.C_GetSessionInfo(session, sessionInfo))) print( "\t\tSessionInfo: state=" + hex(sessionInfo.state) + ", flags=" + hex(sessionInfo.flags) ) print("\tC_GetTokenInfo(): " + hex(a.C_GetTokenInfo(slotList[x], tokenInfo))) print( "\t\tTokenInfo: Label=" + tokenInfo.GetLabel() + ", ManufacturerID=" + tokenInfo.GetManufacturerID() ) print( "\t\tTokenInfo: flags=" + hex(tokenInfo.flags) + ", Model=" + tokenInfo.GetModel() ) print("\tC_Login(): " + hex(a.C_Login(session, PyKCS11.LowLevel.CKU_USER, pin))) print("\tC_Logout(): " + hex(a.C_Logout(session))) print("\tC_CloseSession(): " + hex(a.C_CloseSession(session))) print( "C_OpenSession(): " + hex( a.C_OpenSession( slotList[0], PyKCS11.LowLevel.CKF_RW_SESSION | PyKCS11.LowLevel.CKF_SERIAL_SESSION, session, ) ) ) print("C_Login(): " + hex(a.C_Login(session, PyKCS11.LowLevel.CKU_USER, pin))) SearchResult = PyKCS11.LowLevel.ckobjlist(10) SearchTemplate = PyKCS11.LowLevel.ckattrlist(2) SearchTemplate[0].SetNum(PyKCS11.LowLevel.CKA_CLASS, PyKCS11.LowLevel.CKO_CERTIFICATE) SearchTemplate[1].SetBool(PyKCS11.LowLevel.CKA_TOKEN, True) print("C_FindObjectsInit: " + hex(a.C_FindObjectsInit(session, SearchTemplate))) print("C_FindObjects: " + hex(a.C_FindObjects(session, SearchResult))) print("C_FindObjectsFinal: " + hex(a.C_FindObjectsFinal(session))) for x in SearchResult: print("object " + hex(x.value())) valTemplate = PyKCS11.LowLevel.ckattrlist(1) valTemplate[0].SetType(PyKCS11.LowLevel.CKA_ISSUER) # valTemplate[0].Reserve(128) print( "C_GetAttributeValue(): " + hex(a.C_GetAttributeValue(session, x, valTemplate)) ) print("CKA_ISSUER Len: ", valTemplate[0].GetLen()) print( "C_GetAttributeValue(): " + hex(a.C_GetAttributeValue(session, x, valTemplate)) ) binval = list(valTemplate[0].GetBin()) print("binval=", binval) binval[0] = 0 valTemplate[0].SetBin(PyKCS11.LowLevel.CKA_ISSUER, binval) binval = valTemplate[0].GetBin() # list(valTemplate[0].GetBin()) print("binval[0]=", binval[0]) binval[0] = 0 print( "C_SetAttributeValue(): " + hex(a.C_SetAttributeValue(session, x, valTemplate)) ) print("C_Logout(): " + hex(a.C_Logout(session))) print("C_CloseSession(): " + hex(a.C_CloseSession(session))) print("C_Finalize(): " + hex(a.C_Finalize())) print(a.Unload()) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1636117001.0 pykcs11-1.5.17/samples/destroy_by_ID.py0000755000076500000240000000242114141225011017437 0ustar00rousseaustaff#!/usr/bin/env python3 # Copyright (C) 2017 Ludovic Rousseau # # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import print_function import PyKCS11 # the CKA_ID of the objects to destroy object_id = (0x22,) # slot PIN code pin = "1234" pkcs11 = PyKCS11.PyKCS11Lib() pkcs11.load() slot = pkcs11.getSlotList(tokenPresent=True)[0] session = pkcs11.openSession(slot, PyKCS11.CKF_RW_SESSION) session.login(pin) template = [(PyKCS11.CKA_ID, object_id)] objects = session.findObjects(template) for obj in objects: print(obj) session.destroyObject(obj) session.logout() session.closeSession() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1632046533.0 pykcs11-1.5.17/samples/dumpit.py0000755000076500000240000001630314121606705016221 0ustar00rousseaustaff#!/usr/bin/env python3 # Copyright (C) 2006-2014 Ludovic Rousseau (ludovic.rousseau@free.fr) # # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. import PyKCS11 import binascii import getopt import sys import platform # from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/142812 # Title: Hex dumper # Submitter: Sebastien Keim (other recipes) # Last Updated: 2002/08/05 # Version no: 1.0 def dump(src, length=16): def to_ascii(x): if x >= 32 and x <= 127: return chr(x) else: return '.' N = 0 result = "" while src: s, src = src[:length], src[length:] text_hexa = " ".join(["%02X" % x for x in s]) text_ascii = "".join(map(to_ascii , s)) result += "%04X %-*s %s\n" % (N, length * 3, text_hexa, text_ascii) N += length return result def usage(): print("Usage:", sys.argv[0], end=" ") print("[-a][--all]", end=" ") print("[-p pin][--pin=pin] (use --pin=NULL for pinpad)", end=" ") print("[-c lib][--lib=lib]", end=" ") print("[-s slot][--slot=slot]", end=" ") print("[-h][--help]", end=" ") print() try: opts, args = getopt.getopt( sys.argv[1:], "p:c:Sdhs:a", ["pin=", "lib=", "slot=", "help", "all"], ) except getopt.GetoptError: # print help information and exit: usage() sys.exit(2) pin_available = False lib = None slot = None token_present = True for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() elif o in ("-p", "--pin"): pin = a if pin == "NULL": pin = None pin_available = True elif o in ("-c", "--lib"): lib = a print("using PKCS11 lib:", lib) elif o in ("-s", "--slot"): slot = int(a) if o in ("-a", "--all"): token_present = False red = blue = magenta = normal = "" if sys.stdout.isatty() and platform.system().lower() != "windows": red = "\x1b[01;31m" blue = "\x1b[34m" magenta = "\x1b[35m" normal = "\x1b[0m" format_long = magenta + " %s:" + blue + " %s (%s)" + normal format_binary = magenta + " %s:" + blue + " %d bytes" + normal format_normal = magenta + " %s:" + blue + " %s" + normal pkcs11 = PyKCS11.PyKCS11Lib() pkcs11.load(lib) info = pkcs11.getInfo() print("Library manufacturerID:", info.manufacturerID) slots = pkcs11.getSlotList(token_present) print("Available Slots:", len(slots), slots) if slot is not None: slots = [slots[slot]] print("Using slot:", slots[0]) for s in slots: try: i = pkcs11.getSlotInfo(s) print("Slot no:", s) print(format_normal % ("slotDescription", i.slotDescription.strip())) print(format_normal % ("manufacturerID ", i.manufacturerID.strip())) print(format_normal % ("hardwareVersion", i.hardwareVersion)) print(format_normal % ("firmwareVersion", i.firmwareVersion)) print(format_normal % ("flags ", ", ".join(i.flags2text()))) if not (i.flags & PyKCS11.CKF_TOKEN_PRESENT): print(" Token not present") continue t = pkcs11.getTokenInfo(s) print("TokenInfo") print(format_normal % ("label", t.label.strip())) print(format_normal % ("manufacturerID", t.manufacturerID.strip())) print(format_normal % ("model", t.model.strip())) session = pkcs11.openSession(s) print("Opened session 0x%08X" % session.session.value()) if pin_available: try: if (pin is None) and ( PyKCS11.CKF_PROTECTED_AUTHENTICATION_PATH & t.flags ): print("\nEnter your PIN for %s on the pinpad" % t.label.strip()) session.login(pin=pin) except PyKCS11.PyKCS11Error as e: print("login failed, exception:", e) break objects = session.findObjects() print() print("Found %d objects: %s" % (len(objects), [x.value() for x in objects])) all_attributes = list(PyKCS11.CKA.keys()) # remove the CKR_ATTRIBUTE_SENSITIVE attributes since we can't get # their values and will get an exception instead all_attributes.remove(PyKCS11.CKA_PRIVATE_EXPONENT) all_attributes.remove(PyKCS11.CKA_PRIME_1) all_attributes.remove(PyKCS11.CKA_PRIME_2) all_attributes.remove(PyKCS11.CKA_EXPONENT_1) all_attributes.remove(PyKCS11.CKA_EXPONENT_2) all_attributes.remove(PyKCS11.CKA_COEFFICIENT) # only use the integer values and not the strings like 'CKM_RSA_PKCS' all_attributes = [e for e in all_attributes if isinstance(e, int)] n_obj = 1 for o in objects: print() print( ( red + "==================== Object: %d/%d (%d) ====================" + normal ) % (n_obj, len(objects), o.value()) ) n_obj += 1 try: attributes = session.getAttributeValue(o, all_attributes) except PyKCS11.PyKCS11Error as e: print("getAttributeValue failed:", e) continue attrDict = dict(list(zip(all_attributes, attributes))) print("Dumping attributes:") for q, a in zip(all_attributes, attributes): if a is None: # undefined (CKR_ATTRIBUTE_TYPE_INVALID) attribute continue if q == PyKCS11.CKA_CLASS: print(format_long % (PyKCS11.CKA[q], PyKCS11.CKO[a], a)) elif q == PyKCS11.CKA_CERTIFICATE_TYPE: print(format_long % (PyKCS11.CKA[q], PyKCS11.CKC[a], a)) elif q == PyKCS11.CKA_KEY_TYPE: print(format_long % (PyKCS11.CKA[q], PyKCS11.CKK[a], a)) elif session.isBin(q): print(format_binary % (PyKCS11.CKA[q], len(a))) if a: print(dump(a), end="") elif q == PyKCS11.CKA_SERIAL_NUMBER: print(format_binary % (PyKCS11.CKA[q], len(a))) if a: print(dump(a), end="") else: print(format_normal % (PyKCS11.CKA[q], a)) print() if pin_available: try: session.logout() except PyKCS11.PyKCS11Error as e: print("logout failed, exception:", e) break session.closeSession() except PyKCS11.PyKCS11Error as e: print("Error:", e) raise ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1636117005.0 pykcs11-1.5.17/samples/ec_generate.py0000755000076500000240000000444214141225015017152 0ustar00rousseaustaff#!/usr/bin/env python3 # Copyright (C) 2019 Atte Pellikka # # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. from PyKCS11 import * from asn1crypto.keys import ECDomainParameters, NamedCurve pkcs11 = PyKCS11.PyKCS11Lib() pkcs11.load() slot = pkcs11.getSlotList(tokenPresent=True)[0] session = pkcs11.openSession(slot, CKF_SERIAL_SESSION | CKF_RW_SESSION) session.login("1234") key_id = (0x22,) label = "test" # Select the curve to be used for the keys curve = u"secp256r1" # Setup the domain parameters, unicode conversion needed for the curve string domain_params = ECDomainParameters(name="named", value=NamedCurve(curve)) ec_params = domain_params.dump() ec_public_tmpl = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_PUBLIC_KEY), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_VERIFY, PyKCS11.CK_TRUE), (PyKCS11.CKA_WRAP, PyKCS11.CK_TRUE), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_ECDSA), (PyKCS11.CKA_EC_PARAMS, ec_params), (PyKCS11.CKA_LABEL, label), (PyKCS11.CKA_ID, key_id), ] ec_priv_tmpl = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_PRIVATE_KEY), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_ECDSA), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_SENSITIVE, PyKCS11.CK_TRUE), (PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_SIGN, PyKCS11.CK_TRUE), (PyKCS11.CKA_UNWRAP, PyKCS11.CK_TRUE), (PyKCS11.CKA_LABEL, label), (PyKCS11.CKA_ID, key_id), ] (pub_key, priv_key) = session.generateKeyPair( ec_public_tmpl, ec_priv_tmpl, mecha=PyKCS11.MechanismECGENERATEKEYPAIR ) session.logout() session.closeSession() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1636117007.0 pykcs11-1.5.17/samples/ec_signature.py0000755000076500000240000000360414141225017017362 0ustar00rousseaustaff#!/usr/bin/env python3 # Copyright (C) 2015 Roman Pasechnik # Copyright (C) 2018 Ludovic Rousseau # Copyright (C) 2019 Atte Pellikka # # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import print_function from PyKCS11 import * import binascii pkcs11 = PyKCS11Lib() pkcs11.load() # define environment variable PYKCS11LIB=YourPKCS11Lib # get 1st slot slot = pkcs11.getSlotList(tokenPresent=True)[0] session = pkcs11.openSession(slot, CKF_SERIAL_SESSION | CKF_RW_SESSION) session.login("1234") priv_search_tmpl = [(CKA_CLASS, CKO_PRIVATE_KEY), (CKA_KEY_TYPE, CKK_ECDSA)] pub_search_tmpl = [(CKA_CLASS, CKO_PUBLIC_KEY), (CKA_KEY_TYPE, CKK_ECDSA)] # "Hello world" in hex toSign = "48656c6c6f20776f726c640d0a" mechanism = Mechanism(CKM_ECDSA, None) # find first private key and compute signature privKey = session.findObjects(priv_search_tmpl)[0] signature = session.sign(privKey, binascii.unhexlify(toSign), mechanism) print("\nsignature: {}".format(binascii.hexlify(bytearray(signature)))) # find first public key and verify signature pubKey = session.findObjects(pub_search_tmpl)[0] result = session.verify(pubKey, binascii.unhexlify(toSign), signature, mechanism) print("\nVerified:", result) # logout session.logout() session.closeSession() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1636117010.0 pykcs11-1.5.17/samples/encrypt.py0000755000076500000240000000311414141225022016366 0ustar00rousseaustaff#!/usr/bin/env python3 # Copyright (C) 2015 Roman Pasechnik # # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import print_function from PyKCS11 import * import binascii pkcs11 = PyKCS11Lib() pkcs11.load() # define environment variable PYKCS11LIB=YourPKCS11Lib # get 1st slot slot = pkcs11.getSlotList(tokenPresent=True)[0] session = pkcs11.openSession(slot, CKF_SERIAL_SESSION | CKF_RW_SESSION) session.login("1234") # "Hello world" in hex message = "48656c6c6f20776f726c640d0a" # get first public and private keys pubKey = session.findObjects([(CKA_CLASS, CKO_PUBLIC_KEY)])[0] privKey = session.findObjects([(CKA_CLASS, CKO_PRIVATE_KEY)])[0] enc = session.encrypt(pubKey, binascii.unhexlify(message)) dec = session.decrypt(privKey, enc) print("\nmessage: " + message) print("\nencrypted: {}".format(binascii.hexlify(bytearray(enc)))) print("\ndecrypted: {}".format(bytearray(dec))) # logout session.logout() session.closeSession() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1636117012.0 pykcs11-1.5.17/samples/events.py0000755000076500000240000000535314141225024016217 0ustar00rousseaustaff#!/usr/bin/env python3 # Copyright (C) 2009-2014 Ludovic Rousseau (ludovic.rousseau@free.fr) # # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import print_function import PyKCS11 import getinfo if __name__ == "__main__": import getopt import sys def usage(): print("Usage:", sys.argv[0], end=" ") print("[-p pin][--pin=pin] (use 'NULL' for pinpad)", end=" ") print("[-c lib][--lib=lib]", end=" ") print("[-h][--help]", end=" ") print("[-o][--opensession]") print("[-f][--full]") try: opts, args = getopt.getopt( sys.argv[1:], "p:c:homf", ["pin=", "lib=", "help", "opensession", "mechanisms", "full"], ) except getopt.GetoptError: # print help information and exit: usage() sys.exit(2) lib = None pin = "" open_session = False pin_available = False list_mechanisms = False full = False for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() if o in ("-p", "--pin"): pin = a if pin == "NULL": pin = None pin_available = True open_session = True if o in ("-c", "--lib"): lib = a if o in ("-o", "--opensession"): open_session = True if o in ("-m", "--mechanisms"): list_mechanisms = True if o in ("-f", "--full"): full = True gi = getinfo.getInfo(lib) gi.getInfo() slots = gi.pkcs11.getSlotList() print("Available Slots:", len(slots), slots) if len(slots) == 0: sys.exit(2) while True: print("waiting...") slot = gi.pkcs11.waitForSlotEvent() try: print("Slot %d changed" % slot) gi.getSlotInfo(slot, 0, len(slots)) if full: gi.getSessionInfo(slot, pin) gi.getTokenInfo(slot) if list_mechanisms: gi.getMechanismInfo(slot) except PyKCS11.PyKCS11Error as e: print("Error:", e) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1636117014.0 pykcs11-1.5.17/samples/generate.py0000755000076500000240000000344314141225026016505 0ustar00rousseaustaff#!/usr/bin/env python3 # Copyright (C) 2015 Roman Pasechnik # # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. from PyKCS11 import * # the key_id has to be the same for both objects key_id = (0x22,) pkcs11 = PyKCS11Lib() pkcs11.load() # define environment variable PYKCS11LIB=YourPKCS11Lib # get 1st slot slot = pkcs11.getSlotList(tokenPresent=True)[0] session = pkcs11.openSession(slot, CKF_SERIAL_SESSION | CKF_RW_SESSION) session.login("1234") pubTemplate = [ (CKA_CLASS, CKO_PUBLIC_KEY), (CKA_TOKEN, CK_TRUE), (CKA_PRIVATE, CK_FALSE), (CKA_MODULUS_BITS, 0x0400), (CKA_PUBLIC_EXPONENT, (0x01, 0x00, 0x01)), (CKA_ENCRYPT, CK_TRUE), (CKA_VERIFY, CK_TRUE), (CKA_VERIFY_RECOVER, CK_TRUE), (CKA_WRAP, CK_TRUE), (CKA_LABEL, "My Public Key"), (CKA_ID, key_id), ] privTemplate = [ (CKA_CLASS, CKO_PRIVATE_KEY), (CKA_TOKEN, CK_TRUE), (CKA_PRIVATE, CK_TRUE), (CKA_DECRYPT, CK_TRUE), (CKA_SIGN, CK_TRUE), (CKA_SIGN_RECOVER, CK_TRUE), (CKA_UNWRAP, CK_TRUE), (CKA_ID, key_id), ] (pubKey, privKey) = session.generateKeyPair(pubTemplate, privTemplate) # logout session.logout() session.closeSession() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1677074631.0 pykcs11-1.5.17/samples/genkeypair_import_cert.py0000755000076500000240000001112514375420307021464 0ustar00rousseaustaff#!/usr/bin/env python3 # contributed by Alex Railean, a dot railean at dekart.com # # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. from PyKCS11 import * pkcs11 = PyKCS11Lib() pkcs11.load() # define environment variable PYKCS11LIB=YourPKCS11Lib slot = pkcs11.getSlotList(tokenPresent=True)[0] session = pkcs11.openSession(slot, PyKCS11.CKF_RW_SESSION) pin = "1234" session.login(pin, PyKCS11.CKU_USER) # ############ key-pair generation ########################## # The first step in the process is to create the key-templates. See PKCS#11 # `10.8 Public key objects` to learn which attributes are available. Section # 10.9 covers private keys. label = "pkcs_is_fun" # just a label for identifying objects key_length = 2048 # key-length in bits # the key_id has to be the same for both objects, it will also be necessary # when importing the certificate, to ensure it is linked with these keys. key_id = (0x01,) public_template = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_PUBLIC_KEY), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_VERIFY, PyKCS11.CK_TRUE), (PyKCS11.CKA_WRAP, PyKCS11.CK_TRUE), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_RSA), (PyKCS11.CKA_VERIFY_RECOVER, PyKCS11.CK_TRUE), (PyKCS11.CKA_LABEL, label), (PyKCS11.CKA_MODULUS_BITS, key_length), (PyKCS11.CKA_ID, key_id), ] private_template = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_PRIVATE_KEY), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_TRUE), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_SENSITIVE, PyKCS11.CK_TRUE), (PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_SIGN, PyKCS11.CK_TRUE), (PyKCS11.CKA_UNWRAP, PyKCS11.CK_TRUE), (PyKCS11.CKA_LABEL, label), (PyKCS11.CKA_ID, key_id), ] session.generateKeyPair(public_template, private_template) # ############# the keys were generated and stored on the card ############### # At this point your keys are in the card, the private key is marked as # non-exportable. # To add a certificate, you have to prepare a CSR in PKCS#10 format and sign # it with the key. # It can be done with OpenSSL by typing the commands below in a terminal # 1. openssl # 2. engine dynamic -pre SO_PATH:/usr/lib/engines/engine_pkcs11.so -pre ID:pkcs11 -pre LIST_ADD:1 -pre LOAD -pre MODULE_PATH:libacospkcs11.so # 3. req -engine pkcs11 -keyform engine -key 0:1 -new -text -out /tmp/newcert.csr -subj "/O=users/CN=Test User" # Note that `-key 0:1` means "use slot 0, with key id 1" # The CSR will be printed to stdout and saved to /tmp/newcert.csr # The CSR is sent to a CA, which will issue a certificate and send it back. # Once you have the certificate, it has to be converted to BER (if it isn't # already). It will be assumed that the raw data of the certificate are in # `cert`. cert = b"replace this with the raw certificate itself" subject = b"foobar" # keep in mind that certain elements, such as the subject, must not be # passed as a string, but as an ASN1-encoded structure. Consider using # pyasn1 to do that, see http://pyasn1.sourceforge.net/ cert_template = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_CERTIFICATE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE), (PyKCS11.CKA_LABEL, label), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_CERTIFICATE_TYPE, PyKCS11.CKC_X_509), (PyKCS11.CKA_MODIFIABLE, PyKCS11.CK_TRUE), (PyKCS11.CKA_VALUE, cert), # must be BER-encoded ( PyKCS11.CKA_SUBJECT, subject, ), # must be set and DER, see Table 24, X.509 Certificate Object Attributes ( PyKCS11.CKA_ID, key_id, ), # must be set, and DER see Table 24, X.509 Certificate Object Attributes ] # create the certificate object session.createObject(cert_template) # logout session.logout() session.closeSession() # At this point the certificate is on the card too. Some GUI tools # might display it as invalid, in that case make sure that the # entire certificate chain is available in the certificate store. ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1636117034.0 pykcs11-1.5.17/samples/getinfo.py0000755000076500000240000001214114141225052016340 0ustar00rousseaustaff#!/usr/bin/env python3 # Copyright (C) 2006-2014 Ludovic Rousseau (ludovic.rousseau@free.fr) # # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import print_function import PyKCS11 import platform import sys class getInfo(object): red = blue = magenta = normal = "" def colorize(self, text, arg): print(self.magenta + text + self.blue, arg, self.normal) def display(self, obj, indent=""): dico = obj.to_dict() for key in sorted(dico.keys()): type = obj.fields[key] left = indent + key + ":" if type == "flags": self.colorize(left, ", ".join(dico[key])) elif type == "pair": self.colorize(left, "%d.%d" % dico[key]) else: self.colorize(left, dico[key]) def __init__(self, lib=None): if sys.stdout.isatty() and platform.system().lower() != "windows": self.red = "\x1b[01;31m" self.blue = "\x1b[34m" self.magenta = "\x1b[35m" self.normal = "\x1b[0m" self.pkcs11 = PyKCS11.PyKCS11Lib() self.pkcs11.load(lib) def getSlotInfo(self, slot, slot_index, nb_slots): print() print( self.red + "Slot %d/%d (number %d):" % (slot_index, nb_slots, slot) + self.normal ) self.display(self.pkcs11.getSlotInfo(slot), " ") def getTokenInfo(self, slot): print(" TokenInfo") self.display(self.pkcs11.getTokenInfo(slot), " ") def getMechanismInfo(self, slot): print(" Mechanism list: ") m = self.pkcs11.getMechanismList(slot) for x in m: self.colorize(" ", x) i = self.pkcs11.getMechanismInfo(slot, x) if not i.flags & PyKCS11.CKF_DIGEST: if i.ulMinKeySize != PyKCS11.CK_UNAVAILABLE_INFORMATION: self.colorize(" ulMinKeySize:", i.ulMinKeySize) if i.ulMaxKeySize != PyKCS11.CK_UNAVAILABLE_INFORMATION: self.colorize(" ulMaxKeySize:", i.ulMaxKeySize) self.colorize(" flags:", ", ".join(i.flags2text())) def getInfo(self): self.display(self.pkcs11.getInfo()) def getSessionInfo(self, slot, pin=""): print(" SessionInfo", end=" ") session = self.pkcs11.openSession(slot) if pin != "": if pin is None: print("(using pinpad)") else: print("(using pin: %s)" % pin) session.login(pin) else: print() self.display(session.getSessionInfo(), " ") if pin: session.logout() def usage(): print("Usage:", sys.argv[0], end=" ") print("[-a][--all]", end=" ") print("[-p pin][--pin=pin] (use 'NULL' for pinpad)", end=" ") print("[-s slot][--slot=slot]", end=" ") print("[-c lib][--lib=lib]", end=" ") print("[-m][--mechanisms]", end=" ") print("[-h][--help]") if __name__ == "__main__": import getopt try: opts, args = getopt.getopt( sys.argv[1:], "p:s:c:ham", ["pin=", "slot=", "lib=", "help", "all", "mechanisms"], ) except getopt.GetoptError: # print help information and exit: usage() sys.exit(2) slot = None lib = None pin = "" token_present = True list_mechanisms = False for o, a in opts: if o in ("-h", "--help"): usage() sys.exit() if o in ("-p", "--pin"): pin = a if pin == "NULL": pin = None if o in ("-s", "--slot"): slot = int(a) if o in ("-c", "--lib"): lib = a if o in ("-a", "--all"): token_present = False if o in ("-m", "--mechanisms"): list_mechanisms = True gi = getInfo(lib) gi.getInfo() slots = gi.pkcs11.getSlotList(token_present) print("Available Slots:", len(slots), slots) if len(slots) == 0: sys.exit(2) if slot is not None: slots = [slots[slot]] print("Using slot:", slots[0]) slot_index = 0 nb_slots = len(slots) for slot in slots: slot_index += 1 try: gi.getSlotInfo(slot, slot_index, nb_slots) gi.getSessionInfo(slot, pin) gi.getTokenInfo(slot) if list_mechanisms: gi.getMechanismInfo(slot) except PyKCS11.PyKCS11Error as e: print("Error:", e) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1636117036.0 pykcs11-1.5.17/samples/modulus.py0000755000076500000240000000267414141225054016411 0ustar00rousseaustaff#!/usr/bin/env python3 # Copyright (C) 2015 Roman Pasechnik # # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import print_function from PyKCS11 import * import binascii pkcs11 = PyKCS11Lib() pkcs11.load() # define environment variable PYKCS11LIB=YourPKCS11Lib # get 1st slot slot = pkcs11.getSlotList(tokenPresent=True)[0] session = pkcs11.openSession(slot, CKF_SERIAL_SESSION | CKF_RW_SESSION) session.login("1234") # key ID in hex (has to be tuple, that's why trailing comma) keyID = (0x22,) # find public key and print modulus pubKey = session.findObjects([(CKA_CLASS, CKO_PUBLIC_KEY), (CKA_ID, keyID)])[0] modulus = session.getAttributeValue(pubKey, [CKA_MODULUS])[0] print("\nmodulus: {}".format(binascii.hexlify(bytearray(modulus)))) # logout session.logout() session.closeSession() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1636117038.0 pykcs11-1.5.17/samples/rsa_encrypt.py0000755000076500000240000000375014141225056017250 0ustar00rousseaustaff#!/usr/bin/env python3 # Copyright (C) 2015 Roman Pasechnik # # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. from PyKCS11 import * pkcs11 = PyKCS11Lib() pkcs11.load() # define environment variable PYKCS11LIB=YourPKCS11Lib # get 1st slot slot = pkcs11.getSlotList(tokenPresent=True)[0] session = pkcs11.openSession(slot, CKF_SERIAL_SESSION | CKF_RW_SESSION) session.login("1234") pubTemplate = [ (CKA_CLASS, CKO_PUBLIC_KEY), (CKA_TOKEN, CK_TRUE), (CKA_PRIVATE, CK_FALSE), (CKA_MODULUS_BITS, 2048), (CKA_PUBLIC_EXPONENT, (0x01, 0x00, 0x01)), (CKA_ENCRYPT, CK_TRUE), (CKA_VERIFY, CK_TRUE), (CKA_VERIFY_RECOVER, CK_TRUE), (CKA_WRAP, CK_TRUE), (CKA_LABEL, "Encryption key"), (CKA_ID, (0x43,)), ] privTemplate = [ (CKA_CLASS, CKO_PRIVATE_KEY), (CKA_TOKEN, CK_TRUE), (CKA_PRIVATE, CK_TRUE), (CKA_DECRYPT, CK_TRUE), (CKA_SIGN, CK_TRUE), (CKA_SIGN_RECOVER, CK_TRUE), (CKA_UNWRAP, CK_TRUE), (CKA_ID, (0x43,)), ] (pubKey, privKey) = session.generateKeyPair(pubTemplate, privTemplate) PLAINTEXT = "A test string" mech = RSAOAEPMechanism(CKM_SHA_1, CKG_MGF1_SHA1) ciphertext = session.encrypt(pubKey, PLAINTEXT, mech) decrypted = "".join([chr(i) for i in session.decrypt(privKey, ciphertext, mech)]) assert decrypted == PLAINTEXT session.logout() session.closeSession() print("That's all folks!") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1698503960.0 pykcs11-1.5.17/samples/signature.py0000755000076500000240000000321214517216430016714 0ustar00rousseaustaff#!/usr/bin/env python3 # Copyright (C) 2015 Roman Pasechnik # Copyright (C) 2018 Ludovic Rousseau # # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. from PyKCS11 import * import binascii pkcs11 = PyKCS11Lib() pkcs11.load() # define environment variable PYKCS11LIB=YourPKCS11Lib # get 1st slot slot = pkcs11.getSlotList(tokenPresent=True)[0] session = pkcs11.openSession(slot, CKF_SERIAL_SESSION | CKF_RW_SESSION) session.login("1234") # message to sign toSign = "Hello World!" mechanism = Mechanism(CKM_SHA256_RSA_PKCS, None) # find first private key and compute signature privKey = session.findObjects([(CKA_CLASS, CKO_PRIVATE_KEY)])[0] signature = session.sign(privKey, toSign, mechanism) print("\nsignature: {}".format(binascii.hexlify(bytearray(signature)))) # find first public key and verify signature pubKey = session.findObjects([(CKA_CLASS, CKO_PUBLIC_KEY)])[0] result = session.verify(pubKey, toSign, signature, mechanism) print("\nVerified:", result) # logout session.logout() session.closeSession() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1636117043.0 pykcs11-1.5.17/samples/unblock.py0000755000076500000240000000214614141225063016350 0ustar00rousseaustaff#!/usr/bin/env python3 # Copyright (C) 2006-2014 Ludovic Rousseau # # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program 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 # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. from __future__ import print_function import PyKCS11 pin = "1234" puk = "1234" pkcs11 = PyKCS11.PyKCS11Lib() pkcs11.load() slot = pkcs11.getSlotList(tokenPresent=True)[0] session = pkcs11.openSession(slot, PyKCS11.CKF_RW_SESSION) session.login(puk, PyKCS11.CKU_SO) session.initPin(pin) session.logout() session.closeSession() ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1729078230.139816 pykcs11-1.5.17/setup.cfg0000644000076500000240000000004614703721726014523 0ustar00rousseaustaff[egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1729077608.0 pykcs11-1.5.17/setup.py0000644000076500000240000000630214703720550014407 0ustar00rousseaustafffrom setuptools import setup, Extension from setuptools.command.build_py import build_py import shutil from sys import version_info as pyver from os import path import platform from shutil import which description = """A complete PKCS#11 wrapper for Python. You can use any PKCS#11 (aka CryptoKi) module such as the PSM which comes as part of mozilla or the various modules supplied by vendors of hardware crypto tokens, and almost all PKCS#11 functions and data types. The wrapper has been generated with the help of the SWIG compiler.""" classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: GNU General Public License (GPL)", "Natural Language :: English", "Operating System :: Microsoft :: Windows", "Operating System :: OS Independent", "Operating System :: Unix", "Programming Language :: C", "Programming Language :: C++", "Programming Language :: Python", "Topic :: Security :: Cryptography", "Topic :: Software Development :: Libraries :: Python Modules", ] lib_dirs = [] inc_dirs = ["src"] # some OS, such as FreeBSD, uses /usr/local folders if path.exists("/usr/local"): lib_dirs.append("/usr/local/lib") inc_dirs.append("/usr/local/include") source_files = [ "src/ck_attribute_smart.cpp", "src/pkcs11lib.cpp", "src/pykcs11string.cpp", "src/utility.cpp", "src/pykcs11.i", "src/pykcs11.cpp", ] define_macros = [] extra_compile_args = [] extra_link_args = [] if platform.system().lower() == "windows": source_files.append("src/dyn_win32.c") libraries_val = ["python%d%d" % pyver[:2]] extra_compile_args = ["/Fdvc70.pdb", "/Zi", "/GR", "/EHsc"] extra_link_args = [ "/DEBUG", "/PDB:_LowLevel.pdb", "/SUBSYSTEM:WINDOWS", "/OPT:REF", "/OPT:ICF", ] else: source_files.append("src/dyn_unix.c") libraries_val = [] class MyBuild(build_py): def run(self): if which("swig") is None: print("Install swig and try again") print("") exit(1) self.run_command("build_ext") shutil.copy("src/LowLevel.py", "PyKCS11") build_py.run(self) setup( name="PyKCS11", version="1.5.17", description="A Full PKCS#11 wrapper for Python", keywords="crypto,pki,pkcs11,c++", classifiers=classifiers, platforms="Win32 Unix", long_description=description, author="Giuseppe Amato (Midori)", author_email="paipai@tiscali.it", maintainer="Ludovic Rousseau", maintainer_email="ludovic.rousseau@free.fr", url="https://github.com/LudovicRousseau/PyKCS11", download_url="http://sourceforge.net/projects/pkcs11wrap/files/pykcs11/", license="GPL", cmdclass={"build_py": MyBuild}, ext_modules=[ Extension( name="PyKCS11._LowLevel", sources=source_files, include_dirs=inc_dirs, library_dirs=lib_dirs, libraries=libraries_val, define_macros=define_macros, swig_opts=["-c++"], extra_compile_args=extra_compile_args, extra_link_args=extra_link_args, ) ], py_modules=["PyKCS11.__init__", "PyKCS11.LowLevel"], ) ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1729078230.126035 pykcs11-1.5.17/src/0000755000076500000240000000000014703721726013471 5ustar00rousseaustaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1722545834.0 pykcs11-1.5.17/src/.DS_Store0000644000076500000240000002000414652773252015154 0ustar00rousseaustaffBud1 ttribu  @€ @€ @€ @ck_attribute_smart.cppIlocblob9(ÿÿÿÿÿÿck_attribute_smart.hIlocblob£(ÿÿÿÿÿÿ dyn_generic.hIlocblob (ÿÿÿÿÿÿ dyn_unix.cIlocblobw(ÿÿÿÿÿÿ dyn_win32.cIlocblobá(ÿÿÿÿÿÿ LowLevel.pyIlocblobK(ÿÿÿÿÿÿopenscIlocblobµ(ÿÿÿÿÿÿopenscbwspblobËbplist00×  ]ShowStatusBar[ShowPathbar[ShowToolbar[ShowTabView_ContainerShowSidebar\WindowBounds[ShowSidebar  _{{1049, 357}, {1023, 917}} %1=I`myz{|}~›œopenscfdscboolopenscvSrnlong pkcs11lib.cppIlocblob9˜ÿÿÿÿÿÿ pkcs11lib.hIlocblob£˜ÿÿÿÿÿÿ pykcs11.cppIlocblobw˜ÿÿÿÿÿÿ pykcs11.iIlocblobK˜ÿÿÿÿÿÿpykcs11_wrap.cppIlocblob ˜ÿÿÿÿÿÿpykcs11string.cppIlocblobµ˜ÿÿÿÿÿÿpykcs11string.hIlocblob9ÿÿÿÿÿÿstdafx.hIlocblob ÿÿÿÿÿÿ utility.cppIlocblobwÿÿÿÿÿÿ utility.hIlocblobáÿÿÿÿÿÿ E DSDB `€ @€ @€ @././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1716554236.0 pykcs11-1.5.17/src/ck_attribute_smart.cpp0000644000076500000240000001332514624104774020067 0ustar00rousseaustaff// Copyright (C) 2004 Midori (midori -- a-t -- paipai dot net) // // This file is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program 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 // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. #include "stdafx.h" #include "pykcs11string.h" #include "ck_attribute_smart.h" #include "pkcs11lib.h" #include "utility.h" #include #include CK_ATTRIBUTE_SMART::CK_ATTRIBUTE_SMART(CK_ULONG type, const CK_BYTE* pValue, CK_ULONG len) { this->m_type = type; CK_ULONG i; if (pValue) { m_value.reserve(len); m_value.clear(); for (i=0; i(len); } CK_ATTRIBUTE_SMART::CK_ATTRIBUTE_SMART(const CK_ATTRIBUTE_SMART & val) { vector::const_iterator it; for (it = val.m_value.begin(); it != val.m_value.end(); it++) m_value.push_back(*it); m_type = val.m_type; } CK_ATTRIBUTE_SMART& CK_ATTRIBUTE_SMART::operator=(const CK_ATTRIBUTE_SMART & val) { m_value = val.m_value; m_type = val.m_type; return *this; } CK_ATTRIBUTE_SMART::CK_ATTRIBUTE_SMART() { m_value.reserve(1024); } CK_ATTRIBUTE_SMART::~CK_ATTRIBUTE_SMART() { Reset(); } CK_ULONG CK_ATTRIBUTE_SMART::GetType() const { return m_type; } void CK_ATTRIBUTE_SMART::SetType(CK_ULONG attrType) { m_type = attrType; } int CK_ATTRIBUTE_SMART::GetLen() const { return (int)m_value.size(); } bool CK_ATTRIBUTE_SMART::IsString() const { switch(m_type) { case CKA_LABEL: case CKA_APPLICATION: return true; default: return false; } } bool CK_ATTRIBUTE_SMART::IsBool() const { switch(m_type) { case CKA_ALWAYS_AUTHENTICATE: case CKA_ALWAYS_SENSITIVE: case CKA_DECRYPT: case CKA_DERIVE: case CKA_ENCRYPT: case CKA_EXTRACTABLE: case CKA_HAS_RESET: case CKA_LOCAL: case CKA_MODIFIABLE: case CKA_COPYABLE: case CKA_DESTROYABLE: case CKA_NEVER_EXTRACTABLE: case CKA_PRIVATE: case CKA_RESET_ON_INIT: case CKA_SECONDARY_AUTH: case CKA_SENSITIVE: case CKA_SIGN: case CKA_SIGN_RECOVER: case CKA_TOKEN: case CKA_TRUSTED: case CKA_UNWRAP: case CKA_VERIFY: case CKA_VERIFY_RECOVER: case CKA_WRAP: case CKA_WRAP_WITH_TRUSTED: return true; default: return false; } } bool CK_ATTRIBUTE_SMART::IsNum() const { switch(m_type) { case CKA_CERTIFICATE_TYPE: case CKA_CLASS: case CKA_KEY_GEN_MECHANISM: case CKA_KEY_TYPE: case CKA_MODULUS_BITS: case CKA_VALUE_BITS: case CKA_VALUE_LEN: return true; default: return false; } } bool CK_ATTRIBUTE_SMART::IsAttributeList() const { switch(m_type) { case CKA_WRAP_TEMPLATE: case CKA_UNWRAP_TEMPLATE: return true; default: return false; } } bool CK_ATTRIBUTE_SMART::IsBin() const { return !IsBool() && !IsString() && !IsNum() && !IsAttributeList(); } void CK_ATTRIBUTE_SMART::Reset() { m_value.clear(); m_value.reserve(1024); m_type = 0; } void CK_ATTRIBUTE_SMART::ResetValue() { m_value.clear(); m_value.reserve(1024); } void CK_ATTRIBUTE_SMART::Reserve(long len) { m_value = vector(len); } PyKCS11String CK_ATTRIBUTE_SMART::GetString() const { return PyKCS11String(m_value); } void CK_ATTRIBUTE_SMART::SetString(CK_ULONG attrType, const char* szValue) { Reset(); m_type = attrType; if (szValue && strlen(szValue)) { size_t i; size_t iLen = strlen(szValue); for (i=0; i< iLen; i++) m_value.push_back((unsigned char)szValue[i]); } } long CK_ATTRIBUTE_SMART::GetNum() const { if (!IsNum() || m_value.size() != sizeof(CK_ULONG)) return 0; else { CK_ULONG i; CK_ULONG ulRes = 0; unsigned char* pVal = (unsigned char*)&ulRes; for (i=0; i& val) { Reset(); m_type = attrType; vector RWcopy = val; CK_ULONG ulCount = 0; CK_ATTRIBUTE * pTemplate = AttrVector2Template(RWcopy, ulCount); if (pTemplate) { const CK_BYTE* tmp2 = (const CK_BYTE*)pTemplate; CK_ULONG i; m_value.reserve(ulCount); m_value.reserve(ulCount * sizeof(CK_ATTRIBUTE)); m_value.clear(); for (i=0; i& CK_ATTRIBUTE_SMART::GetBin() { return m_value; } void CK_ATTRIBUTE_SMART::SetBin(unsigned long attrType, const vector& pBuf) { Reset(); m_value = pBuf; m_type = attrType; } ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1555513192.0 pykcs11-1.5.17/src/ck_attribute_smart.h0000644000076500000240000000370113455637550017535 0ustar00rousseaustaff// Copyright (C) 2004 Midori (midori -- a-t -- paipai dot net) // // This file is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program 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 // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. #pragma once #include "pykcs11string.h" #include using namespace std; class CK_ATTRIBUTE_SMART { CK_ATTRIBUTE_TYPE m_type; vector m_value; public: CK_ATTRIBUTE_SMART(unsigned long type, const unsigned char* pValue, unsigned long len); CK_ATTRIBUTE_SMART(const CK_ATTRIBUTE_SMART & val); CK_ATTRIBUTE_SMART& operator=(const CK_ATTRIBUTE_SMART & val); CK_ATTRIBUTE_SMART(); ~CK_ATTRIBUTE_SMART(); void Reset(); void ResetValue(); void Reserve(long len); unsigned long GetType() const; void SetType(unsigned long attrType); int GetLen() const; bool IsString() const; bool IsBool() const; bool IsNum() const; bool IsAttributeList() const; bool IsBin() const; // returns the value as SWIG "cdata.i"'s struct PyKCS11String GetString() const; void SetString(unsigned long attrType, const char* szValue); long GetNum() const; void SetNum(unsigned long attrType, unsigned long ulValue); bool GetBool() const; void SetBool(unsigned long attrType, bool bValue); void SetList(unsigned long attrType, const vector& val); vector& GetBin(); void SetBin(unsigned long attrType, const vector& pBuf); }; ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1704624376.0 pykcs11-1.5.17/src/dyn_generic.h0000644000076500000240000000423614546500370016130 0ustar00rousseaustaff/* * This abstracts dynamic library loading functions. * * MUSCLE SmartCard Development ( http://www.linuxnet.com ) * * Copyright (C) 1999 * David Corcoran * * $Id: dyn_generic.h,v 1.3 2003/10/18 17:19:36 aet-guest Exp $ */ #ifndef __dyn_generic_h__ #define __dyn_generic_h__ /** * @file * @brief load dynamic libraries * * @code * #include "dyn_generic.h" * * #ifdef WIN32 * #define LIBRARY_NAME "foobar.dll" * #else * #define LIBRARY_NAME "foobar.so" * #endif * * void *handle; * void (*p)(int, int); * * SYS_dyn_LoadLibrary(&handle, LIBRARY_NAME); * if (NULL == handle) * { * printf("Can't open %s", LIBRARY_NAME); * return -1; * } * * // we need a cast since function_ptr is of type "void (*)(void)" * // and p is of type "void (*)(int, int)" * SYS_dyn_GetAddress(handle, (function_ptr*)&p, FUNCTION_NAME); * * // we close now to not forget it after testing p value * SYS_dyn_CloseLibrary(&handle); * * if (NULL == p) * { * printf("function %s not found", FUNCTION_NAME); * return -1; * } * * // call the function * p(1, 2); * @endcode */ #ifdef __cplusplus extern "C" { #endif typedef void (*function_ptr)(void); /** * dynamically loads a library * @param handle returned handle * @param library_name library file name * @retval 0 if OK * @retval -1 on error and *pvLHandle is set to NULL */ int SYS_dyn_LoadLibrary(void **handle, const char *library_name); /** * close/unload a dynamically loaded library * @param handle handle returned by SYS_dyn_LoadLibrary() * @retval 0 if OK * @retval -1 on error * * Side effect: *pvLHandle is set to NULL */ int SYS_dyn_CloseLibrary(void **handle); /** * get the adsress of a function from a dynamicall loaded library * @param handle handle returned by SYS_dyn_LoadLibrary() * @param function_ptr address to store the function address * @param function_name function name * @retval 0 if OK * @retval -1 on error and pvFHandle is set to NULL */ int SYS_dyn_GetAddress(void *handle, function_ptr *function_ptr, const char *function_name); #ifdef __cplusplus } #endif #endif ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1548190164.0 pykcs11-1.5.17/src/dyn_unix.c0000644000076500000240000000342713421700724015467 0ustar00rousseaustaff/* * This abstracts dynamic library loading functions and timing. * * MUSCLE SmartCard Development ( http://www.linuxnet.com ) * * Copyright (C) 1999 * David Corcoran * Copyright (C) 2004-2009 * Ludovic Rousseau * * $Id: dyn_unix.c,v 1.13 2005/02/22 14:40:26 rousseau Exp $ */ //#include "config.h" #define HAVE_DLFCN_H #include #include #if defined(HAVE_DLFCN_H) && !defined(HAVE_DL_H) #include #include #include "dyn_generic.h" #define Log2(a, b) printf("%s:%d:%s() " a "\n", __FILE__, __LINE__, __FUNCTION__, b); #define Log3(a, b, c) printf("%s:%d:%s() " a "\n", __FILE__, __LINE__, __FUNCTION__, b, c); int SYS_dyn_LoadLibrary(void **handle, const char *library_name) { *handle = NULL; *handle = dlopen(library_name, RTLD_NOW); if (*handle == NULL) { Log2("%s", dlerror()); return -1; } return 0; } /* SYS_dyn_LoadLibrary */ int SYS_dyn_CloseLibrary(void **handle) { int ret; ret = dlclose(*handle); *handle = NULL; if (ret) { Log2("%s", dlerror()); return -1; } return 0; } /* SYS_dyn_CloseLibrary */ int SYS_dyn_GetAddress(void *handle, function_ptr *func_ptr, const char *function_name) { char new_function_name[256]; int rv; /* Some platforms might need a leading underscore for the symbol */ snprintf(new_function_name, sizeof(new_function_name), "_%s", function_name); *func_ptr = NULL; *func_ptr = dlsym(handle, new_function_name); /* Failed? Try again without the leading underscore */ if (*func_ptr == NULL) *func_ptr = dlsym(handle, function_name); if (*func_ptr == NULL) { Log3("%s: %s", function_name, dlerror()); rv = -1; } else rv = 0; return rv; } /* SYS_dyn_GetAddress */ #endif /* HAVE_DLFCN_H && !HAVE_DL_H && !__APPLE__ */ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1548190635.0 pykcs11-1.5.17/src/dyn_win32.c0000644000076500000240000000404113421701653015441 0ustar00rousseaustaff/* * MUSCLE SmartCard Development ( http://www.linuxnet.com ) * * Copyright (C) 1999 * David Corcoran * * $Id: dyn_win32.c 1957 2006-03-21 13:59:18Z rousseau $ */ /** * @file * @brief This abstracts dynamic library loading functions and timing. */ #if defined(WIN32) || defined(_WIN32) #include #include "windows.h" #include #include #include "dyn_generic.h" /* copy from https://docs.microsoft.com/fr-fr/windows/desktop/Debug/retrieving-the-last-error-code */ static void DisplayError(LPTSTR lpszFunction) { // Retrieve the system error message for the last-error code LPTSTR lpMsgBuf; DWORD dw = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); // Display the error message printf("%s failed with error %d: %s\n", lpszFunction, dw, lpMsgBuf); LocalFree(lpMsgBuf); } int SYS_dyn_LoadLibrary(void **pvLHandle, const char *pcLibrary) { *pvLHandle = NULL; *pvLHandle = LoadLibrary(pcLibrary); if (*pvLHandle == NULL) { DisplayError("LoadLibrary()"); return -1; } return 0; } int SYS_dyn_CloseLibrary(void **pvLHandle) { int ret; ret = FreeLibrary(*pvLHandle); *pvLHandle = NULL; /* If the function fails, the return value is zero. To get extended error * information, call GetLastError. */ if (ret == 0) { DisplayError("FreeLibrary()"); return -1; } return 0; } int SYS_dyn_GetAddress(void *pvLHandle, function_ptr *pvFHandle, const char *pcFunction) { int rv; const char *pcFunctionName; /* * Zero out everything */ rv = 0; pcFunctionName = NULL; pcFunctionName = pcFunction; *pvFHandle = NULL; *pvFHandle = (function_ptr)GetProcAddress(pvLHandle, pcFunctionName); if (*pvFHandle == NULL) { DisplayError("GetProcAddress()"); rv = -1; } else rv = 0; return rv; } #endif /* WIN32 */ ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1729078230.1270292 pykcs11-1.5.17/src/opensc/0000755000076500000240000000000014703721726014760 5ustar00rousseaustaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1589546674.0 pykcs11-1.5.17/src/opensc/.DS_Store0000644000076500000240000001400413657507262016446 0ustar00rousseaustaffBud1†11.hIlocpkcs11.hIlocblob (ÿÿÿÿÿÿ  @€ @€ @€ @ E†DSDB `À @€ @€ @././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1723063758.0 pykcs11-1.5.17/src/opensc/pkcs11.h0000644000076500000240000013145614654756716016261 0ustar00rousseaustaff/* pkcs11.h Copyright 2006, 2007 g10 Code GmbH Copyright 2006 Andreas Jellinghaus This file is free software; as a special exception the author gives unlimited permission to copy and/or distribute it, with or without modifications, as long as this notice is preserved. This file is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, to the extent permitted by law; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ /* Please submit changes back to the Scute project at http://www.scute.org/ (or send them to marcus@g10code.com), so that they can be picked up by other projects from there as well. */ /* This file is a modified implementation of the PKCS #11 standard by RSA Security Inc. It is mostly a drop-in replacement, with the following change: This header file does not require any macro definitions by the user (like CK_DEFINE_FUNCTION etc). In fact, it defines those macros for you (if useful, some are missing, let me know if you need more). There is an additional API available that does comply better to the GNU coding standard. It can be switched on by defining CRYPTOKI_GNU before including this header file. For this, the following changes are made to the specification: All structure types are changed to a "struct ck_foo" where CK_FOO is the type name in PKCS #11. All non-structure types are changed to ck_foo_t where CK_FOO is the lowercase version of the type name in PKCS #11. The basic types (CK_ULONG et al.) are removed without substitute. All members of structures are modified in the following way: Type indication prefixes are removed, and underscore characters are inserted before words. Then the result is lowercased. Note that function names are still in the original case, as they need for ABI compatibility. CK_FALSE, CK_TRUE and NULL_PTR are removed without substitute. Use . If CRYPTOKI_COMPAT is defined before including this header file, then none of the API changes above take place, and the API is the one defined by the PKCS #11 standard. */ #ifndef PKCS11_H #define PKCS11_H 1 #if defined(__cplusplus) extern "C" { #endif /* The version of cryptoki we implement. The revision is changed with each modification of this file. If you do not use the "official" version of this file, please consider deleting the revision macro (you may use a macro with a different name to keep track of your versions). */ #define CRYPTOKI_VERSION_MAJOR 2 #define CRYPTOKI_VERSION_MINOR 20 #define CRYPTOKI_VERSION_REVISION 6 /* Compatibility interface is default, unless CRYPTOKI_GNU is given. */ #ifndef CRYPTOKI_GNU #ifndef CRYPTOKI_COMPAT #define CRYPTOKI_COMPAT 1 #endif #endif /* System dependencies. */ #if defined(_WIN32) || defined(CRYPTOKI_FORCE_WIN32) /* There is a matching pop below. */ #pragma pack(push, cryptoki, 1) #ifdef CRYPTOKI_EXPORTS #define CK_SPEC __declspec(dllexport) #else #define CK_SPEC __declspec(dllimport) #endif #else #define CK_SPEC #endif #ifdef CRYPTOKI_COMPAT /* If we are in compatibility mode, switch all exposed names to the PKCS #11 variant. There are corresponding #undefs below. */ #define ck_flags_t CK_FLAGS #define ck_version _CK_VERSION #define ck_info _CK_INFO #define cryptoki_version cryptokiVersion #define manufacturer_id manufacturerID #define library_description libraryDescription #define library_version libraryVersion #define ck_notification_t CK_NOTIFICATION #define ck_slot_id_t CK_SLOT_ID #define ck_slot_info _CK_SLOT_INFO #define slot_description slotDescription #define hardware_version hardwareVersion #define firmware_version firmwareVersion #define ck_token_info _CK_TOKEN_INFO #define serial_number serialNumber #define max_session_count ulMaxSessionCount #define session_count ulSessionCount #define max_rw_session_count ulMaxRwSessionCount #define rw_session_count ulRwSessionCount #define max_pin_len ulMaxPinLen #define min_pin_len ulMinPinLen #define total_public_memory ulTotalPublicMemory #define free_public_memory ulFreePublicMemory #define total_private_memory ulTotalPrivateMemory #define free_private_memory ulFreePrivateMemory #define utc_time utcTime #define ck_session_handle_t CK_SESSION_HANDLE #define ck_user_type_t CK_USER_TYPE #define ck_state_t CK_STATE #define ck_session_info _CK_SESSION_INFO #define slot_id slotID #define device_error ulDeviceError #define ck_object_handle_t CK_OBJECT_HANDLE #define ck_object_class_t CK_OBJECT_CLASS #define ck_hw_feature_type_t CK_HW_FEATURE_TYPE #define ck_key_type_t CK_KEY_TYPE #define ck_certificate_type_t CK_CERTIFICATE_TYPE #define ck_attribute_type_t CK_ATTRIBUTE_TYPE #define ck_attribute _CK_ATTRIBUTE #define value pValue #define value_len ulValueLen #define ck_date _CK_DATE #define ck_mechanism_type_t CK_MECHANISM_TYPE #define ck_mechanism _CK_MECHANISM #define parameter pParameter #define parameter_len ulParameterLen #define ck_mechanism_info _CK_MECHANISM_INFO #define min_key_size ulMinKeySize #define max_key_size ulMaxKeySize #define ck_rsa_pkcs_oaep_params _CK_RSA_PCKS_OAEP_PARAMS #define source_data pSourceData #define source_data_len ulSourceDataLen #define ck_rv_t CK_RV #define ck_notify_t CK_NOTIFY #define ck_function_list _CK_FUNCTION_LIST #define ck_createmutex_t CK_CREATEMUTEX #define ck_destroymutex_t CK_DESTROYMUTEX #define ck_lockmutex_t CK_LOCKMUTEX #define ck_unlockmutex_t CK_UNLOCKMUTEX #define ck_c_initialize_args _CK_C_INITIALIZE_ARGS #define create_mutex CreateMutex #define destroy_mutex DestroyMutex #define lock_mutex LockMutex #define unlock_mutex UnlockMutex #define reserved pReserved #endif /* CRYPTOKI_COMPAT */ typedef unsigned long ck_flags_t; struct ck_version { unsigned char major; unsigned char minor; }; struct ck_info { struct ck_version cryptoki_version; unsigned char manufacturer_id[32]; ck_flags_t flags; unsigned char library_description[32]; struct ck_version library_version; }; typedef unsigned long ck_notification_t; #define CKN_SURRENDER (0) typedef unsigned long ck_slot_id_t; struct ck_slot_info { unsigned char slot_description[64]; unsigned char manufacturer_id[32]; ck_flags_t flags; struct ck_version hardware_version; struct ck_version firmware_version; }; #define CKF_TOKEN_PRESENT (1 << 0) #define CKF_REMOVABLE_DEVICE (1 << 1) #define CKF_HW_SLOT (1 << 2) #define CKF_ARRAY_ATTRIBUTE (1 << 30) struct ck_token_info { unsigned char label[32]; unsigned char manufacturer_id[32]; unsigned char model[16]; unsigned char serial_number[16]; ck_flags_t flags; unsigned long max_session_count; unsigned long session_count; unsigned long max_rw_session_count; unsigned long rw_session_count; unsigned long max_pin_len; unsigned long min_pin_len; unsigned long total_public_memory; unsigned long free_public_memory; unsigned long total_private_memory; unsigned long free_private_memory; struct ck_version hardware_version; struct ck_version firmware_version; unsigned char utc_time[16]; }; #define CKF_RNG (1 << 0) #define CKF_WRITE_PROTECTED (1 << 1) #define CKF_LOGIN_REQUIRED (1 << 2) #define CKF_USER_PIN_INITIALIZED (1 << 3) #define CKF_RESTORE_KEY_NOT_NEEDED (1 << 5) #define CKF_CLOCK_ON_TOKEN (1 << 6) #define CKF_PROTECTED_AUTHENTICATION_PATH (1 << 8) #define CKF_DUAL_CRYPTO_OPERATIONS (1 << 9) #define CKF_TOKEN_INITIALIZED (1 << 10) #define CKF_SECONDARY_AUTHENTICATION (1 << 11) #define CKF_USER_PIN_COUNT_LOW (1 << 16) #define CKF_USER_PIN_FINAL_TRY (1 << 17) #define CKF_USER_PIN_LOCKED (1 << 18) #define CKF_USER_PIN_TO_BE_CHANGED (1 << 19) #define CKF_SO_PIN_COUNT_LOW (1 << 20) #define CKF_SO_PIN_FINAL_TRY (1 << 21) #define CKF_SO_PIN_LOCKED (1 << 22) #define CKF_SO_PIN_TO_BE_CHANGED (1 << 23) #define CK_UNAVAILABLE_INFORMATION ((unsigned long) -1) #define CK_EFFECTIVELY_INFINITE (0) typedef unsigned long ck_session_handle_t; #define CK_INVALID_HANDLE (0) typedef unsigned long ck_user_type_t; #define CKU_SO (0) #define CKU_USER (1) #define CKU_CONTEXT_SPECIFIC (2) typedef unsigned long ck_state_t; #define CKS_RO_PUBLIC_SESSION (0) #define CKS_RO_USER_FUNCTIONS (1) #define CKS_RW_PUBLIC_SESSION (2) #define CKS_RW_USER_FUNCTIONS (3) #define CKS_RW_SO_FUNCTIONS (4) struct ck_session_info { ck_slot_id_t slot_id; ck_state_t state; ck_flags_t flags; unsigned long device_error; }; #define CKF_RW_SESSION (1 << 1) #define CKF_SERIAL_SESSION (1 << 2) typedef unsigned long ck_object_handle_t; typedef unsigned long ck_object_class_t; #define CKO_DATA (0) #define CKO_CERTIFICATE (1) #define CKO_PUBLIC_KEY (2) #define CKO_PRIVATE_KEY (3) #define CKO_SECRET_KEY (4) #define CKO_HW_FEATURE (5) #define CKO_DOMAIN_PARAMETERS (6) #define CKO_MECHANISM (7) #define CKO_VENDOR_DEFINED ((unsigned long) (1 << 31)) typedef unsigned long ck_hw_feature_type_t; #define CKH_MONOTONIC_COUNTER (1) #define CKH_CLOCK (2) #define CKH_USER_INTERFACE (3) #define CKH_VENDOR_DEFINED ((unsigned long) (1 << 31)) typedef unsigned long ck_key_type_t; #define CKK_RSA (0) #define CKK_DSA (1) #define CKK_DH (2) #define CKK_ECDSA (3) #define CKK_EC (3) #define CKK_X9_42_DH (4) #define CKK_KEA (5) #define CKK_GENERIC_SECRET (0x10) #define CKK_RC2 (0x11) #define CKK_RC4 (0x12) #define CKK_DES (0x13) #define CKK_DES2 (0x14) #define CKK_DES3 (0x15) #define CKK_CAST (0x16) #define CKK_CAST3 (0x17) #define CKK_CAST128 (0x18) #define CKK_RC5 (0x19) #define CKK_IDEA (0x1a) #define CKK_SKIPJACK (0x1b) #define CKK_BATON (0x1c) #define CKK_JUNIPER (0x1d) #define CKK_CDMF (0x1e) #define CKK_AES (0x1f) #define CKK_BLOWFISH (0x20) #define CKK_TWOFISH (0x21) #define CKK_VENDOR_DEFINED ((unsigned long) (1 << 31)) typedef unsigned long ck_certificate_type_t; #define CKC_X_509 (0) #define CKC_X_509_ATTR_CERT (1) #define CKC_WTLS (2) #define CKC_VENDOR_DEFINED ((unsigned long) (1 << 31)) typedef unsigned long ck_attribute_type_t; #define CKA_CLASS (0) #define CKA_TOKEN (1) #define CKA_PRIVATE (2) #define CKA_LABEL (3) #define CKA_APPLICATION (0x10) #define CKA_VALUE (0x11) #define CKA_OBJECT_ID (0x12) #define CKA_CERTIFICATE_TYPE (0x80) #define CKA_ISSUER (0x81) #define CKA_SERIAL_NUMBER (0x82) #define CKA_AC_ISSUER (0x83) #define CKA_OWNER (0x84) #define CKA_ATTR_TYPES (0x85) #define CKA_TRUSTED (0x86) #define CKA_CERTIFICATE_CATEGORY (0x87) #define CKA_JAVA_MIDP_SECURITY_DOMAIN (0x88) #define CKA_URL (0x89) #define CKA_HASH_OF_SUBJECT_PUBLIC_KEY (0x8a) #define CKA_HASH_OF_ISSUER_PUBLIC_KEY (0x8b) #define CKA_CHECK_VALUE (0x90) #define CKA_KEY_TYPE (0x100) #define CKA_SUBJECT (0x101) #define CKA_ID (0x102) #define CKA_SENSITIVE (0x103) #define CKA_ENCRYPT (0x104) #define CKA_DECRYPT (0x105) #define CKA_WRAP (0x106) #define CKA_UNWRAP (0x107) #define CKA_SIGN (0x108) #define CKA_SIGN_RECOVER (0x109) #define CKA_VERIFY (0x10a) #define CKA_VERIFY_RECOVER (0x10b) #define CKA_DERIVE (0x10c) #define CKA_START_DATE (0x110) #define CKA_END_DATE (0x111) #define CKA_MODULUS (0x120) #define CKA_MODULUS_BITS (0x121) #define CKA_PUBLIC_EXPONENT (0x122) #define CKA_PRIVATE_EXPONENT (0x123) #define CKA_PRIME_1 (0x124) #define CKA_PRIME_2 (0x125) #define CKA_EXPONENT_1 (0x126) #define CKA_EXPONENT_2 (0x127) #define CKA_COEFFICIENT (0x128) #define CKA_PRIME (0x130) #define CKA_SUBPRIME (0x131) #define CKA_BASE (0x132) #define CKA_PRIME_BITS (0x133) #define CKA_SUB_PRIME_BITS (0x134) #define CKA_VALUE_BITS (0x160) #define CKA_VALUE_LEN (0x161) #define CKA_EXTRACTABLE (0x162) #define CKA_LOCAL (0x163) #define CKA_NEVER_EXTRACTABLE (0x164) #define CKA_ALWAYS_SENSITIVE (0x165) #define CKA_KEY_GEN_MECHANISM (0x166) #define CKA_MODIFIABLE (0x170) #define CKA_COPYABLE (0x171) #define CKA_DESTROYABLE (0x172) #define CKA_ECDSA_PARAMS (0x180) #define CKA_EC_PARAMS (0x180) #define CKA_EC_POINT (0x181) #define CKA_SECONDARY_AUTH (0x200) #define CKA_AUTH_PIN_FLAGS (0x201) #define CKA_ALWAYS_AUTHENTICATE (0x202) #define CKA_WRAP_WITH_TRUSTED (0x210) #define CKA_HW_FEATURE_TYPE (0x300) #define CKA_RESET_ON_INIT (0x301) #define CKA_HAS_RESET (0x302) #define CKA_PIXEL_X (0x400) #define CKA_PIXEL_Y (0x401) #define CKA_RESOLUTION (0x402) #define CKA_CHAR_ROWS (0x403) #define CKA_CHAR_COLUMNS (0x404) #define CKA_COLOR (0x405) #define CKA_BITS_PER_PIXEL (0x406) #define CKA_CHAR_SETS (0x480) #define CKA_ENCODING_METHODS (0x481) #define CKA_MIME_TYPES (0x482) #define CKA_MECHANISM_TYPE (0x500) #define CKA_REQUIRED_CMS_ATTRIBUTES (0x501) #define CKA_DEFAULT_CMS_ATTRIBUTES (0x502) #define CKA_SUPPORTED_CMS_ATTRIBUTES (0x503) #define CKA_WRAP_TEMPLATE (CKF_ARRAY_ATTRIBUTE | 0x211) #define CKA_UNWRAP_TEMPLATE (CKF_ARRAY_ATTRIBUTE | 0x212) #define CKA_ALLOWED_MECHANISMS (CKF_ARRAY_ATTRIBUTE | 0x600) #define CKA_VENDOR_DEFINED ((unsigned long) (1 << 31)) struct ck_attribute { ck_attribute_type_t type; void *value; unsigned long value_len; }; struct ck_date { unsigned char year[4]; unsigned char month[2]; unsigned char day[2]; }; typedef unsigned long ck_mechanism_type_t; #define CKM_RSA_PKCS_KEY_PAIR_GEN (0) #define CKM_RSA_PKCS (1) #define CKM_RSA_9796 (2) #define CKM_RSA_X_509 (3) #define CKM_MD2_RSA_PKCS (4) #define CKM_MD5_RSA_PKCS (5) #define CKM_SHA1_RSA_PKCS (6) #define CKM_RIPEMD128_RSA_PKCS (7) #define CKM_RIPEMD160_RSA_PKCS (8) #define CKM_RSA_PKCS_OAEP (9) #define CKM_RSA_X9_31_KEY_PAIR_GEN (0xa) #define CKM_RSA_X9_31 (0xb) #define CKM_SHA1_RSA_X9_31 (0xc) #define CKM_RSA_PKCS_PSS (0xd) #define CKM_SHA1_RSA_PKCS_PSS (0xe) #define CKM_DSA_KEY_PAIR_GEN (0x10) #define CKM_DSA (0x11) #define CKM_DSA_SHA1 (0x12) #define CKM_DH_PKCS_KEY_PAIR_GEN (0x20) #define CKM_DH_PKCS_DERIVE (0x21) #define CKM_X9_42_DH_KEY_PAIR_GEN (0x30) #define CKM_X9_42_DH_DERIVE (0x31) #define CKM_X9_42_DH_HYBRID_DERIVE (0x32) #define CKM_X9_42_MQV_DERIVE (0x33) #define CKM_SHA256_RSA_PKCS (0x40) #define CKM_SHA384_RSA_PKCS (0x41) #define CKM_SHA512_RSA_PKCS (0x42) #define CKM_SHA256_RSA_PKCS_PSS (0x43) #define CKM_SHA384_RSA_PKCS_PSS (0x44) #define CKM_SHA512_RSA_PKCS_PSS (0x45) #define CKM_RC2_KEY_GEN (0x100) #define CKM_RC2_ECB (0x101) #define CKM_RC2_CBC (0x102) #define CKM_RC2_MAC (0x103) #define CKM_RC2_MAC_GENERAL (0x104) #define CKM_RC2_CBC_PAD (0x105) #define CKM_RC4_KEY_GEN (0x110) #define CKM_RC4 (0x111) #define CKM_DES_KEY_GEN (0x120) #define CKM_DES_ECB (0x121) #define CKM_DES_CBC (0x122) #define CKM_DES_MAC (0x123) #define CKM_DES_MAC_GENERAL (0x124) #define CKM_DES_CBC_PAD (0x125) #define CKM_DES2_KEY_GEN (0x130) #define CKM_DES3_KEY_GEN (0x131) #define CKM_DES3_ECB (0x132) #define CKM_DES3_CBC (0x133) #define CKM_DES3_MAC (0x134) #define CKM_DES3_MAC_GENERAL (0x135) #define CKM_DES3_CBC_PAD (0x136) #define CKM_CDMF_KEY_GEN (0x140) #define CKM_CDMF_ECB (0x141) #define CKM_CDMF_CBC (0x142) #define CKM_CDMF_MAC (0x143) #define CKM_CDMF_MAC_GENERAL (0x144) #define CKM_CDMF_CBC_PAD (0x145) #define CKM_MD2 (0x200) #define CKM_MD2_HMAC (0x201) #define CKM_MD2_HMAC_GENERAL (0x202) #define CKM_MD5 (0x210) #define CKM_MD5_HMAC (0x211) #define CKM_MD5_HMAC_GENERAL (0x212) #define CKM_SHA_1 (0x220) #define CKM_SHA_1_HMAC (0x221) #define CKM_SHA_1_HMAC_GENERAL (0x222) #define CKM_RIPEMD128 (0x230) #define CKM_RIPEMD128_HMAC (0x231) #define CKM_RIPEMD128_HMAC_GENERAL (0x232) #define CKM_RIPEMD160 (0x240) #define CKM_RIPEMD160_HMAC (0x241) #define CKM_RIPEMD160_HMAC_GENERAL (0x242) #define CKM_SHA256 (0x250) #define CKM_SHA256_HMAC (0x251) #define CKM_SHA256_HMAC_GENERAL (0x252) #define CKM_SHA384 (0x260) #define CKM_SHA384_HMAC (0x261) #define CKM_SHA384_HMAC_GENERAL (0x262) #define CKM_SHA512 (0x270) #define CKM_SHA512_HMAC (0x271) #define CKM_SHA512_HMAC_GENERAL (0x272) #define CKM_CAST_KEY_GEN (0x300) #define CKM_CAST_ECB (0x301) #define CKM_CAST_CBC (0x302) #define CKM_CAST_MAC (0x303) #define CKM_CAST_MAC_GENERAL (0x304) #define CKM_CAST_CBC_PAD (0x305) #define CKM_CAST3_KEY_GEN (0x310) #define CKM_CAST3_ECB (0x311) #define CKM_CAST3_CBC (0x312) #define CKM_CAST3_MAC (0x313) #define CKM_CAST3_MAC_GENERAL (0x314) #define CKM_CAST3_CBC_PAD (0x315) #define CKM_CAST5_KEY_GEN (0x320) #define CKM_CAST128_KEY_GEN (0x320) #define CKM_CAST5_ECB (0x321) #define CKM_CAST128_ECB (0x321) #define CKM_CAST5_CBC (0x322) #define CKM_CAST128_CBC (0x322) #define CKM_CAST5_MAC (0x323) #define CKM_CAST128_MAC (0x323) #define CKM_CAST5_MAC_GENERAL (0x324) #define CKM_CAST128_MAC_GENERAL (0x324) #define CKM_CAST5_CBC_PAD (0x325) #define CKM_CAST128_CBC_PAD (0x325) #define CKM_RC5_KEY_GEN (0x330) #define CKM_RC5_ECB (0x331) #define CKM_RC5_CBC (0x332) #define CKM_RC5_MAC (0x333) #define CKM_RC5_MAC_GENERAL (0x334) #define CKM_RC5_CBC_PAD (0x335) #define CKM_IDEA_KEY_GEN (0x340) #define CKM_IDEA_ECB (0x341) #define CKM_IDEA_CBC (0x342) #define CKM_IDEA_MAC (0x343) #define CKM_IDEA_MAC_GENERAL (0x344) #define CKM_IDEA_CBC_PAD (0x345) #define CKM_GENERIC_SECRET_KEY_GEN (0x350) #define CKM_CONCATENATE_BASE_AND_KEY (0x360) #define CKM_CONCATENATE_BASE_AND_DATA (0x362) #define CKM_CONCATENATE_DATA_AND_BASE (0x363) #define CKM_XOR_BASE_AND_DATA (0x364) #define CKM_EXTRACT_KEY_FROM_KEY (0x365) #define CKM_SSL3_PRE_MASTER_KEY_GEN (0x370) #define CKM_SSL3_MASTER_KEY_DERIVE (0x371) #define CKM_SSL3_KEY_AND_MAC_DERIVE (0x372) #define CKM_SSL3_MASTER_KEY_DERIVE_DH (0x373) #define CKM_TLS_PRE_MASTER_KEY_GEN (0x374) #define CKM_TLS_MASTER_KEY_DERIVE (0x375) #define CKM_TLS_KEY_AND_MAC_DERIVE (0x376) #define CKM_TLS_MASTER_KEY_DERIVE_DH (0x377) #define CKM_SSL3_MD5_MAC (0x380) #define CKM_SSL3_SHA1_MAC (0x381) #define CKM_MD5_KEY_DERIVATION (0x390) #define CKM_MD2_KEY_DERIVATION (0x391) #define CKM_SHA1_KEY_DERIVATION (0x392) #define CKM_PBE_MD2_DES_CBC (0x3a0) #define CKM_PBE_MD5_DES_CBC (0x3a1) #define CKM_PBE_MD5_CAST_CBC (0x3a2) #define CKM_PBE_MD5_CAST3_CBC (0x3a3) #define CKM_PBE_MD5_CAST5_CBC (0x3a4) #define CKM_PBE_MD5_CAST128_CBC (0x3a4) #define CKM_PBE_SHA1_CAST5_CBC (0x3a5) #define CKM_PBE_SHA1_CAST128_CBC (0x3a5) #define CKM_PBE_SHA1_RC4_128 (0x3a6) #define CKM_PBE_SHA1_RC4_40 (0x3a7) #define CKM_PBE_SHA1_DES3_EDE_CBC (0x3a8) #define CKM_PBE_SHA1_DES2_EDE_CBC (0x3a9) #define CKM_PBE_SHA1_RC2_128_CBC (0x3aa) #define CKM_PBE_SHA1_RC2_40_CBC (0x3ab) #define CKM_PKCS5_PBKD2 (0x3b0) #define CKM_PBA_SHA1_WITH_SHA1_HMAC (0x3c0) #define CKM_KEY_WRAP_LYNKS (0x400) #define CKM_KEY_WRAP_SET_OAEP (0x401) #define CKM_SKIPJACK_KEY_GEN (0x1000) #define CKM_SKIPJACK_ECB64 (0x1001) #define CKM_SKIPJACK_CBC64 (0x1002) #define CKM_SKIPJACK_OFB64 (0x1003) #define CKM_SKIPJACK_CFB64 (0x1004) #define CKM_SKIPJACK_CFB32 (0x1005) #define CKM_SKIPJACK_CFB16 (0x1006) #define CKM_SKIPJACK_CFB8 (0x1007) #define CKM_SKIPJACK_WRAP (0x1008) #define CKM_SKIPJACK_PRIVATE_WRAP (0x1009) #define CKM_SKIPJACK_RELAYX (0x100a) #define CKM_KEA_KEY_PAIR_GEN (0x1010) #define CKM_KEA_KEY_DERIVE (0x1011) #define CKM_FORTEZZA_TIMESTAMP (0x1020) #define CKM_BATON_KEY_GEN (0x1030) #define CKM_BATON_ECB128 (0x1031) #define CKM_BATON_ECB96 (0x1032) #define CKM_BATON_CBC128 (0x1033) #define CKM_BATON_COUNTER (0x1034) #define CKM_BATON_SHUFFLE (0x1035) #define CKM_BATON_WRAP (0x1036) #define CKM_ECDSA_KEY_PAIR_GEN (0x1040) #define CKM_EC_KEY_PAIR_GEN (0x1040) #define CKM_ECDSA (0x1041) #define CKM_ECDSA_SHA1 (0x1042) #define CKM_ECDSA_SHA224 (0x1043) #define CKM_ECDSA_SHA256 (0x1044) #define CKM_ECDSA_SHA384 (0x1045) #define CKM_ECDSA_SHA512 (0x1046) #define CKM_ECDH1_DERIVE (0x1050) #define CKM_ECDH1_COFACTOR_DERIVE (0x1051) #define CKM_ECMQV_DERIVE (0x1052) #define CKM_JUNIPER_KEY_GEN (0x1060) #define CKM_JUNIPER_ECB128 (0x1061) #define CKM_JUNIPER_CBC128 (0x1062) #define CKM_JUNIPER_COUNTER (0x1063) #define CKM_JUNIPER_SHUFFLE (0x1064) #define CKM_JUNIPER_WRAP (0x1065) #define CKM_FASTHASH (0x1070) #define CKM_AES_KEY_GEN (0x1080) #define CKM_AES_ECB (0x1081) #define CKM_AES_CBC (0x1082) #define CKM_AES_MAC (0x1083) #define CKM_AES_MAC_GENERAL (0x1084) #define CKM_AES_CBC_PAD (0x1085) #define CKM_DSA_PARAMETER_GEN (0x2000) #define CKM_DH_PKCS_PARAMETER_GEN (0x2001) #define CKM_X9_42_DH_PARAMETER_GEN (0x2002) #define CKM_VENDOR_DEFINED ((unsigned long) (1 << 31)) #define CKG_MGF1_SHA1 (0x00000001) #define CKG_MGF1_SHA256 (0x00000002) #define CKG_MGF1_SHA384 (0x00000003) #define CKG_MGF1_SHA512 (0x00000004) #define CKD_NULL (0x00000001) #define CKD_SHA1_KDF (0x00000002) /* The following X9.42 DH key derivation functions are defined */ #define CKD_SHA1_KDF_ASN1 (0x00000003UL) #define CKD_SHA1_KDF_CONCATENATE (0x00000004UL) #define CKD_SHA224_KDF (0x00000005UL) #define CKD_SHA256_KDF (0x00000006UL) #define CKD_SHA384_KDF (0x00000007UL) #define CKD_SHA512_KDF (0x00000008UL) #define CKD_CPDIVERSIFY_KDF (0x00000009UL) #define CKD_SHA3_224_KDF (0x0000000AUL) #define CKD_SHA3_256_KDF (0x0000000BUL) #define CKD_SHA3_384_KDF (0x0000000CUL) #define CKD_SHA3_512_KDF (0x0000000DUL) #define CKD_SHA1_KDF_SP800 (0x0000000EUL) #define CKD_SHA224_KDF_SP800 (0x0000000FUL) #define CKD_SHA256_KDF_SP800 (0x00000010UL) #define CKD_SHA384_KDF_SP800 (0x00000011UL) #define CKD_SHA512_KDF_SP800 (0x00000012UL) #define CKD_SHA3_224_KDF_SP800 (0x00000013UL) #define CKD_SHA3_256_KDF_SP800 (0x00000014UL) #define CKD_SHA3_384_KDF_SP800 (0x00000015UL) #define CKD_SHA3_512_KDF_SP800 (0x00000016UL) #define CKD_BLAKE2B_160_KDF (0x00000017UL) #define CKD_BLAKE2B_256_KDF (0x00000018UL) #define CKD_BLAKE2B_384_KDF (0x00000019UL) #define CKD_BLAKE2B_512_KDF (0x0000001aUL) struct ck_mechanism { ck_mechanism_type_t mechanism; void *parameter; unsigned long parameter_len; }; struct ck_mechanism_info { unsigned long min_key_size; unsigned long max_key_size; ck_flags_t flags; }; struct ck_rsa_pkcs_oaep_params { unsigned long hashAlg; unsigned long mgf; unsigned long src; void *source_data; unsigned long source_data_len; } ; struct ck_rsa_pkcs_pss_params { unsigned long hashAlg; unsigned long mgf; unsigned long sLen; } ; struct ck_gcm_params { void * pIv; unsigned long ulIvLen; unsigned long ulIvBits; void * pAAD; unsigned long ulAADLen; unsigned long ulTagBits; } ; struct ck_aes_ctr_params { unsigned long ulCounterBits; unsigned char cb[16]; } ; struct ck_ecdh1_derive_params { unsigned long kdf; unsigned long ulSharedDataLen; void * pSharedData; unsigned long ulPublicDataLen; void * pPublicData; } ; struct ck_key_derivation_string_data { unsigned char * pData; unsigned long ulLen; } ; #define CKF_HW (1 << 0) #define CKF_ENCRYPT (1 << 8) #define CKF_DECRYPT (1 << 9) #define CKF_DIGEST (1 << 10) #define CKF_SIGN (1 << 11) #define CKF_SIGN_RECOVER (1 << 12) #define CKF_VERIFY (1 << 13) #define CKF_VERIFY_RECOVER (1 << 14) #define CKF_GENERATE (1 << 15) #define CKF_GENERATE_KEY_PAIR (1 << 16) #define CKF_WRAP (1 << 17) #define CKF_UNWRAP (1 << 18) #define CKF_DERIVE (1 << 19) #define CKF_EXTENSION ((unsigned long) (1 << 31)) /* Flags for C_WaitForSlotEvent. */ #define CKF_DONT_BLOCK (1) typedef unsigned long ck_rv_t; typedef ck_rv_t (*ck_notify_t) (ck_session_handle_t session, ck_notification_t event, void *application); /* Forward reference. */ struct ck_function_list; #define _CK_DECLARE_FUNCTION(name, args) \ typedef ck_rv_t (*CK_ ## name) args; \ ck_rv_t CK_SPEC name args _CK_DECLARE_FUNCTION (C_Initialize, (void *init_args)); _CK_DECLARE_FUNCTION (C_Finalize, (void *reserved)); _CK_DECLARE_FUNCTION (C_GetInfo, (struct ck_info *info)); _CK_DECLARE_FUNCTION (C_GetFunctionList, (struct ck_function_list **function_list)); _CK_DECLARE_FUNCTION (C_GetSlotList, (unsigned char token_present, ck_slot_id_t *slot_list, unsigned long *count)); _CK_DECLARE_FUNCTION (C_GetSlotInfo, (ck_slot_id_t slot_id, struct ck_slot_info *info)); _CK_DECLARE_FUNCTION (C_GetTokenInfo, (ck_slot_id_t slot_id, struct ck_token_info *info)); _CK_DECLARE_FUNCTION (C_WaitForSlotEvent, (ck_flags_t flags, ck_slot_id_t *slot, void *reserved)); _CK_DECLARE_FUNCTION (C_GetMechanismList, (ck_slot_id_t slot_id, ck_mechanism_type_t *mechanism_list, unsigned long *count)); _CK_DECLARE_FUNCTION (C_GetMechanismInfo, (ck_slot_id_t slot_id, ck_mechanism_type_t type, struct ck_mechanism_info *info)); _CK_DECLARE_FUNCTION (C_InitToken, (ck_slot_id_t slot_id, unsigned char *pin, unsigned long pin_len, unsigned char *label)); _CK_DECLARE_FUNCTION (C_InitPIN, (ck_session_handle_t session, unsigned char *pin, unsigned long pin_len)); _CK_DECLARE_FUNCTION (C_SetPIN, (ck_session_handle_t session, unsigned char *old_pin, unsigned long old_len, unsigned char *new_pin, unsigned long new_len)); _CK_DECLARE_FUNCTION (C_OpenSession, (ck_slot_id_t slot_id, ck_flags_t flags, void *application, ck_notify_t notify, ck_session_handle_t *session)); _CK_DECLARE_FUNCTION (C_CloseSession, (ck_session_handle_t session)); _CK_DECLARE_FUNCTION (C_CloseAllSessions, (ck_slot_id_t slot_id)); _CK_DECLARE_FUNCTION (C_GetSessionInfo, (ck_session_handle_t session, struct ck_session_info *info)); _CK_DECLARE_FUNCTION (C_GetOperationState, (ck_session_handle_t session, unsigned char *operation_state, unsigned long *operation_state_len)); _CK_DECLARE_FUNCTION (C_SetOperationState, (ck_session_handle_t session, unsigned char *operation_state, unsigned long operation_state_len, ck_object_handle_t encryption_key, ck_object_handle_t authentiation_key)); _CK_DECLARE_FUNCTION (C_Login, (ck_session_handle_t session, ck_user_type_t user_type, unsigned char *pin, unsigned long pin_len)); _CK_DECLARE_FUNCTION (C_Logout, (ck_session_handle_t session)); _CK_DECLARE_FUNCTION (C_CreateObject, (ck_session_handle_t session, struct ck_attribute *templ, unsigned long count, ck_object_handle_t *object)); _CK_DECLARE_FUNCTION (C_CopyObject, (ck_session_handle_t session, ck_object_handle_t object, struct ck_attribute *templ, unsigned long count, ck_object_handle_t *new_object)); _CK_DECLARE_FUNCTION (C_DestroyObject, (ck_session_handle_t session, ck_object_handle_t object)); _CK_DECLARE_FUNCTION (C_GetObjectSize, (ck_session_handle_t session, ck_object_handle_t object, unsigned long *size)); _CK_DECLARE_FUNCTION (C_GetAttributeValue, (ck_session_handle_t session, ck_object_handle_t object, struct ck_attribute *templ, unsigned long count)); _CK_DECLARE_FUNCTION (C_SetAttributeValue, (ck_session_handle_t session, ck_object_handle_t object, struct ck_attribute *templ, unsigned long count)); _CK_DECLARE_FUNCTION (C_FindObjectsInit, (ck_session_handle_t session, struct ck_attribute *templ, unsigned long count)); _CK_DECLARE_FUNCTION (C_FindObjects, (ck_session_handle_t session, ck_object_handle_t *object, unsigned long max_object_count, unsigned long *object_count)); _CK_DECLARE_FUNCTION (C_FindObjectsFinal, (ck_session_handle_t session)); _CK_DECLARE_FUNCTION (C_EncryptInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_Encrypt, (ck_session_handle_t session, unsigned char *data, unsigned long data_len, unsigned char *encrypted_data, unsigned long *encrypted_data_len)); _CK_DECLARE_FUNCTION (C_EncryptUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len, unsigned char *encrypted_part, unsigned long *encrypted_part_len)); _CK_DECLARE_FUNCTION (C_EncryptFinal, (ck_session_handle_t session, unsigned char *last_encrypted_part, unsigned long *last_encrypted_part_len)); _CK_DECLARE_FUNCTION (C_DecryptInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_Decrypt, (ck_session_handle_t session, unsigned char *encrypted_data, unsigned long encrypted_data_len, unsigned char *data, unsigned long *data_len)); _CK_DECLARE_FUNCTION (C_DecryptUpdate, (ck_session_handle_t session, unsigned char *encrypted_part, unsigned long encrypted_part_len, unsigned char *part, unsigned long *part_len)); _CK_DECLARE_FUNCTION (C_DecryptFinal, (ck_session_handle_t session, unsigned char *last_part, unsigned long *last_part_len)); _CK_DECLARE_FUNCTION (C_DigestInit, (ck_session_handle_t session, struct ck_mechanism *mechanism)); _CK_DECLARE_FUNCTION (C_Digest, (ck_session_handle_t session, unsigned char *data, unsigned long data_len, unsigned char *digest, unsigned long *digest_len)); _CK_DECLARE_FUNCTION (C_DigestUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len)); _CK_DECLARE_FUNCTION (C_DigestKey, (ck_session_handle_t session, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_DigestFinal, (ck_session_handle_t session, unsigned char *digest, unsigned long *digest_len)); _CK_DECLARE_FUNCTION (C_SignInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_Sign, (ck_session_handle_t session, unsigned char *data, unsigned long data_len, unsigned char *signature, unsigned long *signature_len)); _CK_DECLARE_FUNCTION (C_SignUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len)); _CK_DECLARE_FUNCTION (C_SignFinal, (ck_session_handle_t session, unsigned char *signature, unsigned long *signature_len)); _CK_DECLARE_FUNCTION (C_SignRecoverInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_SignRecover, (ck_session_handle_t session, unsigned char *data, unsigned long data_len, unsigned char *signature, unsigned long *signature_len)); _CK_DECLARE_FUNCTION (C_VerifyInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_Verify, (ck_session_handle_t session, unsigned char *data, unsigned long data_len, unsigned char *signature, unsigned long signature_len)); _CK_DECLARE_FUNCTION (C_VerifyUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len)); _CK_DECLARE_FUNCTION (C_VerifyFinal, (ck_session_handle_t session, unsigned char *signature, unsigned long signature_len)); _CK_DECLARE_FUNCTION (C_VerifyRecoverInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_VerifyRecover, (ck_session_handle_t session, unsigned char *signature, unsigned long signature_len, unsigned char *data, unsigned long *data_len)); _CK_DECLARE_FUNCTION (C_DigestEncryptUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len, unsigned char *encrypted_part, unsigned long *encrypted_part_len)); _CK_DECLARE_FUNCTION (C_DecryptDigestUpdate, (ck_session_handle_t session, unsigned char *encrypted_part, unsigned long encrypted_part_len, unsigned char *part, unsigned long *part_len)); _CK_DECLARE_FUNCTION (C_SignEncryptUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len, unsigned char *encrypted_part, unsigned long *encrypted_part_len)); _CK_DECLARE_FUNCTION (C_DecryptVerifyUpdate, (ck_session_handle_t session, unsigned char *encrypted_part, unsigned long encrypted_part_len, unsigned char *part, unsigned long *part_len)); _CK_DECLARE_FUNCTION (C_GenerateKey, (ck_session_handle_t session, struct ck_mechanism *mechanism, struct ck_attribute *templ, unsigned long count, ck_object_handle_t *key)); _CK_DECLARE_FUNCTION (C_GenerateKeyPair, (ck_session_handle_t session, struct ck_mechanism *mechanism, struct ck_attribute *public_key_template, unsigned long public_key_attribute_count, struct ck_attribute *private_key_template, unsigned long private_key_attribute_count, ck_object_handle_t *public_key, ck_object_handle_t *private_key)); _CK_DECLARE_FUNCTION (C_WrapKey, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t wrapping_key, ck_object_handle_t key, unsigned char *wrapped_key, unsigned long *wrapped_key_len)); _CK_DECLARE_FUNCTION (C_UnwrapKey, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t unwrapping_key, unsigned char *wrapped_key, unsigned long wrapped_key_len, struct ck_attribute *templ, unsigned long attribute_count, ck_object_handle_t *key)); _CK_DECLARE_FUNCTION (C_DeriveKey, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t base_key, struct ck_attribute *templ, unsigned long attribute_count, ck_object_handle_t *key)); _CK_DECLARE_FUNCTION (C_SeedRandom, (ck_session_handle_t session, unsigned char *seed, unsigned long seed_len)); _CK_DECLARE_FUNCTION (C_GenerateRandom, (ck_session_handle_t session, unsigned char *random_data, unsigned long random_len)); _CK_DECLARE_FUNCTION (C_GetFunctionStatus, (ck_session_handle_t session)); _CK_DECLARE_FUNCTION (C_CancelFunction, (ck_session_handle_t session)); struct ck_function_list { struct ck_version version; CK_C_Initialize C_Initialize; CK_C_Finalize C_Finalize; CK_C_GetInfo C_GetInfo; CK_C_GetFunctionList C_GetFunctionList; CK_C_GetSlotList C_GetSlotList; CK_C_GetSlotInfo C_GetSlotInfo; CK_C_GetTokenInfo C_GetTokenInfo; CK_C_GetMechanismList C_GetMechanismList; CK_C_GetMechanismInfo C_GetMechanismInfo; CK_C_InitToken C_InitToken; CK_C_InitPIN C_InitPIN; CK_C_SetPIN C_SetPIN; CK_C_OpenSession C_OpenSession; CK_C_CloseSession C_CloseSession; CK_C_CloseAllSessions C_CloseAllSessions; CK_C_GetSessionInfo C_GetSessionInfo; CK_C_GetOperationState C_GetOperationState; CK_C_SetOperationState C_SetOperationState; CK_C_Login C_Login; CK_C_Logout C_Logout; CK_C_CreateObject C_CreateObject; CK_C_CopyObject C_CopyObject; CK_C_DestroyObject C_DestroyObject; CK_C_GetObjectSize C_GetObjectSize; CK_C_GetAttributeValue C_GetAttributeValue; CK_C_SetAttributeValue C_SetAttributeValue; CK_C_FindObjectsInit C_FindObjectsInit; CK_C_FindObjects C_FindObjects; CK_C_FindObjectsFinal C_FindObjectsFinal; CK_C_EncryptInit C_EncryptInit; CK_C_Encrypt C_Encrypt; CK_C_EncryptUpdate C_EncryptUpdate; CK_C_EncryptFinal C_EncryptFinal; CK_C_DecryptInit C_DecryptInit; CK_C_Decrypt C_Decrypt; CK_C_DecryptUpdate C_DecryptUpdate; CK_C_DecryptFinal C_DecryptFinal; CK_C_DigestInit C_DigestInit; CK_C_Digest C_Digest; CK_C_DigestUpdate C_DigestUpdate; CK_C_DigestKey C_DigestKey; CK_C_DigestFinal C_DigestFinal; CK_C_SignInit C_SignInit; CK_C_Sign C_Sign; CK_C_SignUpdate C_SignUpdate; CK_C_SignFinal C_SignFinal; CK_C_SignRecoverInit C_SignRecoverInit; CK_C_SignRecover C_SignRecover; CK_C_VerifyInit C_VerifyInit; CK_C_Verify C_Verify; CK_C_VerifyUpdate C_VerifyUpdate; CK_C_VerifyFinal C_VerifyFinal; CK_C_VerifyRecoverInit C_VerifyRecoverInit; CK_C_VerifyRecover C_VerifyRecover; CK_C_DigestEncryptUpdate C_DigestEncryptUpdate; CK_C_DecryptDigestUpdate C_DecryptDigestUpdate; CK_C_SignEncryptUpdate C_SignEncryptUpdate; CK_C_DecryptVerifyUpdate C_DecryptVerifyUpdate; CK_C_GenerateKey C_GenerateKey; CK_C_GenerateKeyPair C_GenerateKeyPair; CK_C_WrapKey C_WrapKey; CK_C_UnwrapKey C_UnwrapKey; CK_C_DeriveKey C_DeriveKey; CK_C_SeedRandom C_SeedRandom; CK_C_GenerateRandom C_GenerateRandom; CK_C_GetFunctionStatus C_GetFunctionStatus; CK_C_CancelFunction C_CancelFunction; CK_C_WaitForSlotEvent C_WaitForSlotEvent; }; typedef ck_rv_t (*ck_createmutex_t) (void **mutex); typedef ck_rv_t (*ck_destroymutex_t) (void *mutex); typedef ck_rv_t (*ck_lockmutex_t) (void *mutex); typedef ck_rv_t (*ck_unlockmutex_t) (void *mutex); struct ck_c_initialize_args { ck_createmutex_t create_mutex; ck_destroymutex_t destroy_mutex; ck_lockmutex_t lock_mutex; ck_unlockmutex_t unlock_mutex; ck_flags_t flags; void *reserved; }; #define CKF_LIBRARY_CANT_CREATE_OS_THREADS (1 << 0) #define CKF_OS_LOCKING_OK (1 << 1) #define CKR_OK (0) #define CKR_CANCEL (1) #define CKR_HOST_MEMORY (2) #define CKR_SLOT_ID_INVALID (3) #define CKR_GENERAL_ERROR (5) #define CKR_FUNCTION_FAILED (6) #define CKR_ARGUMENTS_BAD (7) #define CKR_NO_EVENT (8) #define CKR_NEED_TO_CREATE_THREADS (9) #define CKR_CANT_LOCK (0xa) #define CKR_ATTRIBUTE_READ_ONLY (0x10) #define CKR_ATTRIBUTE_SENSITIVE (0x11) #define CKR_ATTRIBUTE_TYPE_INVALID (0x12) #define CKR_ATTRIBUTE_VALUE_INVALID (0x13) #define CKR_DATA_INVALID (0x20) #define CKR_DATA_LEN_RANGE (0x21) #define CKR_DEVICE_ERROR (0x30) #define CKR_DEVICE_MEMORY (0x31) #define CKR_DEVICE_REMOVED (0x32) #define CKR_ENCRYPTED_DATA_INVALID (0x40) #define CKR_ENCRYPTED_DATA_LEN_RANGE (0x41) #define CKR_FUNCTION_CANCELED (0x50) #define CKR_FUNCTION_NOT_PARALLEL (0x51) #define CKR_FUNCTION_NOT_SUPPORTED (0x54) #define CKR_KEY_HANDLE_INVALID (0x60) #define CKR_KEY_SIZE_RANGE (0x62) #define CKR_KEY_TYPE_INCONSISTENT (0x63) #define CKR_KEY_NOT_NEEDED (0x64) #define CKR_KEY_CHANGED (0x65) #define CKR_KEY_NEEDED (0x66) #define CKR_KEY_INDIGESTIBLE (0x67) #define CKR_KEY_FUNCTION_NOT_PERMITTED (0x68) #define CKR_KEY_NOT_WRAPPABLE (0x69) #define CKR_KEY_UNEXTRACTABLE (0x6a) #define CKR_MECHANISM_INVALID (0x70) #define CKR_MECHANISM_PARAM_INVALID (0x71) #define CKR_OBJECT_HANDLE_INVALID (0x82) #define CKR_OPERATION_ACTIVE (0x90) #define CKR_OPERATION_NOT_INITIALIZED (0x91) #define CKR_PIN_INCORRECT (0xa0) #define CKR_PIN_INVALID (0xa1) #define CKR_PIN_LEN_RANGE (0xa2) #define CKR_PIN_EXPIRED (0xa3) #define CKR_PIN_LOCKED (0xa4) #define CKR_SESSION_CLOSED (0xb0) #define CKR_SESSION_COUNT (0xb1) #define CKR_SESSION_HANDLE_INVALID (0xb3) #define CKR_SESSION_PARALLEL_NOT_SUPPORTED (0xb4) #define CKR_SESSION_READ_ONLY (0xb5) #define CKR_SESSION_EXISTS (0xb6) #define CKR_SESSION_READ_ONLY_EXISTS (0xb7) #define CKR_SESSION_READ_WRITE_SO_EXISTS (0xb8) #define CKR_SIGNATURE_INVALID (0xc0) #define CKR_SIGNATURE_LEN_RANGE (0xc1) #define CKR_TEMPLATE_INCOMPLETE (0xd0) #define CKR_TEMPLATE_INCONSISTENT (0xd1) #define CKR_TOKEN_NOT_PRESENT (0xe0) #define CKR_TOKEN_NOT_RECOGNIZED (0xe1) #define CKR_TOKEN_WRITE_PROTECTED (0xe2) #define CKR_UNWRAPPING_KEY_HANDLE_INVALID (0xf0) #define CKR_UNWRAPPING_KEY_SIZE_RANGE (0xf1) #define CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT (0xf2) #define CKR_USER_ALREADY_LOGGED_IN (0x100) #define CKR_USER_NOT_LOGGED_IN (0x101) #define CKR_USER_PIN_NOT_INITIALIZED (0x102) #define CKR_USER_TYPE_INVALID (0x103) #define CKR_USER_ANOTHER_ALREADY_LOGGED_IN (0x104) #define CKR_USER_TOO_MANY_TYPES (0x105) #define CKR_WRAPPED_KEY_INVALID (0x110) #define CKR_WRAPPED_KEY_LEN_RANGE (0x112) #define CKR_WRAPPING_KEY_HANDLE_INVALID (0x113) #define CKR_WRAPPING_KEY_SIZE_RANGE (0x114) #define CKR_WRAPPING_KEY_TYPE_INCONSISTENT (0x115) #define CKR_RANDOM_SEED_NOT_SUPPORTED (0x120) #define CKR_RANDOM_NO_RNG (0x121) #define CKR_DOMAIN_PARAMS_INVALID (0x130) #define CKR_BUFFER_TOO_SMALL (0x150) #define CKR_SAVED_STATE_INVALID (0x160) #define CKR_INFORMATION_SENSITIVE (0x170) #define CKR_STATE_UNSAVEABLE (0x180) #define CKR_CRYPTOKI_NOT_INITIALIZED (0x190) #define CKR_CRYPTOKI_ALREADY_INITIALIZED (0x191) #define CKR_MUTEX_BAD (0x1a0) #define CKR_MUTEX_NOT_LOCKED (0x1a1) #define CKR_FUNCTION_REJECTED (0x200) #define CKR_VENDOR_DEFINED ((unsigned long) (1 << 31)) /* Compatibility layer. */ #ifdef CRYPTOKI_COMPAT #undef CK_DEFINE_FUNCTION #define CK_DEFINE_FUNCTION(retval, name) retval CK_SPEC name /* For NULL. */ #include typedef unsigned char CK_BYTE; typedef unsigned char CK_CHAR; typedef unsigned char CK_UTF8CHAR; typedef unsigned char CK_BBOOL; typedef unsigned long int CK_ULONG; typedef long int CK_LONG; typedef CK_BYTE *CK_BYTE_PTR; typedef CK_CHAR *CK_CHAR_PTR; typedef CK_UTF8CHAR *CK_UTF8CHAR_PTR; typedef CK_ULONG *CK_ULONG_PTR; typedef void *CK_VOID_PTR; typedef void **CK_VOID_PTR_PTR; #define CK_FALSE 0 #define CK_TRUE 1 #ifndef CK_DISABLE_TRUE_FALSE #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE 1 #endif #endif typedef struct ck_version CK_VERSION; typedef struct ck_version *CK_VERSION_PTR; typedef struct ck_info CK_INFO; typedef struct ck_info *CK_INFO_PTR; typedef ck_slot_id_t *CK_SLOT_ID_PTR; typedef struct ck_slot_info CK_SLOT_INFO; typedef struct ck_slot_info *CK_SLOT_INFO_PTR; typedef struct ck_token_info CK_TOKEN_INFO; typedef struct ck_token_info *CK_TOKEN_INFO_PTR; typedef ck_session_handle_t *CK_SESSION_HANDLE_PTR; typedef struct ck_session_info CK_SESSION_INFO; typedef struct ck_session_info *CK_SESSION_INFO_PTR; typedef ck_object_handle_t *CK_OBJECT_HANDLE_PTR; typedef ck_object_class_t *CK_OBJECT_CLASS_PTR; typedef struct ck_attribute CK_ATTRIBUTE; typedef struct ck_attribute *CK_ATTRIBUTE_PTR; typedef struct ck_date CK_DATE; typedef struct ck_date *CK_DATE_PTR; typedef ck_mechanism_type_t *CK_MECHANISM_TYPE_PTR; typedef struct ck_mechanism CK_MECHANISM; typedef struct ck_mechanism *CK_MECHANISM_PTR; typedef struct ck_mechanism_info CK_MECHANISM_INFO; typedef struct ck_mechanism_info *CK_MECHANISM_INFO_PTR; typedef struct ck_rsa_pkcs_oaep_params CK_RSA_PKCS_OAEP_PARAMS; typedef struct ck_rsa_pkcs_oaep_params *CK_RSA_PKCS_OAEP_PARAMS_PTR; typedef struct ck_rsa_pkcs_pss_params CK_RSA_PKCS_PSS_PARAMS; typedef struct ck_rsa_pkcs_pss_params *CK_RSA_PKCS_PSS_PARAMS_PTR; typedef struct ck_gcm_params CK_GCM_PARAMS; typedef struct ck_aes_ctr_params CK_AES_CTR_PARAMS; typedef struct ck_aes_ctr_params *CK_AES_CTR_PARAMS_PTR; typedef struct ck_ecdh1_derive_params CK_ECDH1_DERIVE_PARAMS; typedef struct ck_ecdh1_derive_params *CK_ECDH1_DERIVE_PARAMS_PTR; typedef struct ck_key_derivation_string_data CK_KEY_DERIVATION_STRING_DATA; typedef struct ck_key_derivation_string_data *CK_KEY_DERIVATION_STRING_DATA_PTR; typedef struct ck_function_list CK_FUNCTION_LIST; typedef struct ck_function_list *CK_FUNCTION_LIST_PTR; typedef struct ck_function_list **CK_FUNCTION_LIST_PTR_PTR; typedef struct ck_c_initialize_args CK_C_INITIALIZE_ARGS; typedef struct ck_c_initialize_args *CK_C_INITIALIZE_ARGS_PTR; #define NULL_PTR NULL /* Delete the helper macros defined at the top of the file. */ #undef ck_flags_t #undef ck_version #undef ck_info #undef cryptoki_version #undef manufacturer_id #undef library_description #undef library_version #undef ck_notification_t #undef ck_slot_id_t #undef ck_slot_info #undef slot_description #undef hardware_version #undef firmware_version #undef ck_token_info #undef serial_number #undef max_session_count #undef session_count #undef max_rw_session_count #undef rw_session_count #undef max_pin_len #undef min_pin_len #undef total_public_memory #undef free_public_memory #undef total_private_memory #undef free_private_memory #undef utc_time #undef ck_session_handle_t #undef ck_user_type_t #undef ck_state_t #undef ck_session_info #undef slot_id #undef device_error #undef ck_object_handle_t #undef ck_object_class_t #undef ck_hw_feature_type_t #undef ck_key_type_t #undef ck_certificate_type_t #undef ck_attribute_type_t #undef ck_attribute #undef value #undef value_len #undef ck_date #undef ck_mechanism_type_t #undef ck_mechanism #undef parameter #undef parameter_len #undef ck_mechanism_info #undef min_key_size #undef max_key_size #undef ck_rsa_pkcs_oaep_params #undef ck_rsa_pkcs_pss_params #undef ck_rsa_pkcs_pss_params #undef ck_rv_t #undef ck_notify_t #undef ck_function_list #undef ck_createmutex_t #undef ck_destroymutex_t #undef ck_lockmutex_t #undef ck_unlockmutex_t #undef ck_c_initialize_args #undef create_mutex #undef destroy_mutex #undef lock_mutex #undef unlock_mutex #undef reserved #endif /* CRYPTOKI_COMPAT */ /* System dependencies. */ #if defined(_WIN32) || defined(CRYPTOKI_FORCE_WIN32) #pragma pack(pop, cryptoki) #endif #if defined(__cplusplus) } #endif #endif /* PKCS11_H */ ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1704624694.0 pykcs11-1.5.17/src/pkcs11lib.cpp0000644000076500000240000005341314546501066015772 0ustar00rousseaustaff// Copyright (C) 2004 Midori (midori -- a-t -- paipai dot net) // Copyright (C) 2008-2014 Ludovic Rousseau // // This file is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program 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 // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. #include "stdafx.h" #include "pykcs11string.h" #include "ck_attribute_smart.h" #include "pkcs11lib.h" #include "utility.h" #include #include "dyn_generic.h" CPKCS11Lib::CPKCS11Lib(void): m_hLib(0), m_pFunc(NULL) { } CPKCS11Lib::~CPKCS11Lib(void) { } CK_RV CPKCS11Lib::Load(const char* szLib) { CK_RV rv; SYS_dyn_LoadLibrary((void**)&m_hLib, szLib); if (!m_hLib) return -1; CK_C_GetFunctionList pC_GetFunctionList; SYS_dyn_GetAddress(m_hLib, (function_ptr *)&pC_GetFunctionList, "C_GetFunctionList"); if (!pC_GetFunctionList) { SYS_dyn_CloseLibrary((void**)&m_hLib); return -4; } rv = pC_GetFunctionList(&m_pFunc); if (CKR_OK != rv || !m_pFunc) { SYS_dyn_CloseLibrary((void**)&m_hLib); return rv; } rv = m_pFunc->C_Initialize(NULL); if (CKR_OK != rv && CKR_CRYPTOKI_ALREADY_INITIALIZED != rv) return rv; return CKR_OK; } bool CPKCS11Lib::Unload() { bool bRes = false; if (m_hLib && m_pFunc) m_pFunc->C_Finalize(NULL); if (m_hLib) { bRes = true; SYS_dyn_CloseLibrary((void**)&m_hLib); } m_hLib = 0; m_pFunc = NULL; return bRes; } /* duplicate a reference to a library */ void CPKCS11Lib::Duplicate(CPKCS11Lib *ref) { m_hLib = ref->m_hLib; m_pFunc = ref->m_pFunc; } CK_RV CPKCS11Lib::C_Initialize() { CK_RV rv; rv = m_pFunc->C_Initialize(NULL); return rv; } CK_RV CPKCS11Lib::C_Finalize() { CK_RV rv; rv = m_pFunc->C_Finalize(NULL); return rv; } CK_RV CPKCS11Lib::C_GetInfo(CK_INFO* pInfo) { CK_RV rv; if (!m_pFunc) rv = CKR_CRYPTOKI_NOT_INITIALIZED; else rv = m_pFunc->C_GetInfo(pInfo); return rv; } CK_RV CPKCS11Lib::C_GetSlotList( unsigned char tokenPresent, vector& slotList) { CK_RV rv; CK_ULONG i; slotList.clear(); CK_ULONG ulSlotCount; rv = m_pFunc->C_GetSlotList(tokenPresent, NULL, &ulSlotCount); if (CKR_OK == rv) { CK_SLOT_ID_PTR ck_slotList; ck_slotList = (CK_SLOT_ID_PTR)malloc(ulSlotCount * sizeof(CK_SLOT_ID)); rv = m_pFunc->C_GetSlotList(tokenPresent, ck_slotList, &ulSlotCount); if (CKR_OK == rv) for(i=0; iC_GetSlotInfo(slotID, pInfo); return rv; } CK_RV CPKCS11Lib::C_GetTokenInfo ( CK_SLOT_ID slotID, CK_TOKEN_INFO* pInfo) { CK_RV rv; rv = m_pFunc->C_GetTokenInfo(slotID, pInfo); return rv; } CK_RV CPKCS11Lib::C_InitToken( CK_SLOT_ID slotID, vector pin, const char* pLabel) { CK_RV rv; CK_ULONG ulPinLen = 0; CK_BYTE* pPin = Vector2Buffer(pin, ulPinLen); rv = m_pFunc->C_InitToken(slotID, (CK_UTF8CHAR_PTR) pPin, ulPinLen, (CK_CHAR*)pLabel); return rv; } CK_RV CPKCS11Lib::C_InitPIN( CK_SESSION_HANDLE hSession, vector pin) { CK_RV rv; CK_ULONG ulPinLen = 0; CK_BYTE* pPin = Vector2Buffer(pin, ulPinLen); rv = m_pFunc->C_InitPIN(hSession, (CK_UTF8CHAR_PTR) pPin, ulPinLen); return rv; } CK_RV CPKCS11Lib::C_SetPIN( CK_SESSION_HANDLE hSession, vector OldPin, vector NewPin) { CK_RV rv; CK_ULONG ulOldLen = 0; CK_BYTE* pOldPin = Vector2Buffer(OldPin, ulOldLen); CK_ULONG ulNewLen = 0; CK_BYTE* pNewPin = Vector2Buffer(NewPin, ulNewLen); rv = m_pFunc->C_SetPIN(hSession, (CK_UTF8CHAR_PTR)pOldPin, ulOldLen, (CK_UTF8CHAR_PTR)pNewPin, ulNewLen); return rv; } CK_RV CPKCS11Lib::C_OpenSession( CK_SLOT_ID slotID, CK_FLAGS flags, CK_SESSION_HANDLE& outhSession) { CK_RV rv; rv = m_pFunc->C_OpenSession(slotID, flags, NULL, NULL, &outhSession); return rv; } CK_RV CPKCS11Lib::C_CloseSession( CK_SESSION_HANDLE hSession) { CK_RV rv; rv = m_pFunc->C_CloseSession(hSession); return rv; } CK_RV CPKCS11Lib::C_CloseAllSessions( CK_SLOT_ID slotID) { CK_RV rv; rv = m_pFunc->C_CloseAllSessions(slotID); return rv; } CK_RV CPKCS11Lib::C_GetSessionInfo( CK_SESSION_HANDLE hSession, CK_SESSION_INFO* pInfo) { CK_RV rv; rv = m_pFunc->C_GetSessionInfo(hSession, pInfo); return rv; } CK_RV CPKCS11Lib::C_Login( CK_SESSION_HANDLE hSession, CK_USER_TYPE userType, vector pin) { CK_RV rv; CK_ULONG ulPinLen = 0; CK_BYTE* pPin = Vector2Buffer(pin, ulPinLen); rv = m_pFunc->C_Login(hSession, userType, (CK_UTF8CHAR_PTR)pPin, ulPinLen); return rv; } CK_RV CPKCS11Lib::C_Logout( CK_SESSION_HANDLE hSession) { CK_RV rv; rv = m_pFunc->C_Logout(hSession); return rv; } CK_RV CPKCS11Lib::C_CreateObject( CK_SESSION_HANDLE hSession, vector Template, CK_OBJECT_HANDLE& outhObject) { CK_RV rv; CK_ULONG ulCount = 0; CK_OBJECT_HANDLE hObj = static_cast(outhObject); CK_ATTRIBUTE * pTemplate = AttrVector2Template(Template, ulCount); rv = m_pFunc->C_CreateObject(hSession, pTemplate, ulCount, &hObj); if (pTemplate) DestroyTemplate(pTemplate, ulCount); outhObject = static_cast(hObj); return rv; } CK_RV CPKCS11Lib::C_DestroyObject( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject) { CK_RV rv; rv = m_pFunc->C_DestroyObject(hSession, (CK_OBJECT_HANDLE)hObject); return rv; } CK_RV CPKCS11Lib::C_GetObjectSize( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ULONG* pulSize) { CK_RV rv; rv = m_pFunc->C_GetObjectSize(hSession, (CK_OBJECT_HANDLE)hObject, pulSize); return rv; } CK_RV CPKCS11Lib::C_GetAttributeValue ( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, vector &Template) { CK_RV rv; CK_ULONG ulCount = 0, i; CK_ATTRIBUTE * pTemplate = AttrVector2Template(Template, ulCount); rv = m_pFunc->C_GetAttributeValue(hSession, (CK_OBJECT_HANDLE)hObject, pTemplate, ulCount); for (i=0; i Template) { CK_RV rv; CK_ULONG ulCount = 0; CK_ATTRIBUTE * pTemplate = AttrVector2Template(Template, ulCount); rv = m_pFunc->C_SetAttributeValue(hSession, (CK_OBJECT_HANDLE)hObject, pTemplate, ulCount); if (pTemplate) DestroyTemplate(pTemplate, ulCount); return rv; } CK_RV CPKCS11Lib::C_FindObjectsInit( CK_SESSION_HANDLE hSession, vector &Template) { CK_RV rv; CK_ULONG ulCount = 0; CK_ATTRIBUTE * pTemplate = AttrVector2Template(Template, ulCount); rv = m_pFunc->C_FindObjectsInit(hSession, pTemplate, ulCount); if (pTemplate) DestroyTemplate(pTemplate, ulCount); return rv; } CK_RV CPKCS11Lib::C_FindObjects( CK_SESSION_HANDLE hSession, vector& objectList) { CK_RV rv; CK_ULONG i; if (!objectList.size()) return CKR_ARGUMENTS_BAD; CK_ULONG ulObjectsMax = (CK_ULONG) objectList.size(); CK_ULONG ulObjects = 0; CK_OBJECT_HANDLE_PTR pList = new CK_OBJECT_HANDLE[ulObjectsMax]; objectList.clear(); rv = m_pFunc->C_FindObjects(hSession, pList, ulObjectsMax, &ulObjects); if (CKR_OK == rv && ulObjects) { for (i=0; i(pList[i])); } if (pList) delete [] pList; return rv; } CK_RV CPKCS11Lib::C_FindObjectsFinal( CK_SESSION_HANDLE hSession) { CK_RV rv; rv = m_pFunc->C_FindObjectsFinal(hSession); return rv; } CK_RV CPKCS11Lib::C_EncryptInit( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, CK_OBJECT_HANDLE hKey) { CK_RV rv; rv = m_pFunc->C_EncryptInit(hSession, pMechanism, (CK_OBJECT_HANDLE)hKey); return rv; } CK_RV CPKCS11Lib::C_Encrypt( CK_SESSION_HANDLE hSession, vector inData, vector &outEncryptedData) { CK_RV rv; if (!inData.size()) return CKR_ARGUMENTS_BAD; CK_ULONG ulInDataLen = 0; CK_BYTE* pInData = Vector2Buffer(inData, ulInDataLen); CK_ULONG ulOutDataLen = 0; CK_BYTE* pOutData = Vector2Buffer(outEncryptedData, ulOutDataLen); rv = m_pFunc->C_Encrypt(hSession, pInData, ulInDataLen, pOutData, &ulOutDataLen); if (CKR_OK == rv) Buffer2Vector(pOutData, ulOutDataLen, outEncryptedData, true); if (pOutData) delete []pOutData; if (pInData) delete []pInData; return rv; } CK_RV CPKCS11Lib::C_EncryptUpdate( CK_SESSION_HANDLE hSession, vector inData, vector &outEncryptedData) { CK_RV rv; if (!inData.size()) return CKR_ARGUMENTS_BAD; CK_ULONG ulInDataLen = 0; CK_BYTE* pInData = Vector2Buffer(inData, ulInDataLen); CK_ULONG ulOutDataLen = 0; CK_BYTE* pOutData = Vector2Buffer(outEncryptedData, ulOutDataLen); rv = m_pFunc->C_EncryptUpdate(hSession, pInData, ulInDataLen, pOutData, &ulOutDataLen); if (CKR_OK == rv) Buffer2Vector(pOutData, ulOutDataLen, outEncryptedData, true); if (pOutData) delete []pOutData; if (pInData) delete []pInData; return rv; } CK_RV CPKCS11Lib::C_EncryptFinal( CK_SESSION_HANDLE hSession, vector &outEncryptedData) { CK_RV rv; CK_ULONG ulOutDataLen = 0; CK_BYTE* pOutData = Vector2Buffer(outEncryptedData, ulOutDataLen); rv = m_pFunc->C_EncryptFinal(hSession, pOutData, &ulOutDataLen); if (CKR_OK == rv) Buffer2Vector(pOutData, ulOutDataLen, outEncryptedData, true); if (pOutData) delete []pOutData; return rv; } CK_RV CPKCS11Lib::C_DecryptInit( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, CK_OBJECT_HANDLE hKey) { CK_RV rv; rv = m_pFunc->C_DecryptInit(hSession, pMechanism, (CK_OBJECT_HANDLE)hKey); return rv; } CK_RV CPKCS11Lib::C_Decrypt( CK_SESSION_HANDLE hSession, vector inEncryptedData, vector &outData) { CK_RV rv; if (!inEncryptedData.size()) return CKR_ARGUMENTS_BAD; CK_ULONG ulInDataLen = 0; CK_BYTE* pInData = Vector2Buffer(inEncryptedData, ulInDataLen); CK_ULONG ulOutDataLen = 0; CK_BYTE* pOutData = Vector2Buffer(outData, ulOutDataLen); rv = m_pFunc->C_Decrypt(hSession, pInData, ulInDataLen, pOutData, &ulOutDataLen); if (CKR_OK == rv) Buffer2Vector(pOutData, ulOutDataLen, outData, true); if (pOutData) delete []pOutData; if (pInData) delete []pInData; return rv; } CK_RV CPKCS11Lib::C_DecryptUpdate( CK_SESSION_HANDLE hSession, vector inEncryptedData, vector &outData) { CK_RV rv; if (!inEncryptedData.size()) return CKR_ARGUMENTS_BAD; CK_ULONG ulInDataLen = 0; CK_BYTE* pInData = Vector2Buffer(inEncryptedData, ulInDataLen); CK_ULONG ulOutDataLen = 0; CK_BYTE* pOutData = Vector2Buffer(outData, ulOutDataLen); rv = m_pFunc->C_DecryptUpdate(hSession, pInData, ulInDataLen, pOutData, &ulOutDataLen); if (CKR_OK == rv) Buffer2Vector(pOutData, ulOutDataLen, outData, true); if (pOutData) delete []pOutData; if (pInData) delete []pInData; return rv; } CK_RV CPKCS11Lib::C_DecryptFinal( CK_SESSION_HANDLE hSession, vector &outData) { CK_RV rv; CK_ULONG ulOutDataLen = 0; CK_BYTE* pOutData = Vector2Buffer(outData, ulOutDataLen); rv = m_pFunc->C_DecryptFinal(hSession, pOutData, &ulOutDataLen); if (CKR_OK == rv) Buffer2Vector(pOutData, ulOutDataLen, outData, true); if (pOutData) delete []pOutData; return rv; } CK_RV CPKCS11Lib::C_DigestInit( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism) { CK_RV rv; rv = m_pFunc->C_DigestInit(hSession, pMechanism); return rv; } CK_RV CPKCS11Lib::C_Digest( CK_SESSION_HANDLE hSession, vector inData, vector &outDigest) { CK_RV rv; if (!inData.size()) return CKR_ARGUMENTS_BAD; CK_ULONG ulInDataLen = 0; CK_BYTE* pInData = Vector2Buffer(inData, ulInDataLen); CK_ULONG ulOutDataLen = 0; CK_BYTE* pOutData = Vector2Buffer(outDigest, ulOutDataLen); rv = m_pFunc->C_Digest(hSession, pInData, ulInDataLen, pOutData, &ulOutDataLen); if (CKR_OK == rv) Buffer2Vector(pOutData, ulOutDataLen, outDigest, true); if (pOutData) delete []pOutData; if (pInData) delete []pInData; return rv; } CK_RV CPKCS11Lib::C_DigestUpdate( CK_SESSION_HANDLE hSession, vector inData) { CK_RV rv; if (!inData.size()) return CKR_ARGUMENTS_BAD; CK_ULONG ulInDataLen = 0; CK_BYTE* pInData = Vector2Buffer(inData, ulInDataLen); rv = m_pFunc->C_DigestUpdate(hSession, pInData, ulInDataLen); if (pInData) delete []pInData; return rv; } CK_RV CPKCS11Lib::C_DigestKey ( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey) { CK_RV rv; rv = m_pFunc->C_DigestKey(hSession, (CK_OBJECT_HANDLE)hKey); return rv; } CK_RV CPKCS11Lib::C_DigestFinal( CK_SESSION_HANDLE hSession, vector &outDigest) { CK_RV rv; CK_ULONG ulOutDataLen = 0; CK_BYTE* pOutData = Vector2Buffer(outDigest, ulOutDataLen); rv = m_pFunc->C_DigestFinal(hSession, pOutData, &ulOutDataLen); if (CKR_OK == rv) Buffer2Vector(pOutData, ulOutDataLen, outDigest, true); if (pOutData) delete []pOutData; return rv; } CK_RV CPKCS11Lib::C_SignInit( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, CK_OBJECT_HANDLE hKey) { CK_RV rv; rv = m_pFunc->C_SignInit(hSession, pMechanism, (CK_OBJECT_HANDLE)hKey); return rv; } CK_RV CPKCS11Lib::C_Sign( CK_SESSION_HANDLE hSession, vector inData, vector &outSignature) { CK_RV rv; if (!inData.size()) return CKR_ARGUMENTS_BAD; CK_ULONG ulInDataLen = 0; CK_BYTE* pInData = Vector2Buffer(inData, ulInDataLen); CK_ULONG ulOutDataLen = 0; CK_BYTE* pOutData = Vector2Buffer(outSignature, ulOutDataLen); rv = m_pFunc->C_Sign(hSession, pInData, ulInDataLen, pOutData, &ulOutDataLen); if (CKR_OK == rv) Buffer2Vector(pOutData, ulOutDataLen, outSignature, true); if (pOutData) delete []pOutData; if (pInData) delete []pInData; return rv; } CK_RV CPKCS11Lib::C_SignUpdate( CK_SESSION_HANDLE hSession, vector inData) { CK_RV rv; if (!inData.size()) return CKR_ARGUMENTS_BAD; CK_ULONG ulInDataLen = 0; CK_BYTE* pInData = Vector2Buffer(inData, ulInDataLen); rv = m_pFunc->C_SignUpdate(hSession, pInData, ulInDataLen); if (pInData) delete []pInData; return rv; } CK_RV CPKCS11Lib::C_SignFinal ( CK_SESSION_HANDLE hSession, vector &outSignature) { CK_RV rv; CK_ULONG ulOutDataLen = 0; CK_BYTE* pOutData = Vector2Buffer(outSignature, ulOutDataLen); rv = m_pFunc->C_SignFinal(hSession, pOutData, &ulOutDataLen); if (CKR_OK == rv) Buffer2Vector(pOutData, ulOutDataLen, outSignature, true); if (pOutData) delete []pOutData; return rv; } CK_RV CPKCS11Lib::C_VerifyInit ( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, CK_OBJECT_HANDLE hKey) { CK_RV rv; rv = m_pFunc->C_VerifyInit(hSession, pMechanism, (CK_OBJECT_HANDLE)hKey); return rv; } CK_RV CPKCS11Lib::C_Verify( CK_SESSION_HANDLE hSession, vector inData, vector inSignature) { CK_RV rv; if (!inData.size()) return CKR_ARGUMENTS_BAD; if (!inSignature.size()) return CKR_ARGUMENTS_BAD; CK_ULONG ulInDataLen = 0; CK_BYTE* pInData = Vector2Buffer(inData, ulInDataLen); CK_ULONG ulInSignatureLen = 0; CK_BYTE* pInSignature = Vector2Buffer(inSignature, ulInSignatureLen); rv = m_pFunc->C_Verify(hSession, pInData, ulInDataLen, pInSignature, ulInSignatureLen); if (pInData) delete []pInData; if (pInSignature) delete []pInSignature; return rv; } CK_RV CPKCS11Lib::C_VerifyUpdate( CK_SESSION_HANDLE hSession, vector inData) { CK_RV rv; if (!inData.size()) return CKR_ARGUMENTS_BAD; CK_ULONG ulInDataLen = 0; CK_BYTE* pInData = Vector2Buffer(inData, ulInDataLen); rv = m_pFunc->C_VerifyUpdate(hSession, pInData, ulInDataLen); if (pInData) delete []pInData; return rv; } CK_RV CPKCS11Lib::C_VerifyFinal( CK_SESSION_HANDLE hSession, vector inSignature) { CK_RV rv; if (!inSignature.size()) return CKR_ARGUMENTS_BAD; CK_ULONG ulInSignatureLen = 0; CK_BYTE* pInSignature = Vector2Buffer(inSignature, ulInSignatureLen); rv = m_pFunc->C_VerifyFinal(hSession, pInSignature, ulInSignatureLen); if (pInSignature) delete []pInSignature; return rv; } CK_RV CPKCS11Lib::C_GenerateKey( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, vector Template, CK_OBJECT_HANDLE& outhKey) { CK_RV rv; CK_ULONG ulCount = 0; CK_OBJECT_HANDLE hKey = static_cast(outhKey); CK_ATTRIBUTE * pTemplate = AttrVector2Template(Template, ulCount); rv = m_pFunc->C_GenerateKey(hSession, pMechanism, pTemplate, ulCount, &hKey); if (pTemplate) DestroyTemplate(pTemplate, ulCount); outhKey = static_cast(hKey); return rv; } CK_RV CPKCS11Lib::C_GenerateKeyPair( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, vector PublicKeyTemplate, vector PrivateKeyTemplate, CK_OBJECT_HANDLE& outhPublicKey, CK_OBJECT_HANDLE& outhPrivateKey) { CK_RV rv; CK_ULONG ulPublicKeyAttributeCount = 0, ulPrivateKeyAttributeCount = 0; CK_OBJECT_HANDLE hPublicKey = static_cast(outhPublicKey); CK_OBJECT_HANDLE hPrivateKey = static_cast(outhPrivateKey); CK_ATTRIBUTE * pPublicKeyTemplate = AttrVector2Template(PublicKeyTemplate, ulPublicKeyAttributeCount); CK_ATTRIBUTE * pPrivateKeyTemplate = AttrVector2Template(PrivateKeyTemplate, ulPrivateKeyAttributeCount); rv = m_pFunc->C_GenerateKeyPair(hSession, pMechanism, pPublicKeyTemplate, ulPublicKeyAttributeCount, pPrivateKeyTemplate, ulPrivateKeyAttributeCount, &hPublicKey, &hPrivateKey); if (pPublicKeyTemplate) DestroyTemplate(pPublicKeyTemplate, ulPublicKeyAttributeCount); if (pPrivateKeyTemplate) DestroyTemplate(pPrivateKeyTemplate, ulPrivateKeyAttributeCount); outhPublicKey = static_cast(hPublicKey); outhPrivateKey = static_cast(hPrivateKey); return rv; } CK_RV CPKCS11Lib::C_WrapKey( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, CK_OBJECT_HANDLE hWrappingKey, CK_OBJECT_HANDLE hKey, vector &WrappedKey) { CK_RV rv; CK_ULONG ulOutDataLen = 0; CK_BYTE* pOutData = Vector2Buffer(WrappedKey, ulOutDataLen); rv = m_pFunc->C_WrapKey(hSession, pMechanism, (CK_OBJECT_HANDLE)hWrappingKey, (CK_OBJECT_HANDLE)hKey, pOutData, &ulOutDataLen); if (CKR_OK == rv) Buffer2Vector(pOutData, ulOutDataLen, WrappedKey, true); if (pOutData) delete []pOutData; return rv; } CK_RV CPKCS11Lib::C_UnwrapKey( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, CK_OBJECT_HANDLE hUnwrappingKey, vector WrappedKey, vector Template, CK_OBJECT_HANDLE& outhKey) { CK_RV rv; CK_OBJECT_HANDLE hKey = static_cast(outhKey); if (!WrappedKey.size()) return CKR_ARGUMENTS_BAD; CK_ULONG ulInDataLen = 0; CK_BYTE* pInData = Vector2Buffer(WrappedKey, ulInDataLen); CK_ULONG ulAttributeCount = 0; CK_ATTRIBUTE* pTemplate = AttrVector2Template(Template, ulAttributeCount); rv = m_pFunc->C_UnwrapKey(hSession, pMechanism, (CK_OBJECT_HANDLE)hUnwrappingKey, pInData, ulInDataLen, pTemplate, ulAttributeCount, &hKey); if (pInData) delete []pInData; if (pTemplate) DestroyTemplate(pTemplate, ulAttributeCount); outhKey = static_cast(hKey); return rv; } CK_RV CPKCS11Lib::C_DeriveKey( CK_SESSION_HANDLE hSession, CK_MECHANISM *pMechanism, CK_OBJECT_HANDLE hBaseKey, vector Template, CK_OBJECT_HANDLE & outKey) { CK_RV rv; CK_OBJECT_HANDLE hKey = static_cast(outKey); CK_ULONG ulAttributeCount = 0; CK_ATTRIBUTE* pTemplate = AttrVector2Template(Template, ulAttributeCount); rv = m_pFunc->C_DeriveKey(hSession, pMechanism, hBaseKey, pTemplate, ulAttributeCount, &hKey); if (pTemplate) DestroyTemplate(pTemplate, ulAttributeCount); outKey = static_cast(hKey); return rv; } CK_RV CPKCS11Lib::C_SeedRandom( CK_SESSION_HANDLE hSession, vector Seed) { CK_RV rv; CK_ULONG ulInDataLen = 0; CK_BYTE* pInData = Vector2Buffer(Seed, ulInDataLen); rv = m_pFunc->C_SeedRandom(hSession, pInData, ulInDataLen); if (pInData) delete []pInData; return rv; } CK_RV CPKCS11Lib::C_GenerateRandom( CK_SESSION_HANDLE hSession, vector &RandomData) { CK_RV rv; CK_ULONG ulOutDataLen = 0; CK_BYTE* pOutData = Vector2Buffer(RandomData, ulOutDataLen); rv = m_pFunc->C_GenerateRandom(hSession, pOutData, ulOutDataLen); if (CKR_OK == rv) Buffer2Vector(pOutData, ulOutDataLen, RandomData, true); if (pOutData) delete []pOutData; return rv; } CK_RV CPKCS11Lib::C_WaitForSlotEvent( CK_FLAGS flags, unsigned long* pSlot) { CK_RV rv; rv = m_pFunc->C_WaitForSlotEvent(flags, pSlot, NULL); return rv; } CK_RV CPKCS11Lib::C_GetMechanismList( unsigned long slotID, vector &mechanismList) { CK_RV rv; CK_ULONG i; mechanismList.clear(); CK_MECHANISM_TYPE ck_mechanismList[1024]; CK_ULONG ulCount = sizeof(ck_mechanismList)/sizeof(ck_mechanismList[0]); rv = m_pFunc->C_GetMechanismList(slotID, ck_mechanismList, &ulCount); if (CKR_OK == rv) for(i=0; iC_GetMechanismInfo(slotID, type, pInfo); return rv; } /////////////////////////////////////////////////////////////////////////////// ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1704624694.0 pykcs11-1.5.17/src/pkcs11lib.h0000644000076500000240000001611514546501066015435 0ustar00rousseaustaff// Copyright (C) 2004 Midori (midori -- a-t -- paipai dot net) // Copyright (C) 2008-2010 Ludovic Rousseau // // This file is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program 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 // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. #pragma once #ifdef SWIG //#define CK_OBJECT_HANDLE unsigned long //#define CK_SESSION_HANDLE unsigned long #else typedef CK_ATTRIBUTE CK_ATTRIBUTE_INTERNAL; #ifdef WIN32 #pragma warning(disable: 4800 4244) #include #endif #include using namespace std; #endif class CPKCS11Lib { #ifdef WIN32 HMODULE m_hLib; #else void *m_hLib; #endif CK_FUNCTION_LIST* m_pFunc; public: CPKCS11Lib(void); ~CPKCS11Lib(void); CK_RV Load(const char* szLib); bool Unload(); void Duplicate(CPKCS11Lib *ref); CK_RV C_Initialize(); CK_RV C_Finalize(); CK_RV C_GetInfo(CK_INFO* pInfo); CK_RV C_GetSlotList(unsigned char tokenPresent, vector& slotList); CK_RV C_GetSlotInfo(unsigned long slotID,CK_SLOT_INFO* pInfo); CK_RV C_GetTokenInfo(unsigned long slotID,CK_TOKEN_INFO* pInfo); #ifdef SWIG %apply (char *STRING, int LENGTH) { (char* pPin, unsigned long ulPinLen), (char* pOldPin, unsigned long ulOldLen), (char* pNewPin, unsigned long ulNewLen) }; %apply (char *STRING) { (char* pLabel) }; #endif CK_RV C_InitToken(unsigned long slotID, vector pin, const char* pLabel); CK_RV C_InitPIN( CK_SESSION_HANDLE hSession, vector pin); CK_RV C_SetPIN( CK_SESSION_HANDLE hSession, vector OldPin, vector NewPin); CK_RV C_OpenSession( unsigned long slotID, unsigned long flags, CK_SESSION_HANDLE& outhSession); CK_RV C_CloseSession(CK_SESSION_HANDLE hSession); CK_RV C_CloseAllSessions(unsigned long slotID); CK_RV C_GetSessionInfo( CK_SESSION_HANDLE hSession, CK_SESSION_INFO* pInfo); CK_RV C_Login( CK_SESSION_HANDLE hSession, unsigned long userType, vector pin); #ifdef SWIG %clear (char* pPin, unsigned long ulPinLen), (char* pOldPin, unsigned long ulOldLen), (char* pNewPin, unsigned long ulNewLen) ; %clear (char* pLabel); #endif CK_RV C_Logout(CK_SESSION_HANDLE hSession); CK_RV C_CreateObject( CK_SESSION_HANDLE hSession, vector Template, CK_OBJECT_HANDLE& outhObject); CK_RV C_DestroyObject( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject); CK_RV C_GetObjectSize( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, unsigned long* pulSize); CK_RV C_GetAttributeValue( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, vector &Template); CK_RV C_SetAttributeValue( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, vector Template); CK_RV C_FindObjectsInit( CK_SESSION_HANDLE hSession, vector &Template); CK_RV C_FindObjects( CK_SESSION_HANDLE hSession, vector &objectsList); CK_RV C_FindObjectsFinal(CK_SESSION_HANDLE hSession); CK_RV C_EncryptInit( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, CK_OBJECT_HANDLE hKey); CK_RV C_Encrypt( CK_SESSION_HANDLE hSession, vector inData, vector &outEncryptedData); CK_RV C_EncryptUpdate( CK_SESSION_HANDLE hSession, vector inData, vector &outEncryptedData); CK_RV C_EncryptFinal( CK_SESSION_HANDLE hSession, vector &outEncryptedData); CK_RV C_DecryptInit( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, CK_OBJECT_HANDLE hKey); CK_RV C_Decrypt( CK_SESSION_HANDLE hSession, vector inEncryptedData, vector &outData); CK_RV C_DecryptUpdate( CK_SESSION_HANDLE hSession, vector inEncryptedData, vector &outData); CK_RV C_DecryptFinal( CK_SESSION_HANDLE hSession, vector &outData); CK_RV C_DigestInit( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism); CK_RV C_Digest( CK_SESSION_HANDLE hSession, vector inData, vector &outDigest); CK_RV C_DigestUpdate( CK_SESSION_HANDLE hSession, vector inData); CK_RV C_DigestKey( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey); CK_RV C_DigestFinal( CK_SESSION_HANDLE hSession, vector &outDigest); CK_RV C_SignInit( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, CK_OBJECT_HANDLE hKey); CK_RV C_Sign( CK_SESSION_HANDLE hSession, vector inData, vector &outSignature); CK_RV C_SignUpdate( CK_SESSION_HANDLE hSession, vector inData); CK_RV C_SignFinal( CK_SESSION_HANDLE hSession, vector &outSignature); CK_RV C_VerifyInit( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, CK_OBJECT_HANDLE hKey); CK_RV C_Verify( CK_SESSION_HANDLE hSession, vector inData, vector inSignature); CK_RV C_VerifyUpdate( CK_SESSION_HANDLE hSession, vector inData); CK_RV C_VerifyFinal( CK_SESSION_HANDLE hSession, vector inSignature); CK_RV C_GenerateKey( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, vector Template, CK_OBJECT_HANDLE & outhKey); CK_RV C_GenerateKeyPair( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, vector PublicKeyTemplate, vector PrivateKeyTemplate, CK_OBJECT_HANDLE& outhPublicKey, CK_OBJECT_HANDLE& outhPrivateKey ); CK_RV C_WrapKey( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, CK_OBJECT_HANDLE hWrappingKey, CK_OBJECT_HANDLE hKey, vector &WrappedKey); CK_RV C_UnwrapKey( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, CK_OBJECT_HANDLE hUnwrappingKey, vector WrappedKey, vector Template, CK_OBJECT_HANDLE & outhKey); CK_RV C_DeriveKey( CK_SESSION_HANDLE hSession, CK_MECHANISM *pMechanism, CK_OBJECT_HANDLE hBaseKey, vector Template, CK_OBJECT_HANDLE & outkey); CK_RV C_SeedRandom( CK_SESSION_HANDLE hSession, vector Seed); CK_RV C_GenerateRandom( CK_SESSION_HANDLE hSession, vector &RandomData); CK_RV C_WaitForSlotEvent( unsigned long flags, unsigned long * INOUT); CK_RV C_GetMechanismList( unsigned long slotID, vector &mechanismList); CK_RV C_GetMechanismInfo( unsigned long slotID, unsigned long type, CK_MECHANISM_INFO* pInfo); }; ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1704624376.0 pykcs11-1.5.17/src/pykcs11.cpp0000644000076500000240000000210714546500370015463 0ustar00rousseaustaff// Copyright (C) 2004 Midori (midori -- a-t -- paipai dot net) // // This file is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program 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 // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. // PyKCS11.cpp : Defines the entry point for the DLL application. // #include "stdafx.h" #if defined(WIN32) || defined(_WIN32) #include BOOL WINAPI DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { return TRUE; } #endif ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1723063758.0 pykcs11-1.5.17/src/pykcs11.i0000644000076500000240000015104214654756716015155 0ustar00rousseaustaff// Copyright (C) 2004 Midori (midori -- a-t -- paipai dot net) // // This file is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program 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 // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. %module LowLevel %{ #include #include #include #include "opensc/pkcs11.h" #ifdef WIN32 #pragma warning(disable: 4800 4244) #endif #include #include "pykcs11string.h" #include "ck_attribute_smart.h" #include "pkcs11lib.h" using namespace std; %} %inline %{ using namespace std; %} %include cdata.i %include cpointer.i %include typemaps.i %include std_vector.i %template(ckintlist) vector; %template(ckbytelist) vector; %template(ckattrlist) vector; %template(ckobjlist) vector; %pointer_class(unsigned long, CK_SESSION_HANDLE); %pointer_class(unsigned long, CK_OBJECT_HANDLE); #if SWIGPYTHON %typemap(out) PyKCS11String { #ifdef Py_USING_UNICODE $result = PyBytes_FromStringAndSize((const char*)($1.m_str.c_str()),(int)($1.m_str.size())); #else $result = PyUnicode_Decode((const char*)($1.m_str.c_str()),(int)($1.m_str.size()), "utf-8", "ignore"); #endif } %typemap(out) CK_RV { $result = PyInt_FromLong((long)$1); } #else #endif typedef struct CK_VERSION { %immutable; unsigned char major; unsigned char minor; %mutable; } CK_VERSION; typedef struct CK_INFO { %immutable; CK_VERSION cryptokiVersion; unsigned char manufacturerID[32]; unsigned long flags; unsigned char libraryDescription[32]; CK_VERSION libraryVersion; %mutable; } CK_INFO; %extend CK_INFO { PyKCS11String GetManufacturerID() { return PyKCS11String(self->manufacturerID, sizeof(self->manufacturerID)); } PyKCS11String GetLibraryDescription() { return PyKCS11String(self->libraryDescription, sizeof(self->libraryDescription)); } PyKCS11String GetLibraryVersion() { char szVal[10]; snprintf(szVal, sizeof szVal, "%d.%d", self->libraryVersion.major, self->libraryVersion.minor); return PyKCS11String(szVal); } }; typedef struct CK_SLOT_INFO { %immutable; //unsigned char slotDescription[64]; //unsigned char manufacturerID[32]; unsigned long flags; CK_VERSION hardwareVersion; CK_VERSION firmwareVersion; %mutable; } CK_SLOT_INFO; %extend CK_SLOT_INFO { PyKCS11String GetManufacturerID() { return PyKCS11String(self->manufacturerID, sizeof(self->manufacturerID)); } PyKCS11String GetSlotDescription() { return PyKCS11String(self->slotDescription, sizeof(self->slotDescription)); } PyKCS11String GetHardwareVersion() { char szVal[10]; snprintf(szVal, sizeof szVal, "%d.%02d", self->hardwareVersion.major, self->hardwareVersion.minor); return PyKCS11String(szVal); } PyKCS11String GetFirmwareVersion() { char szVal[10]; snprintf(szVal, sizeof szVal, "%d.%02d", self->firmwareVersion.major, self->firmwareVersion.minor); return PyKCS11String(szVal); } }; typedef struct CK_TOKEN_INFO { %immutable; //unsigned char label[32]; //unsigned char manufacturerID[32]; //unsigned char model[16]; //unsigned char serialNumber[16]; unsigned long flags; unsigned long ulMaxSessionCount; unsigned long ulSessionCount; unsigned long ulMaxRwSessionCount; unsigned long ulRwSessionCount; unsigned long ulMaxPinLen; unsigned long ulMinPinLen; unsigned long ulTotalPublicMemory; unsigned long ulFreePublicMemory; unsigned long ulTotalPrivateMemory; unsigned long ulFreePrivateMemory; CK_VERSION hardwareVersion; CK_VERSION firmwareVersion; //unsigned char utcTime[16]; %mutable; } CK_TOKEN_INFO; %extend CK_TOKEN_INFO { PyKCS11String GetLabel() { return PyKCS11String(self->label, sizeof(self->label)); } PyKCS11String GetManufacturerID() { return PyKCS11String(self->manufacturerID, sizeof(self->manufacturerID)); } PyKCS11String GetModel() { return PyKCS11String(self->model, sizeof(self->model)); } PyKCS11String GetSerialNumber() { return PyKCS11String(self->serialNumber, sizeof(self->serialNumber)); } PyKCS11String GetFirmwareVersion() { char szVal[10]; snprintf(szVal, sizeof szVal, "%d.%02d", self->firmwareVersion.major, self->firmwareVersion.minor); return PyKCS11String(szVal); } PyKCS11String GetUtcTime() { return PyKCS11String(self->utcTime, sizeof(self->utcTime)); } }; typedef struct CK_SESSION_INFO { %immutable; unsigned long slotID; unsigned long state; unsigned long flags; unsigned long ulDeviceError; %mutable; } CK_SESSION_INFO; typedef struct CK_DATE{ //unsigned char year[4]; //unsigned char month[2]; // unsigned char day[2]; } CK_DATE; %extend CK_DATE { PyKCS11String GetYear() { char szVal[10]; memcpy(szVal, self->year, sizeof(self->year) ); return PyKCS11String(szVal); } PyKCS11String GetMonth() { char szVal[10]; memcpy(szVal, self->month, sizeof(self->month) ); return PyKCS11String(szVal); } PyKCS11String GetDay() { char szVal[10]; memcpy(szVal, self->day, sizeof(self->day) ); return PyKCS11String(szVal); } }; %typemap(in) void* { vector *vect; // If the value being set is of ckbytelist type: if (SWIG_IsOK(SWIG_ConvertPtr($input, (void **)&vect, $descriptor(vector *), 0))) { // Get the data from the vector // Only set value if not null if (vect) arg2 = vect->data(); else arg2 = NULL; } else { // If the value isn't a ckbytelist, then it must be a pointer to a mechanism parameter int res2 = -1; do { // Add mechanism parameters here res2 = SWIG_ConvertPtr($input, &arg2, $descriptor(CK_RSA_PKCS_OAEP_PARAMS*), 0); if( SWIG_IsOK( res2 ) ) break; res2 = SWIG_ConvertPtr($input, &arg2, $descriptor(CK_RSA_PKCS_PSS_PARAMS*), 0); if( SWIG_IsOK( res2 ) ) break; res2 = SWIG_ConvertPtr($input, &arg2, $descriptor(CK_GCM_PARAMS*), 0); if( SWIG_IsOK( res2 ) ) break; res2 = SWIG_ConvertPtr($input, &arg2, $descriptor(CK_ECDH1_DERIVE_PARAMS*), 0); if( SWIG_IsOK( res2 ) ) break; res2 = SWIG_ConvertPtr($input, &arg2, $descriptor(CK_AES_CTR_PARAMS*), 0); if( SWIG_IsOK( res2 ) ) break; res2 = SWIG_ConvertPtr($input, &arg2, $descriptor(CK_KEY_DERIVATION_STRING_DATA*), 0); if( SWIG_IsOK( res2 ) ) break; res2 = SWIG_ConvertPtr($input, &arg2, $descriptor(CK_OBJECT_HANDLE*), 0); if( SWIG_IsOK( res2 ) ) break; } while(0); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "unsupported CK_MECHANISM Parameter type."); } } } // typemap for CK_BYTE_PTR (unsigned char*) mechanism parameters %typemap(in) unsigned char* { vector *vect; // If the value being set is of ckbytelist type: int res = SWIG_ConvertPtr($input, (void **)&vect, $descriptor(vector *), 0); if (SWIG_IsOK(res)) { // Get the data from the vector // Only set value if not null if (vect) arg2 = vect->data(); else arg2 = NULL; } else { // If a mechanism parameter has a 'CK_BYTE_PTR' as a member, it must be represented as a ckbytelist SWIG_exception_fail(SWIG_ArgError(res), "CK_BYTE_PTR members of CK_* mechanism params must be represented as ckbytelist type"); } } // typemap for CK_BYTE static arrays %typemap(in) unsigned char[ANY](unsigned char out[$1_dim0]) { vector *vect; // Expect a value of ckbytelist type: int res = SWIG_ConvertPtr($input, (void **)&vect, $descriptor(vector *), 0); if (SWIG_IsOK(res)) { if (vect->size() != $1_dim0) { SWIG_exception_fail(SWIG_ValueError, "Expected a ckbytelist with $1_dim0 elements"); } for (size_t i = 0; i < $1_dim0; i++) { out[i] = (*vect)[i]; } } else { // If a mechanism parameter has a CK_BYTE array as a member, it must be represented as a ckbytelist SWIG_exception_fail(SWIG_ArgError(res), "CK_BYTE arrays of CK_* mechanism params must be represented as ckbytelist type"); } $1 = &out[0]; } typedef struct CK_MECHANISM { unsigned long mechanism; void* pParameter; unsigned long ulParameterLen; } CK_MECHANISM; %extend CK_MECHANISM { CK_MECHANISM() { CK_MECHANISM* m = new CK_MECHANISM(); m->ulParameterLen = m->mechanism = 0; m->pParameter = NULL; return m; } }; // For all complex mechanism parameters which has 'void *' as a member, it must a ckbytelist %typemap(in) void* { vector *vect; int res = SWIG_ConvertPtr($input, (void **)&vect, $descriptor(vector *), 0); if (SWIG_IsOK(res)) { // Get the data from the vector // Only set value if not null if (vect) arg2 = vect->data(); else arg2 = NULL; } else { SWIG_exception_fail(SWIG_ArgError(res), "void * members of CK_* mechanism params must be represented as ckbytelist type"); } } %constant int CK_OBJECT_HANDLE_LENGTH = sizeof(CK_OBJECT_HANDLE); typedef struct CK_GCM_PARAMS { void * pIv; unsigned long ulIvLen; void * pAAD; unsigned long ulAADLen; unsigned long ulTagBits; } CK_GCM_PARAMS; %extend CK_GCM_PARAMS { CK_GCM_PARAMS() { CK_GCM_PARAMS *p = new CK_GCM_PARAMS(); p->pIv = p->pAAD = NULL; p->ulIvLen = p->ulAADLen = p->ulTagBits = 0; return p; } }; %constant int CK_GCM_PARAMS_LENGTH = sizeof(CK_GCM_PARAMS); typedef struct CK_AES_CTR_PARAMS { unsigned long ulCounterBits; unsigned char cb[16]; } CK_AES_CTR_PARAMS; %extend CK_AES_CTR_PARAMS { CK_AES_CTR_PARAMS() { CK_AES_CTR_PARAMS *p = new CK_AES_CTR_PARAMS(); p->ulCounterBits = 128; memset(p->cb, 0, sizeof(p->cb)); return p; } }; %constant int CK_AES_CTR_PARAMS_LENGTH = sizeof(CK_AES_CTR_PARAMS); typedef struct CK_RSA_PKCS_OAEP_PARAMS { unsigned long hashAlg; unsigned long mgf; unsigned long src; void* pSourceData; unsigned long ulSourceDataLen; } CK_RSA_PKCS_OAEP_PARAMS; %extend CK_RSA_PKCS_OAEP_PARAMS { CK_RSA_PKCS_OAEP_PARAMS() { CK_RSA_PKCS_OAEP_PARAMS* p = new CK_RSA_PKCS_OAEP_PARAMS(); p->hashAlg = 0; p->mgf = 0; p->src = 0; p->source_data = NULL; p->source_data_len = 0; return p; } }; %constant int CK_RSA_PKCS_OAEP_PARAMS_LENGTH = sizeof(CK_RSA_PKCS_OAEP_PARAMS); typedef struct CK_RSA_PKCS_PSS_PARAMS { unsigned long hashAlg; unsigned long mgf; unsigned long sLen; } CK_RSA_PKCS_PSS_PARAMS; %extend CK_RSA_PKCS_PSS_PARAMS { CK_RSA_PKCS_PSS_PARAMS() { CK_RSA_PKCS_PSS_PARAMS *p = new CK_RSA_PKCS_PSS_PARAMS(); p->hashAlg = 0; p->mgf = 0; p->sLen = 0; return p; } }; %constant int CK_RSA_PKCS_PSS_PARAMS_LENGTH = sizeof(CK_RSA_PKCS_PSS_PARAMS); typedef struct CK_ECDH1_DERIVE_PARAMS { unsigned long kdf; unsigned long ulSharedDataLen; void* pSharedData; unsigned long ulPublicDataLen; void* pPublicData; } CK_ECDH1_DERIVE_PARAMS; %extend CK_ECDH1_DERIVE_PARAMS { CK_ECDH1_DERIVE_PARAMS() { CK_ECDH1_DERIVE_PARAMS *p = new CK_ECDH1_DERIVE_PARAMS(); p->kdf = CKD_NULL; p->pSharedData = NULL; p->ulSharedDataLen = 0; p->pPublicData = NULL; p->ulPublicDataLen = 0; return p; } }; %constant int CK_ECDH1_DERIVE_PARAMS_LENGTH = sizeof(CK_ECDH1_DERIVE_PARAMS); typedef struct CK_KEY_DERIVATION_STRING_DATA { unsigned char * pData; unsigned long ulLen; } CK_KEY_DERIVATION_STRING_DATA; %extend CK_KEY_DERIVATION_STRING_DATA { CK_KEY_DERIVATION_STRING_DATA() { CK_KEY_DERIVATION_STRING_DATA *p = new CK_KEY_DERIVATION_STRING_DATA(); p->ulLen = 0; p->pData = NULL; return p; } }; %constant int CK_KEY_DERIVATION_STRING_DATA_LENGTH = sizeof(CK_KEY_DERIVATION_STRING_DATA); typedef struct CK_MECHANISM_INFO { %immutable; unsigned long ulMinKeySize; unsigned long ulMaxKeySize; unsigned long flags; %mutable; } CK_MECHANISM_INFO; typedef unsigned long CK_RV; #define FALSE 0 #define TRUE !(FALSE) #define CK_TRUE 1 #define CK_FALSE 0 #define CK_UNAVAILABLE_INFORMATION (~0UL) #define CK_EFFECTIVELY_INFINITE 0 #define CK_INVALID_HANDLE 0 #define CKN_SURRENDER 0 #define CKN_OTP_CHANGED 1 #define CKF_TOKEN_PRESENT 0x00000001 #define CKF_REMOVABLE_DEVICE 0x00000002 #define CKF_HW_SLOT 0x00000004 #define CKF_RNG 0x00000001 #define CKF_WRITE_PROTECTED 0x00000002 #define CKF_LOGIN_REQUIRED 0x00000004 #define CKF_USER_PIN_INITIALIZED 0x00000008 #define CKF_RESTORE_KEY_NOT_NEEDED 0x00000020 #define CKF_CLOCK_ON_TOKEN 0x00000040 #define CKF_PROTECTED_AUTHENTICATION_PATH 0x00000100 #define CKF_DUAL_CRYPTO_OPERATIONS 0x00000200 #define CKF_TOKEN_INITIALIZED 0x00000400 #define CKF_SECONDARY_AUTHENTICATION 0x00000800 #define CKF_USER_PIN_COUNT_LOW 0x00010000 #define CKF_USER_PIN_FINAL_TRY 0x00020000 #define CKF_USER_PIN_LOCKED 0x00040000 #define CKF_USER_PIN_TO_BE_CHANGED 0x00080000 #define CKF_SO_PIN_COUNT_LOW 0x00100000 #define CKF_SO_PIN_FINAL_TRY 0x00200000 #define CKF_SO_PIN_LOCKED 0x00400000 #define CKF_SO_PIN_TO_BE_CHANGED 0x00800000 #define CKF_ERROR_STATE 0x01000000 #define CKF_ARRAY_ATTRIBUTE (1 << 30) #define CKU_SO 0 #define CKU_USER 1 #define CKU_CONTEXT_SPECIFIC 2 #define CKS_RO_PUBLIC_SESSION 0 #define CKS_RO_USER_FUNCTIONS 1 #define CKS_RW_PUBLIC_SESSION 2 #define CKS_RW_USER_FUNCTIONS 3 #define CKS_RW_SO_FUNCTIONS 4 #define CKF_RW_SESSION 0x00000002 #define CKF_SERIAL_SESSION 0x00000004 #define CKO_DATA 0x00000000 #define CKO_CERTIFICATE 0x00000001 #define CKO_PUBLIC_KEY 0x00000002 #define CKO_PRIVATE_KEY 0x00000003 #define CKO_SECRET_KEY 0x00000004 #define CKO_HW_FEATURE 0x00000005 #define CKO_DOMAIN_PARAMETERS 0x00000006 #define CKO_MECHANISM 0x00000007 #define CKO_OTP_KEY 0x00000008 #define CKO_PROFILE 0x00000009 #define CKO_VENDOR_DEFINED 0x80000000UL #define CKH_MONOTONIC_COUNTER 0x00000001 #define CKH_CLOCK 0x00000002 #define CKH_USER_INTERFACE 0x00000003 #define CKH_VENDOR_DEFINED 0x80000000UL #define CKK_RSA 0x00000000 #define CKK_DSA 0x00000001 #define CKK_DH 0x00000002 #define CKK_ECDSA 0x00000003 #define CKK_EC 0x00000003 #define CKK_X9_42_DH 0x00000004 #define CKK_KEA 0x00000005 #define CKK_GENERIC_SECRET 0x00000010 #define CKK_RC2 0x00000011 #define CKK_RC4 0x00000012 #define CKK_DES 0x00000013 #define CKK_DES2 0x00000014 #define CKK_DES3 0x00000015 #define CKK_CAST 0x00000016 #define CKK_CAST3 0x00000017 #define CKK_CAST5 0x00000018 #define CKK_CAST128 0x00000018 #define CKK_RC5 0x00000019 #define CKK_IDEA 0x0000001A #define CKK_SKIPJACK 0x0000001B #define CKK_BATON 0x0000001C #define CKK_JUNIPER 0x0000001D #define CKK_CDMF 0x0000001E #define CKK_AES 0x0000001F #define CKK_BLOWFISH 0x00000020 #define CKK_TWOFISH 0x00000021 #define CKK_SECURID 0x00000022 #define CKK_HOTP 0x00000023 #define CKK_ACTI 0x00000024 #define CKK_CAMELLIA 0x00000025 #define CKK_ARIA 0x00000026 #define CKK_MD5_HMAC 0x00000027 #define CKK_SHA_1_HMAC 0x00000028 #define CKK_RIPEMD128_HMAC 0x00000029 #define CKK_RIPEMD160_HMAC 0x0000002A #define CKK_SHA256_HMAC 0x0000002B #define CKK_SHA384_HMAC 0x0000002C #define CKK_SHA512_HMAC 0x0000002D #define CKK_SHA224_HMAC 0x0000002E #define CKK_GOSTR3410 0x00000030 #define CKK_GOSTR3411 0x00000031 #define CKK_GOST28147 0x00000032 #define CKK_CHACHA20 0x00000033 #define CKK_POLY1305 0x00000034 #define CKK_AES_XTS 0x00000035 #define CKK_SHA3_224_HMAC 0x00000036 #define CKK_SHA3_256_HMAC 0x00000037 #define CKK_SHA3_384_HMAC 0x00000038 #define CKK_SHA3_512_HMAC 0x00000039 #define CKK_BLAKE2B_160_HMAC 0x0000003a #define CKK_BLAKE2B_256_HMAC 0x0000003b #define CKK_BLAKE2B_384_HMAC 0x0000003c #define CKK_BLAKE2B_512_HMAC 0x0000003d #define CKK_SALSA20 0x0000003e #define CKK_X2RATCHET 0x0000003f #define CKK_EC_EDWARDS 0x00000040 #define CKK_EC_MONTGOMERY 0x00000041 #define CKK_HKDF 0x00000042 #define CKK_VENDOR_DEFINED 0x80000000UL #define CKC_X_509 0x00000000 #define CKC_X_509_ATTR_CERT 0x00000001 #define CKC_WTLS 0x00000002 #define CKC_VENDOR_DEFINED 0x80000000UL #define CKA_CLASS 0x00000000 #define CKA_TOKEN 0x00000001 #define CKA_PRIVATE 0x00000002 #define CKA_LABEL 0x00000003 #define CKA_UNIQUE_ID 0x00000004 #define CKA_APPLICATION 0x00000010 #define CKA_VALUE 0x00000011 #define CKA_OBJECT_ID 0x00000012 #define CKA_CERTIFICATE_TYPE 0x00000080 #define CKA_ISSUER 0x00000081 #define CKA_SERIAL_NUMBER 0x00000082 #define CKA_AC_ISSUER 0x00000083 #define CKA_OWNER 0x00000084 #define CKA_ATTR_TYPES 0x00000085 #define CKA_TRUSTED 0x00000086 #define CKA_CERTIFICATE_CATEGORY 0x00000087 #define CKA_JAVA_MIDP_SECURITY_DOMAIN 0x00000088 #define CKA_URL 0x00000089 #define CKA_HASH_OF_SUBJECT_PUBLIC_KEY 0x0000008A #define CKA_HASH_OF_ISSUER_PUBLIC_KEY 0x0000008B #define CKA_NAME_HASH_ALGORITHM 0x0000008C #define CKA_CHECK_VALUE 0x00000090 #define CKA_KEY_TYPE 0x00000100 #define CKA_SUBJECT 0x00000101 #define CKA_ID 0x00000102 #define CKA_SENSITIVE 0x00000103 #define CKA_ENCRYPT 0x00000104 #define CKA_DECRYPT 0x00000105 #define CKA_WRAP 0x00000106 #define CKA_UNWRAP 0x00000107 #define CKA_SIGN 0x00000108 #define CKA_SIGN_RECOVER 0x00000109 #define CKA_VERIFY 0x0000010A #define CKA_VERIFY_RECOVER 0x0000010B #define CKA_DERIVE 0x0000010C #define CKA_START_DATE 0x00000110 #define CKA_END_DATE 0x00000111 #define CKA_MODULUS 0x00000120 #define CKA_MODULUS_BITS 0x00000121 #define CKA_PUBLIC_EXPONENT 0x00000122 #define CKA_PRIVATE_EXPONENT 0x00000123 #define CKA_PRIME_1 0x00000124 #define CKA_PRIME_2 0x00000125 #define CKA_EXPONENT_1 0x00000126 #define CKA_EXPONENT_2 0x00000127 #define CKA_COEFFICIENT 0x00000128 #define CKA_PUBLIC_KEY_INFO 0x00000129 #define CKA_PRIME 0x00000130 #define CKA_SUBPRIME 0x00000131 #define CKA_BASE 0x00000132 #define CKA_PRIME_BITS 0x00000133 #define CKA_SUBPRIME_BITS 0x00000134 #define CKA_SUB_PRIME_BITS CKA_SUBPRIME_BITS #define CKA_VALUE_BITS 0x00000160 #define CKA_VALUE_LEN 0x00000161 #define CKA_EXTRACTABLE 0x00000162 #define CKA_LOCAL 0x00000163 #define CKA_NEVER_EXTRACTABLE 0x00000164 #define CKA_ALWAYS_SENSITIVE 0x00000165 #define CKA_KEY_GEN_MECHANISM 0x00000166 #define CKA_MODIFIABLE 0x00000170 #define CKA_COPYABLE 0x00000171 #define CKA_DESTROYABLE 0x00000172 #define CKA_ECDSA_PARAMS 0x00000180 #define CKA_EC_PARAMS 0x00000180 #define CKA_EC_POINT 0x00000181 #define CKA_SECONDARY_AUTH 0x00000200 #define CKA_AUTH_PIN_FLAGS 0x00000201 #define CKA_ALWAYS_AUTHENTICATE 0x00000202 #define CKA_WRAP_WITH_TRUSTED 0x00000210 #define CKA_WRAP_TEMPLATE (CKF_ARRAY_ATTRIBUTE|0x00000211) #define CKA_UNWRAP_TEMPLATE (CKF_ARRAY_ATTRIBUTE|0x00000212) #define CKA_DERIVE_TEMPLATE (CKF_ARRAY_ATTRIBUTE|0x00000213) #define CKA_OTP_FORMAT 0x00000220 #define CKA_OTP_LENGTH 0x00000221 #define CKA_OTP_TIME_INTERVAL 0x00000222 #define CKA_OTP_USER_FRIENDLY_MODE 0x00000223 #define CKA_OTP_CHALLENGE_REQUIREMENT 0x00000224 #define CKA_OTP_TIME_REQUIREMENT 0x00000225 #define CKA_OTP_COUNTER_REQUIREMENT 0x00000226 #define CKA_OTP_PIN_REQUIREMENT 0x00000227 #define CKA_OTP_COUNTER 0x0000022E #define CKA_OTP_TIME 0x0000022F #define CKA_OTP_USER_IDENTIFIER 0x0000022A #define CKA_OTP_SERVICE_IDENTIFIER 0x0000022B #define CKA_OTP_SERVICE_LOGO 0x0000022C #define CKA_OTP_SERVICE_LOGO_TYPE 0x0000022D #define CKA_GOSTR3410_PARAMS 0x00000250 #define CKA_GOSTR3411_PARAMS 0x00000251 #define CKA_GOST28147_PARAMS 0x00000252 #define CKA_HW_FEATURE_TYPE 0x00000300 #define CKA_RESET_ON_INIT 0x00000301 #define CKA_HAS_RESET 0x00000302 #define CKA_PIXEL_X 0x00000400 #define CKA_PIXEL_Y 0x00000401 #define CKA_RESOLUTION 0x00000402 #define CKA_CHAR_ROWS 0x00000403 #define CKA_CHAR_COLUMNS 0x00000404 #define CKA_COLOR 0x00000405 #define CKA_BITS_PER_PIXEL 0x00000406 #define CKA_CHAR_SETS 0x00000480 #define CKA_ENCODING_METHODS 0x00000481 #define CKA_MIME_TYPES 0x00000482 #define CKA_MECHANISM_TYPE 0x00000500 #define CKA_REQUIRED_CMS_ATTRIBUTES 0x00000501 #define CKA_DEFAULT_CMS_ATTRIBUTES 0x00000502 #define CKA_SUPPORTED_CMS_ATTRIBUTES 0x00000503 #define CKA_ALLOWED_MECHANISMS (CKF_ARRAY_ATTRIBUTE|0x00000600) #define CKA_PROFILE_ID 0x00000601 #define CKA_VENDOR_DEFINED 0x80000000UL #define CKM_RSA_PKCS_KEY_PAIR_GEN 0x00000000 #define CKM_RSA_PKCS 0x00000001 #define CKM_RSA_9796 0x00000002 #define CKM_RSA_X_509 0x00000003 #define CKM_MD2_RSA_PKCS 0x00000004 #define CKM_MD5_RSA_PKCS 0x00000005 #define CKM_SHA1_RSA_PKCS 0x00000006 #define CKM_RIPEMD128_RSA_PKCS 0x00000007 #define CKM_RIPEMD160_RSA_PKCS 0x00000008 #define CKM_RSA_PKCS_OAEP 0x00000009 #define CKM_RSA_X9_31_KEY_PAIR_GEN 0x0000000A #define CKM_RSA_X9_31 0x0000000B #define CKM_SHA1_RSA_X9_31 0x0000000C #define CKM_RSA_PKCS_PSS 0x0000000D #define CKM_SHA1_RSA_PKCS_PSS 0x0000000E #define CKM_DSA_KEY_PAIR_GEN 0x00000010 #define CKM_DSA 0x00000011 #define CKM_DSA_SHA1 0x00000012 #define CKM_DSA_SHA224 0x00000013 #define CKM_DSA_SHA256 0x00000014 #define CKM_DSA_SHA384 0x00000015 #define CKM_DSA_SHA512 0x00000016 #define CKM_DSA_SHA3_224 0x00000018 #define CKM_DSA_SHA3_256 0x00000019 #define CKM_DSA_SHA3_384 0x0000001A #define CKM_DSA_SHA3_512 0x0000001B #define CKM_DH_PKCS_KEY_PAIR_GEN 0x00000020 #define CKM_DH_PKCS_DERIVE 0x00000021 #define CKM_X9_42_DH_KEY_PAIR_GEN 0x00000030 #define CKM_X9_42_DH_DERIVE 0x00000031 #define CKM_X9_42_DH_HYBRID_DERIVE 0x00000032 #define CKM_X9_42_MQV_DERIVE 0x00000033 #define CKM_SHA256_RSA_PKCS 0x00000040 #define CKM_SHA384_RSA_PKCS 0x00000041 #define CKM_SHA512_RSA_PKCS 0x00000042 #define CKM_SHA256_RSA_PKCS_PSS 0x00000043 #define CKM_SHA384_RSA_PKCS_PSS 0x00000044 #define CKM_SHA512_RSA_PKCS_PSS 0x00000045 #define CKM_SHA224_RSA_PKCS 0x00000046 #define CKM_SHA224_RSA_PKCS_PSS 0x00000047 #define CKM_SHA512_224 0x00000048 #define CKM_SHA512_224_HMAC 0x00000049 #define CKM_SHA512_224_HMAC_GENERAL 0x0000004A #define CKM_SHA512_224_KEY_DERIVATION 0x0000004B #define CKM_SHA512_256 0x0000004C #define CKM_SHA512_256_HMAC 0x0000004D #define CKM_SHA512_256_HMAC_GENERAL 0x0000004E #define CKM_SHA512_256_KEY_DERIVATION 0x0000004F #define CKM_SHA512_T 0x00000050 #define CKM_SHA512_T_HMAC 0x00000051 #define CKM_SHA512_T_HMAC_GENERAL 0x00000052 #define CKM_SHA512_T_KEY_DERIVATION 0x00000053 #define CKM_SHA3_256_RSA_PKCS 0x00000060 #define CKM_SHA3_384_RSA_PKCS 0x00000061 #define CKM_SHA3_512_RSA_PKCS 0x00000062 #define CKM_SHA3_256_RSA_PKCS_PSS 0x00000063 #define CKM_SHA3_384_RSA_PKCS_PSS 0x00000064 #define CKM_SHA3_512_RSA_PKCS_PSS 0x00000065 #define CKM_SHA3_224_RSA_PKCS 0x00000066 #define CKM_SHA3_224_RSA_PKCS_PSS 0x00000067 #define CKM_RC2_KEY_GEN 0x00000100 #define CKM_RC2_ECB 0x00000101 #define CKM_RC2_CBC 0x00000102 #define CKM_RC2_MAC 0x00000103 #define CKM_RC2_MAC_GENERAL 0x00000104 #define CKM_RC2_CBC_PAD 0x00000105 #define CKM_RC4_KEY_GEN 0x00000110 #define CKM_RC4 0x00000111 #define CKM_DES_KEY_GEN 0x00000120 #define CKM_DES_ECB 0x00000121 #define CKM_DES_CBC 0x00000122 #define CKM_DES_MAC 0x00000123 #define CKM_DES_MAC_GENERAL 0x00000124 #define CKM_DES_CBC_PAD 0x00000125 #define CKM_DES2_KEY_GEN 0x00000130 #define CKM_DES3_KEY_GEN 0x00000131 #define CKM_DES3_ECB 0x00000132 #define CKM_DES3_CBC 0x00000133 #define CKM_DES3_MAC 0x00000134 #define CKM_DES3_MAC_GENERAL 0x00000135 #define CKM_DES3_CBC_PAD 0x00000136 #define CKM_DES3_CMAC_GENERAL 0x00000137 #define CKM_DES3_CMAC 0x00000138 #define CKM_CDMF_KEY_GEN 0x00000140 #define CKM_CDMF_ECB 0x00000141 #define CKM_CDMF_CBC 0x00000142 #define CKM_CDMF_MAC 0x00000143 #define CKM_CDMF_MAC_GENERAL 0x00000144 #define CKM_CDMF_CBC_PAD 0x00000145 #define CKM_DES_OFB64 0x00000150 #define CKM_DES_OFB8 0x00000151 #define CKM_DES_CFB64 0x00000152 #define CKM_DES_CFB8 0x00000153 #define CKM_MD2 0x00000200 #define CKM_MD2_HMAC 0x00000201 #define CKM_MD2_HMAC_GENERAL 0x00000202 #define CKM_MD5 0x00000210 #define CKM_MD5_HMAC 0x00000211 #define CKM_MD5_HMAC_GENERAL 0x00000212 #define CKM_SHA_1 0x00000220 #define CKM_SHA_1_HMAC 0x00000221 #define CKM_SHA_1_HMAC_GENERAL 0x00000222 #define CKM_RIPEMD128 0x00000230 #define CKM_RIPEMD128_HMAC 0x00000231 #define CKM_RIPEMD128_HMAC_GENERAL 0x00000232 #define CKM_RIPEMD160 0x00000240 #define CKM_RIPEMD160_HMAC 0x00000241 #define CKM_RIPEMD160_HMAC_GENERAL 0x00000242 #define CKM_SHA256 0x00000250 #define CKM_SHA256_HMAC 0x00000251 #define CKM_SHA256_HMAC_GENERAL 0x00000252 #define CKM_SHA224 0x00000255 #define CKM_SHA224_HMAC 0x00000256 #define CKM_SHA224_HMAC_GENERAL 0x00000257 #define CKM_SHA384 0x00000260 #define CKM_SHA384_HMAC 0x00000261 #define CKM_SHA384_HMAC_GENERAL 0x00000262 #define CKM_SHA512 0x00000270 #define CKM_SHA512_HMAC 0x00000271 #define CKM_SHA512_HMAC_GENERAL 0x00000272 #define CKM_SECURID_KEY_GEN 0x00000280 #define CKM_SECURID 0x00000282 #define CKM_HOTP_KEY_GEN 0x00000290 #define CKM_HOTP 0x00000291 #define CKM_ACTI 0x000002A0 #define CKM_ACTI_KEY_GEN 0x000002A1 #define CKM_SHA3_256 0x000002B0 #define CKM_SHA3_256_HMAC 0x000002B1 #define CKM_SHA3_256_HMAC_GENERAL 0x000002B2 #define CKM_SHA3_256_KEY_GEN 0x000002B3 #define CKM_SHA3_224 0x000002B5 #define CKM_SHA3_224_HMAC 0x000002B6 #define CKM_SHA3_224_HMAC_GENERAL 0x000002B7 #define CKM_SHA3_224_KEY_GEN 0x000002B8 #define CKM_SHA3_384 0x000002C0 #define CKM_SHA3_384_HMAC 0x000002C1 #define CKM_SHA3_384_HMAC_GENERAL 0x000002C2 #define CKM_SHA3_384_KEY_GEN 0x000002C3 #define CKM_SHA3_512 0x000002D0 #define CKM_SHA3_512_HMAC 0x000002D1 #define CKM_SHA3_512_HMAC_GENERAL 0x000002D2 #define CKM_SHA3_512_KEY_GEN 0x000002D3 #define CKM_CAST_KEY_GEN 0x00000300 #define CKM_CAST_ECB 0x00000301 #define CKM_CAST_CBC 0x00000302 #define CKM_CAST_MAC 0x00000303 #define CKM_CAST_MAC_GENERAL 0x00000304 #define CKM_CAST_CBC_PAD 0x00000305 #define CKM_CAST3_KEY_GEN 0x00000310 #define CKM_CAST3_ECB 0x00000311 #define CKM_CAST3_CBC 0x00000312 #define CKM_CAST3_MAC 0x00000313 #define CKM_CAST3_MAC_GENERAL 0x00000314 #define CKM_CAST3_CBC_PAD 0x00000315 #define CKM_CAST5_KEY_GEN 0x00000320 #define CKM_CAST128_KEY_GEN 0x00000320 #define CKM_CAST5_ECB 0x00000321 #define CKM_CAST128_ECB 0x00000321 #define CKM_CAST5_CBC 0x00000322 #define CKM_CAST128_CBC 0x00000322 #define CKM_CAST5_MAC 0x00000323 #define CKM_CAST128_MAC 0x00000323 #define CKM_CAST5_MAC_GENERAL 0x00000324 #define CKM_CAST128_MAC_GENERAL 0x00000324 #define CKM_CAST5_CBC_PAD 0x00000325 #define CKM_CAST128_CBC_PAD 0x00000325 #define CKM_RC5_KEY_GEN 0x00000330 #define CKM_RC5_ECB 0x00000331 #define CKM_RC5_CBC 0x00000332 #define CKM_RC5_MAC 0x00000333 #define CKM_RC5_MAC_GENERAL 0x00000334 #define CKM_RC5_CBC_PAD 0x00000335 #define CKM_IDEA_KEY_GEN 0x00000340 #define CKM_IDEA_ECB 0x00000341 #define CKM_IDEA_CBC 0x00000342 #define CKM_IDEA_MAC 0x00000343 #define CKM_IDEA_MAC_GENERAL 0x00000344 #define CKM_IDEA_CBC_PAD 0x00000345 #define CKM_GENERIC_SECRET_KEY_GEN 0x00000350 #define CKM_CONCATENATE_BASE_AND_KEY 0x00000360 #define CKM_CONCATENATE_BASE_AND_DATA 0x00000362 #define CKM_CONCATENATE_DATA_AND_BASE 0x00000363 #define CKM_XOR_BASE_AND_DATA 0x00000364 #define CKM_EXTRACT_KEY_FROM_KEY 0x00000365 #define CKM_SSL3_PRE_MASTER_KEY_GEN 0x00000370 #define CKM_SSL3_MASTER_KEY_DERIVE 0x00000371 #define CKM_SSL3_KEY_AND_MAC_DERIVE 0x00000372 #define CKM_SSL3_MASTER_KEY_DERIVE_DH 0x00000373 #define CKM_TLS_PRE_MASTER_KEY_GEN 0x00000374 #define CKM_TLS_MASTER_KEY_DERIVE 0x00000375 #define CKM_TLS_KEY_AND_MAC_DERIVE 0x00000376 #define CKM_TLS_MASTER_KEY_DERIVE_DH 0x00000377 #define CKM_TLS_PRF 0x00000378 #define CKM_SSL3_MD5_MAC 0x00000380 #define CKM_SSL3_SHA1_MAC 0x00000381 #define CKM_MD5_KEY_DERIVATION 0x00000390 #define CKM_MD2_KEY_DERIVATION 0x00000391 #define CKM_SHA1_KEY_DERIVATION 0x00000392 #define CKM_SHA256_KEY_DERIVATION 0x00000393 #define CKM_SHA384_KEY_DERIVATION 0x00000394 #define CKM_SHA512_KEY_DERIVATION 0x00000395 #define CKM_SHA224_KEY_DERIVATION 0x00000396 #define CKM_SHA3_256_KEY_DERIVE 0x00000397 #define CKM_SHA3_224_KEY_DERIVE 0x00000398 #define CKM_SHA3_384_KEY_DERIVE 0x00000399 #define CKM_SHA3_512_KEY_DERIVE 0x0000039A #define CKM_SHAKE_128_KEY_DERIVE 0x0000039B #define CKM_SHAKE_256_KEY_DERIVE 0x0000039C #define CKM_PBE_MD2_DES_CBC 0x000003A0 #define CKM_PBE_MD5_DES_CBC 0x000003A1 #define CKM_PBE_MD5_CAST_CBC 0x000003A2 #define CKM_PBE_MD5_CAST3_CBC 0x000003A3 #define CKM_PBE_MD5_CAST5_CBC 0x000003A4 #define CKM_PBE_MD5_CAST128_CBC 0x000003A4 #define CKM_PBE_SHA1_CAST5_CBC 0x000003A5 #define CKM_PBE_SHA1_CAST128_CBC 0x000003A5 #define CKM_PBE_SHA1_RC4_128 0x000003A6 #define CKM_PBE_SHA1_RC4_40 0x000003A7 #define CKM_PBE_SHA1_DES3_EDE_CBC 0x000003A8 #define CKM_PBE_SHA1_DES2_EDE_CBC 0x000003A9 #define CKM_PBE_SHA1_RC2_128_CBC 0x000003AA #define CKM_PBE_SHA1_RC2_40_CBC 0x000003AB #define CKM_SP800_108_COUNTER_KDF 0x000003ac #define CKM_SP800_108_FEEDBACK_KDF 0x000003ad #define CKM_SP800_108_DOUBLE_PIPELINE_KDF 0x000003ae #define CKM_PKCS5_PBKD2 0x000003B0 #define CKM_PBA_SHA1_WITH_SHA1_HMAC 0x000003C0 #define CKM_WTLS_PRE_MASTER_KEY_GEN 0x000003D0 #define CKM_WTLS_MASTER_KEY_DERIVE 0x000003D1 #define CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC 0x000003D2 #define CKM_WTLS_PRF 0x000003D3 #define CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE 0x000003D4 #define CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE 0x000003D5 #define CKM_TLS10_MAC_SERVER 0x000003D6 #define CKM_TLS10_MAC_CLIENT 0x000003D7 #define CKM_TLS12_MAC 0x000003D8 #define CKM_TLS12_KDF 0x000003D9 #define CKM_TLS12_MASTER_KEY_DERIVE 0x000003E0 #define CKM_TLS12_KEY_AND_MAC_DERIVE 0x000003E1 #define CKM_TLS12_MASTER_KEY_DERIVE_DH 0x000003E2 #define CKM_TLS12_KEY_SAFE_DERIVE 0x000003E3 #define CKM_TLS_MAC 0x000003E4 #define CKM_TLS_KDF 0x000003E5 #define CKM_KEY_WRAP_LYNKS 0x00000400 #define CKM_KEY_WRAP_SET_OAEP 0x00000401 #define CKM_CMS_SIG 0x00000500 #define CKM_KIP_DERIVE 0x00000510 #define CKM_KIP_WRAP 0x00000511 #define CKM_KIP_MAC 0x00000512 #define CKM_CAMELLIA_KEY_GEN 0x00000550 #define CKM_CAMELLIA_ECB 0x00000551 #define CKM_CAMELLIA_CBC 0x00000552 #define CKM_CAMELLIA_MAC 0x00000553 #define CKM_CAMELLIA_MAC_GENERAL 0x00000554 #define CKM_CAMELLIA_CBC_PAD 0x00000555 #define CKM_CAMELLIA_ECB_ENCRYPT_DATA 0x00000556 #define CKM_CAMELLIA_CBC_ENCRYPT_DATA 0x00000557 #define CKM_CAMELLIA_CTR 0x00000558 #define CKM_ARIA_KEY_GEN 0x00000560 #define CKM_ARIA_ECB 0x00000561 #define CKM_ARIA_CBC 0x00000562 #define CKM_ARIA_MAC 0x00000563 #define CKM_ARIA_MAC_GENERAL 0x00000564 #define CKM_ARIA_CBC_PAD 0x00000565 #define CKM_ARIA_ECB_ENCRYPT_DATA 0x00000566 #define CKM_ARIA_CBC_ENCRYPT_DATA 0x00000567 #define CKM_SEED_KEY_GEN 0x00000650 #define CKM_SEED_ECB 0x00000651 #define CKM_SEED_CBC 0x00000652 #define CKM_SEED_MAC 0x00000653 #define CKM_SEED_MAC_GENERAL 0x00000654 #define CKM_SEED_CBC_PAD 0x00000655 #define CKM_SEED_ECB_ENCRYPT_DATA 0x00000656 #define CKM_SEED_CBC_ENCRYPT_DATA 0x00000657 #define CKM_SKIPJACK_KEY_GEN 0x00001000 #define CKM_SKIPJACK_ECB64 0x00001001 #define CKM_SKIPJACK_CBC64 0x00001002 #define CKM_SKIPJACK_OFB64 0x00001003 #define CKM_SKIPJACK_CFB64 0x00001004 #define CKM_SKIPJACK_CFB32 0x00001005 #define CKM_SKIPJACK_CFB16 0x00001006 #define CKM_SKIPJACK_CFB8 0x00001007 #define CKM_SKIPJACK_WRAP 0x00001008 #define CKM_SKIPJACK_PRIVATE_WRAP 0x00001009 #define CKM_SKIPJACK_RELAYX 0x0000100a #define CKM_KEA_KEY_PAIR_GEN 0x00001010 #define CKM_KEA_KEY_DERIVE 0x00001011 #define CKM_KEA_DERIVE 0x00001012 #define CKM_FORTEZZA_TIMESTAMP 0x00001020 #define CKM_BATON_KEY_GEN 0x00001030 #define CKM_BATON_ECB128 0x00001031 #define CKM_BATON_ECB96 0x00001032 #define CKM_BATON_CBC128 0x00001033 #define CKM_BATON_COUNTER 0x00001034 #define CKM_BATON_SHUFFLE 0x00001035 #define CKM_BATON_WRAP 0x00001036 #define CKM_ECDSA_KEY_PAIR_GEN 0x00001040 #define CKM_EC_KEY_PAIR_GEN 0x00001040 #define CKM_ECDSA 0x00001041 #define CKM_ECDSA_SHA1 0x00001042 #define CKM_ECDSA_SHA224 0x00001043 #define CKM_ECDSA_SHA256 0x00001044 #define CKM_ECDSA_SHA384 0x00001045 #define CKM_ECDSA_SHA512 0x00001046 #define CKM_ECDSA_SHA3_224 0x00001047 #define CKM_ECDSA_SHA3_256 0x00001048 #define CKM_ECDSA_SHA3_384 0x00001049 #define CKM_ECDSA_SHA3_512 0x0000104a #define CKM_ECDH1_DERIVE 0x00001050 #define CKM_ECDH1_COFACTOR_DERIVE 0x00001051 #define CKM_ECMQV_DERIVE 0x00001052 #define CKM_ECDH_AES_KEY_WRAP 0x00001053 #define CKM_RSA_AES_KEY_WRAP 0x00001054 #define CKM_EC_EDWARDS_KEY_PAIR_GEN 0x00001055 #define CKM_EC_MONTGOMERY_KEY_PAIR_GEN 0x00001056 #define CKM_EDDSA 0x00001057 #define CKM_JUNIPER_KEY_GEN 0x00001060 #define CKM_JUNIPER_ECB128 0x00001061 #define CKM_JUNIPER_CBC128 0x00001062 #define CKM_JUNIPER_COUNTER 0x00001063 #define CKM_JUNIPER_SHUFFLE 0x00001064 #define CKM_JUNIPER_WRAP 0x00001065 #define CKM_FASTHASH 0x00001070 #define CKM_AES_XTS 0x00001071 #define CKM_AES_XTS_KEY_GEN 0x00001072 #define CKM_AES_KEY_GEN 0x00001080 #define CKM_AES_ECB 0x00001081 #define CKM_AES_CBC 0x00001082 #define CKM_AES_MAC 0x00001083 #define CKM_AES_MAC_GENERAL 0x00001084 #define CKM_AES_CBC_PAD 0x00001085 #define CKM_AES_CTR 0x00001086 #define CKM_AES_GCM 0x00001087 #define CKM_AES_CCM 0x00001088 #define CKM_AES_CTS 0x00001089 #define CKM_AES_CMAC 0x0000108A #define CKM_AES_CMAC_GENERAL 0x0000108B #define CKM_AES_XCBC_MAC 0x0000108C #define CKM_AES_XCBC_MAC_96 0x0000108D #define CKM_AES_GMAC 0x0000108E #define CKM_BLOWFISH_KEY_GEN 0x00001090 #define CKM_BLOWFISH_CBC 0x00001091 #define CKM_TWOFISH_KEY_GEN 0x00001092 #define CKM_TWOFISH_CBC 0x00001093 #define CKM_BLOWFISH_CBC_PAD 0x00001094 #define CKM_TWOFISH_CBC_PAD 0x00001095 #define CKM_DES_ECB_ENCRYPT_DATA 0x00001100 #define CKM_DES_CBC_ENCRYPT_DATA 0x00001101 #define CKM_DES3_ECB_ENCRYPT_DATA 0x00001102 #define CKM_DES3_CBC_ENCRYPT_DATA 0x00001103 #define CKM_AES_ECB_ENCRYPT_DATA 0x00001104 #define CKM_AES_CBC_ENCRYPT_DATA 0x00001105 #define CKM_GOSTR3410_KEY_PAIR_GEN 0x00001200 #define CKM_GOSTR3410 0x00001201 #define CKM_GOSTR3410_WITH_GOSTR3411 0x00001202 #define CKM_GOSTR3410_KEY_WRAP 0x00001203 #define CKM_GOSTR3410_DERIVE 0x00001204 #define CKM_GOSTR3411 0x00001210 #define CKM_GOSTR3411_HMAC 0x00001211 #define CKM_GOST28147_KEY_GEN 0x00001220 #define CKM_GOST28147_ECB 0x00001221 #define CKM_GOST28147 0x00001222 #define CKM_GOST28147_MAC 0x00001223 #define CKM_GOST28147_KEY_WRAP 0x00001224 #define CKM_CHACHA20_KEY_GEN 0x00001225 #define CKM_CHACHA20 0x00001226 #define CKM_POLY1305_KEY_GEN 0x00001227 #define CKM_POLY1305 0x00001228 #define CKM_DSA_PARAMETER_GEN 0x00002000 #define CKM_DH_PKCS_PARAMETER_GEN 0x00002001 #define CKM_X9_42_DH_PARAMETER_GEN 0x00002002 #define CKM_DSA_PROBABLISTIC_PARAMETER_GEN 0x00002003 #define CKM_DSA_SHAWE_TAYLOR_PARAMETER_GEN 0x00002004 #define CKM_AES_OFB 0x00002104 #define CKM_AES_CFB64 0x00002105 #define CKM_AES_CFB8 0x00002106 #define CKM_AES_CFB128 0x00002107 #define CKM_AES_CFB1 0x00002108 #define CKM_AES_KEY_WRAP 0x00002109 #define CKM_AES_KEY_WRAP_PAD 0x0000210A #define CKM_AES_KEY_WRAP_KWP 0x0000210B #define CKM_RSA_PKCS_TPM_1_1 0x00004001 #define CKM_RSA_PKCS_OAEP_TPM_1_1 0x00004002 #define CKM_SHA_1_KEY_GEN 0x00004003 #define CKM_SHA224_KEY_GEN 0x00004004 #define CKM_SHA256_KEY_GEN 0x00004005 #define CKM_SHA384_KEY_GEN 0x00004006 #define CKM_SHA512_KEY_GEN 0x00004007 #define CKM_SHA512_224_KEY_GEN 0x00004008 #define CKM_SHA512_256_KEY_GEN 0x00004009 #define CKM_SHA512_T_KEY_GEN 0x0000400a #define CKM_NULL 0x0000400b #define CKM_BLAKE2B_160 0x0000400c #define CKM_BLAKE2B_160_HMAC 0x0000400d #define CKM_BLAKE2B_160_HMAC_GENERAL 0x0000400e #define CKM_BLAKE2B_160_KEY_DERIVE 0x0000400f #define CKM_BLAKE2B_160_KEY_GEN 0x00004010 #define CKM_BLAKE2B_256 0x00004011 #define CKM_BLAKE2B_256_HMAC 0x00004012 #define CKM_BLAKE2B_256_HMAC_GENERAL 0x00004013 #define CKM_BLAKE2B_256_KEY_DERIVE 0x00004014 #define CKM_BLAKE2B_256_KEY_GEN 0x00004015 #define CKM_BLAKE2B_384 0x00004016 #define CKM_BLAKE2B_384_HMAC 0x00004017 #define CKM_BLAKE2B_384_HMAC_GENERAL 0x00004018 #define CKM_BLAKE2B_384_KEY_DERIVE 0x00004019 #define CKM_BLAKE2B_384_KEY_GEN 0x0000401a #define CKM_BLAKE2B_512 0x0000401b #define CKM_BLAKE2B_512_HMAC 0x0000401c #define CKM_BLAKE2B_512_HMAC_GENERAL 0x0000401d #define CKM_BLAKE2B_512_KEY_DERIVE 0x0000401e #define CKM_BLAKE2B_512_KEY_GEN 0x0000401f #define CKM_SALSA20 0x00004020 #define CKM_CHACHA20_POLY1305 0x00004021 #define CKM_SALSA20_POLY1305 0x00004022 #define CKM_X3DH_INITIALIZE 0x00004023 #define CKM_X3DH_RESPOND 0x00004024 #define CKM_X2RATCHET_INITIALIZE 0x00004025 #define CKM_X2RATCHET_RESPOND 0x00004026 #define CKM_X2RATCHET_ENCRYPT 0x00004027 #define CKM_X2RATCHET_DECRYPT 0x00004028 #define CKM_XEDDSA 0x00004029 #define CKM_HKDF_DERIVE 0x0000402a #define CKM_HKDF_DATA 0x0000402b #define CKM_HKDF_KEY_GEN 0x0000402c #define CKM_VENDOR_DEFINED 0x80000000UL #define CKG_MGF1_SHA1 0x00000001 #define CKG_MGF1_SHA256 0x00000002 #define CKG_MGF1_SHA384 0x00000003 #define CKG_MGF1_SHA512 0x00000004 #define CKF_HW 0x00000001 #define CKF_MESSAGE_ENCRYPT 0x00000002 #define CKF_MESSAGE_DECRYPT 0x00000004 #define CKF_MESSAGE_SIGN 0x00000008 #define CKF_MESSAGE_VERIFY 0x00000010 #define CKF_MULTI_MESSGE 0x00000020 #define CKF_FIND_OBJECTS 0x00000040 #define CKF_ENCRYPT 0x00000100 #define CKF_DECRYPT 0x00000200 #define CKF_DIGEST 0x00000400 #define CKF_SIGN 0x00000800 #define CKF_SIGN_RECOVER 0x00001000 #define CKF_VERIFY 0x00002000 #define CKF_VERIFY_RECOVER 0x00004000 #define CKF_GENERATE 0x00008000 #define CKF_GENERATE_KEY_PAIR 0x00010000 #define CKF_WRAP 0x00020000 #define CKF_UNWRAP 0x00040000 #define CKF_DERIVE 0x00080000 #define CKF_EC_F_P 0x00100000 #define CKF_EC_F_2M 0x00200000 #define CKF_EC_ECPARAMETERS 0x00400000 #define CKF_EC_NAMEDCURVE 0x00800000 #define CKF_EC_UNCOMPRESS 0x01000000 #define CKF_EC_COMPRESS 0x02000000 #define CKF_EC_CURVENAME 0x04000000 #define CKF_EXTENSION 0x80000000UL #define CKR_OK 0x00000000 #define CKR_CANCEL 0x00000001 #define CKR_HOST_MEMORY 0x00000002 #define CKR_SLOT_ID_INVALID 0x00000003 #define CKR_GENERAL_ERROR 0x00000005 #define CKR_FUNCTION_FAILED 0x00000006 #define CKR_ARGUMENTS_BAD 0x00000007 #define CKR_NO_EVENT 0x00000008 #define CKR_NEED_TO_CREATE_THREADS 0x00000009 #define CKR_CANT_LOCK 0x0000000A #define CKR_ATTRIBUTE_READ_ONLY 0x00000010 #define CKR_ATTRIBUTE_SENSITIVE 0x00000011 #define CKR_ATTRIBUTE_TYPE_INVALID 0x00000012 #define CKR_ATTRIBUTE_VALUE_INVALID 0x00000013 #define CKR_DATA_INVALID 0x00000020 #define CKR_DATA_LEN_RANGE 0x00000021 #define CKR_DEVICE_ERROR 0x00000030 #define CKR_DEVICE_MEMORY 0x00000031 #define CKR_DEVICE_REMOVED 0x00000032 #define CKR_ENCRYPTED_DATA_INVALID 0x00000040 #define CKR_ENCRYPTED_DATA_LEN_RANGE 0x00000041 #define CKR_FUNCTION_CANCELED 0x00000050 #define CKR_FUNCTION_NOT_PARALLEL 0x00000051 #define CKR_FUNCTION_NOT_SUPPORTED 0x00000054 #define CKR_KEY_HANDLE_INVALID 0x00000060 #define CKR_KEY_SIZE_RANGE 0x00000062 #define CKR_KEY_TYPE_INCONSISTENT 0x00000063 #define CKR_KEY_NOT_NEEDED 0x00000064 #define CKR_KEY_CHANGED 0x00000065 #define CKR_KEY_NEEDED 0x00000066 #define CKR_KEY_INDIGESTIBLE 0x00000067 #define CKR_KEY_FUNCTION_NOT_PERMITTED 0x00000068 #define CKR_KEY_NOT_WRAPPABLE 0x00000069 #define CKR_KEY_UNEXTRACTABLE 0x0000006A #define CKR_MECHANISM_INVALID 0x00000070 #define CKR_MECHANISM_PARAM_INVALID 0x00000071 #define CKR_OBJECT_HANDLE_INVALID 0x00000082 #define CKR_OPERATION_ACTIVE 0x00000090 #define CKR_OPERATION_NOT_INITIALIZED 0x00000091 #define CKR_PIN_INCORRECT 0x000000A0 #define CKR_PIN_INVALID 0x000000A1 #define CKR_PIN_LEN_RANGE 0x000000A2 #define CKR_PIN_EXPIRED 0x000000A3 #define CKR_PIN_LOCKED 0x000000A4 #define CKR_SESSION_CLOSED 0x000000B0 #define CKR_SESSION_COUNT 0x000000B1 #define CKR_SESSION_HANDLE_INVALID 0x000000B3 #define CKR_SESSION_PARALLEL_NOT_SUPPORTED 0x000000B4 #define CKR_SESSION_READ_ONLY 0x000000B5 #define CKR_SESSION_EXISTS 0x000000B6 #define CKR_SESSION_READ_ONLY_EXISTS 0x000000B7 #define CKR_SESSION_READ_WRITE_SO_EXISTS 0x000000B8 #define CKR_SIGNATURE_INVALID 0x000000C0 #define CKR_SIGNATURE_LEN_RANGE 0x000000C1 #define CKR_TEMPLATE_INCOMPLETE 0x000000D0 #define CKR_TEMPLATE_INCONSISTENT 0x000000D1 #define CKR_TOKEN_NOT_PRESENT 0x000000E0 #define CKR_TOKEN_NOT_RECOGNIZED 0x000000E1 #define CKR_TOKEN_WRITE_PROTECTED 0x000000E2 #define CKR_UNWRAPPING_KEY_HANDLE_INVALID 0x000000F0 #define CKR_UNWRAPPING_KEY_SIZE_RANGE 0x000000F1 #define CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT 0x000000F2 #define CKR_USER_ALREADY_LOGGED_IN 0x00000100 #define CKR_USER_NOT_LOGGED_IN 0x00000101 #define CKR_USER_PIN_NOT_INITIALIZED 0x00000102 #define CKR_USER_TYPE_INVALID 0x00000103 #define CKR_USER_ANOTHER_ALREADY_LOGGED_IN 0x00000104 #define CKR_USER_TOO_MANY_TYPES 0x00000105 #define CKR_WRAPPED_KEY_INVALID 0x00000110 #define CKR_WRAPPED_KEY_LEN_RANGE 0x00000112 #define CKR_WRAPPING_KEY_HANDLE_INVALID 0x00000113 #define CKR_WRAPPING_KEY_SIZE_RANGE 0x00000114 #define CKR_WRAPPING_KEY_TYPE_INCONSISTENT 0x00000115 #define CKR_RANDOM_SEED_NOT_SUPPORTED 0x00000120 #define CKR_RANDOM_NO_RNG 0x00000121 #define CKR_DOMAIN_PARAMS_INVALID 0x00000130 #define CKR_CURVE_NOT_SUPPORTED 0x00000140 #define CKR_BUFFER_TOO_SMALL 0x00000150 #define CKR_SAVED_STATE_INVALID 0x00000160 #define CKR_INFORMATION_SENSITIVE 0x00000170 #define CKR_STATE_UNSAVEABLE 0x00000180 #define CKR_CRYPTOKI_NOT_INITIALIZED 0x00000190 #define CKR_CRYPTOKI_ALREADY_INITIALIZED 0x00000191 #define CKR_MUTEX_BAD 0x000001A0 #define CKR_MUTEX_NOT_LOCKED 0x000001A1 #define CKR_NEW_PIN_MODE 0x000001B0 #define CKR_NEXT_OTP 0x000001B1 #define CKR_EXCEEDED_MAX_ITERATIONS 0x000001B5 #define CKR_FIPS_SELF_TEST_FAILED 0x000001B6 #define CKR_LIBRARY_LOAD_FAILED 0x000001B7 #define CKR_PIN_TOO_WEAK 0x000001B8 #define CKR_PUBLIC_KEY_INVALID 0x000001B9 #define CKR_FUNCTION_REJECTED 0x00000200 #define CKR_VENDOR_DEFINED 0x80000000UL #define CKF_LIBRARY_CANT_CREATE_OS_THREADS 0x00000001 #define CKF_OS_LOCKING_OK 0x00000002 #define CKF_DONT_BLOCK 1 #define CKG_MGF1_SHA1 0x00000001 #define CKG_MGF1_SHA256 0x00000002 #define CKG_MGF1_SHA384 0x00000003 #define CKG_MGF1_SHA512 0x00000004 #define CKG_MGF1_SHA224 0x00000005 #define CKZ_DATA_SPECIFIED 0x00000001 #define CKD_NULL 0x00000001 #define CKD_SHA1_KDF 0x00000002 #define CKD_SHA1_KDF_ASN1 0x00000003 #define CKD_SHA1_KDF_CONCATENATE 0x00000004 #define CKD_SHA224_KDF 0x00000005 #define CKD_SHA256_KDF 0x00000006 #define CKD_SHA384_KDF 0x00000007 #define CKD_SHA512_KDF 0x00000008 #define CKD_CPDIVERSIFY_KDF 0x00000009 #define CKD_SHA3_224_KDF 0x0000000A #define CKD_SHA3_256_KDF 0x0000000B #define CKD_SHA3_384_KDF 0x0000000C #define CKD_SHA3_512_KDF 0x0000000D #define CKD_SHA1_KDF_SP800 0x0000000E #define CKD_SHA224_KDF_SP800 0x0000000F #define CKD_SHA256_KDF_SP800 0x00000010 #define CKD_SHA384_KDF_SP800 0x00000011 #define CKD_SHA512_KDF_SP800 0x00000012 #define CKD_SHA3_224_KDF_SP800 0x00000013 #define CKD_SHA3_256_KDF_SP800 0x00000014 #define CKD_SHA3_384_KDF_SP800 0x00000015 #define CKD_SHA3_512_KDF_SP800 0x00000016 #define CKD_BLAKE2B_160_KDF 0x00000017 #define CKD_BLAKE2B_256_KDF 0x00000018 #define CKD_BLAKE2B_384_KDF 0x00000019 #define CKD_BLAKE2B_512_KDF 0x0000001a #define CKP_PKCS5_PBKD2_HMAC_SHA1 0x00000001 #define CKP_PKCS5_PBKD2_HMAC_GOSTR3411 0x00000002 #define CKP_PKCS5_PBKD2_HMAC_SHA224 0x00000003 #define CKP_PKCS5_PBKD2_HMAC_SHA256 0x00000004 #define CKP_PKCS5_PBKD2_HMAC_SHA384 0x00000005 #define CKP_PKCS5_PBKD2_HMAC_SHA512 0x00000006 #define CKP_PKCS5_PBKD2_HMAC_SHA512_224 0x00000007 #define CKP_PKCS5_PBKD2_HMAC_SHA512_256 0x00000008 #define CKZ_SALT_SPECIFIED 0x00000001 %include "pkcs11lib.h" class CK_ATTRIBUTE_SMART { public: void Reset(); void ResetValue(); void Reserve(long len); unsigned long GetType() const; void SetType(unsigned long attrType); int GetLen() const; bool IsString() const; bool IsBool() const; bool IsNum() const; bool IsAttributeList() const; bool IsBin() const; PyKCS11String GetString() const; void SetString(unsigned long attrType, const char* szValue); long GetNum() const; void SetNum(unsigned long attrType, unsigned long ulValue); bool GetBool() const; void SetBool(unsigned long attrType, bool bValue); void SetList(unsigned long attrType, const vector& val); vector GetBin(); void SetBin(unsigned long attrType, const vector& pBuf); }; ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1548190164.0 pykcs11-1.5.17/src/pykcs11string.cpp0000644000076500000240000000261713421700724016714 0ustar00rousseaustaff// Copyright (C) 2004 Midori (midori -- a-t -- paipai dot net) // // This file is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program 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 // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. #include "stdafx.h" #include "pykcs11string.h" PyKCS11String::PyKCS11String() {} PyKCS11String::PyKCS11String(unsigned char* pBuf, int len) { int i; if (m_str.max_size() < (size_t)len) m_str.reserve(len); for (i=0; i < len; i++) m_str.push_back((char)pBuf[i]); } PyKCS11String::PyKCS11String(const char* str):m_str(str) { } PyKCS11String::PyKCS11String(basic_string str):m_str(str) { } PyKCS11String::PyKCS11String(vector bin_str) { if (m_str.max_size() < bin_str.size()) m_str.reserve(bin_str.size()); size_t iSize = bin_str.size(); size_t i; for (i=0; i < iSize; i++) m_str.push_back(bin_str[i]); } ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1548190164.0 pykcs11-1.5.17/src/pykcs11string.h0000644000076500000240000000212713421700724016355 0ustar00rousseaustaff// Copyright (C) 2004 Midori (midori -- a-t -- paipai dot net) // // This file is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program 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 // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. #pragma once #include #include using namespace std; typedef struct PyKCS11String { PyKCS11String(); PyKCS11String(unsigned char* pBuf, int len); PyKCS11String(const char* str); PyKCS11String(basic_string str); PyKCS11String(vector bin_str); basic_string m_str; }PyKCS11String; ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1548190164.0 pykcs11-1.5.17/src/stdafx.h0000644000076500000240000000241613421700724015125 0ustar00rousseaustaff// Copyright (C) 2004 Midori (midori -- a-t -- paipai dot net) // // This file is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program 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 // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include #include #include #include using namespace std; #ifdef WIN32 #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files: #include #endif #include "opensc/pkcs11.h" // TODO: reference additional headers your program requires here ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1548190164.0 pykcs11-1.5.17/src/utility.cpp0000644000076500000240000000457413421700724015701 0ustar00rousseaustaff// Copyright (C) 2004 Midori (midori -- a-t -- paipai dot net) // // This file is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program 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 // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. #include "stdafx.h" #include #include "pykcs11string.h" #include "ck_attribute_smart.h" #include "pkcs11lib.h" #include "utility.h" using namespace std; unsigned char * Vector2Buffer(vector &Buf, CK_ULONG &Len) { Len = (CK_ULONG)Buf.size(); if (!Len) return NULL; CK_ULONG i; unsigned char *pBuf = new unsigned char[Len]; for (i = 0; i &Buf, bool bAllocIfNull) { Buf.clear(); if (!pBuf & bAllocIfNull) Buf = vector(Len); else { Buf.reserve(Len); CK_ULONG i; for (i = 0; i &Attr, CK_ULONG &Len) { Len = (CK_ULONG) Attr.size(); if (!Len) return NULL; CK_ULONG i; CK_ATTRIBUTE_PTR pTemplate = new CK_ATTRIBUTE[Len]; for (i=0; i< Len; i++) { pTemplate[i].type = Attr[i].GetType(); pTemplate[i].pValue = Vector2Buffer(Attr[i].GetBin(), pTemplate[i].ulValueLen); } return pTemplate; } void Template2AttrVector(CK_ATTRIBUTE_PTR pTemplate, CK_ULONG Len, vector &Attr) { CK_ULONG i; for (i=0; i &Buf, CK_ULONG &Len); CK_ATTRIBUTE_PTR AttrVector2Template(vector &Attr, CK_ULONG &Len); void Template2AttrVector(CK_ATTRIBUTE_PTR pTemplate, CK_ULONG Len, vector &Attr); void DestroyTemplate(CK_ATTRIBUTE_PTR &pTemplate, CK_ULONG Len); void Buffer2Vector(unsigned char* pBuf, CK_ULONG Len, vector &Buf, bool bAllocIfNull); #endif //_UTILITY_H__DEFINED_ ././@PaxHeader0000000000000000000000000000003300000000000010211 xustar0027 mtime=1729078230.137195 pykcs11-1.5.17/test/0000755000076500000240000000000014703721726013661 5ustar00rousseaustaff././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1662224040.0 pykcs11-1.5.17/test/test_CK.py0000644000076500000240000000130014304703250015546 0ustar00rousseaustaff#! /usr/bin/env python # execute using: # python test/test_CK.py import unittest import PyKCS11 class TestUtil(unittest.TestCase): def test_CKM(self): self.assertEqual(PyKCS11.CKM_RSA_PKCS_KEY_PAIR_GEN, 0x00000000) self.assertEqual( PyKCS11.CKM[PyKCS11.CKM_RSA_PKCS_KEY_PAIR_GEN], "CKM_RSA_PKCS_KEY_PAIR_GEN" ) self.assertEqual(PyKCS11.CKM_VENDOR_DEFINED, 0x80000000) def test_CKR(self): self.assertEqual(PyKCS11.CKR_VENDOR_DEFINED, 0x80000000) def test_CKH(self): self.assertEqual(PyKCS11.CKH_USER_INTERFACE, 3) self.assertEqual(PyKCS11.CKH['CKH_USER_INTERFACE'], 3) if __name__ == "__main__": unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1680465794.0 pykcs11-1.5.17/test/test_LowLevel.py0000644000076500000240000001121414412357602017015 0ustar00rousseaustaffimport unittest from PyKCS11 import ckbytelist import PyKCS11.LowLevel import os import platform class TestUtil(unittest.TestCase): def test_LowLevel(self): a = PyKCS11.LowLevel.CPKCS11Lib() self.assertIsNotNone(a) # File not found self.assertEqual(a.Load("NoFile"), -1) # C_GetFunctionList() not found if platform.system() == 'Linux': # GNU/Linux lib = "libc.so.6" elif platform.system() == 'Darwin': # macOS lib = "/usr/lib/libSystem.B.dylib" else: # Windows lib = "WinSCard.dll" self.assertEqual(a.Load(lib), -4) info = PyKCS11.LowLevel.CK_INFO() self.assertIsNotNone(info) slotInfo = PyKCS11.LowLevel.CK_SLOT_INFO() self.assertIsNotNone(slotInfo) lib = os.getenv("PYKCS11LIB") if lib is None: raise (Exception("Define PYKCS11LIB")) session = PyKCS11.LowLevel.CK_SESSION_HANDLE() self.assertIsNotNone(session) sessionInfo = PyKCS11.LowLevel.CK_SESSION_INFO() self.assertIsNotNone(sessionInfo) tokenInfo = PyKCS11.LowLevel.CK_TOKEN_INFO() self.assertIsNotNone(tokenInfo) slotList = PyKCS11.LowLevel.ckintlist() self.assertIsNotNone(slotList) a.Load(lib) self.assertEqual(a.C_GetInfo(info), PyKCS11.LowLevel.CKR_OK) manufacturerID = info.GetManufacturerID() self.assertEqual(manufacturerID, "SoftHSM".ljust(32)) del info a.C_GetSlotList(0, slotList) slot = slotList[0] self.assertEqual(a.C_GetSlotInfo(slot, slotInfo), PyKCS11.LowLevel.CKR_OK) self.assertEqual( a.C_OpenSession( slot, PyKCS11.LowLevel.CKF_SERIAL_SESSION | PyKCS11.LowLevel.CKF_RW_SESSION, session, ), PyKCS11.LowLevel.CKR_OK, ) self.assertEqual( a.C_GetSessionInfo(session, sessionInfo), PyKCS11.LowLevel.CKR_OK ) self.assertEqual(a.C_GetTokenInfo(slot, tokenInfo), PyKCS11.LowLevel.CKR_OK) label = tokenInfo.GetLabel() manufacturerID = tokenInfo.GetManufacturerID() flags = tokenInfo.flags model = tokenInfo.GetModel() pin = ckbytelist("1234") self.assertEqual( a.C_Login(session, PyKCS11.LowLevel.CKU_USER, pin), PyKCS11.LowLevel.CKR_OK ) self.assertEqual(a.C_Logout(session), PyKCS11.LowLevel.CKR_OK) self.assertEqual(a.C_CloseSession(session), PyKCS11.LowLevel.CKR_OK) self.assertEqual( a.C_OpenSession(slotList[0], PyKCS11.LowLevel.CKF_SERIAL_SESSION, session), PyKCS11.LowLevel.CKR_OK, ) self.assertEqual( a.C_Login(session, PyKCS11.LowLevel.CKU_USER, pin), PyKCS11.LowLevel.CKR_OK ) SearchResult = PyKCS11.LowLevel.ckobjlist(10) SearchTemplate = PyKCS11.LowLevel.ckattrlist(2) SearchTemplate[0].SetNum( PyKCS11.LowLevel.CKA_CLASS, PyKCS11.LowLevel.CKO_CERTIFICATE ) SearchTemplate[1].SetBool(PyKCS11.LowLevel.CKA_TOKEN, True) self.assertEqual( a.C_FindObjectsInit(session, SearchTemplate), PyKCS11.LowLevel.CKR_OK ) self.assertEqual( a.C_FindObjects(session, SearchResult), PyKCS11.LowLevel.CKR_OK ) self.assertEqual(a.C_FindObjectsFinal(session), PyKCS11.LowLevel.CKR_OK) for x in SearchResult: print("object: " + hex(x.value())) valTemplate = PyKCS11.LowLevel.ckattrlist(2) valTemplate[0].SetType(PyKCS11.LowLevel.CKA_LABEL) # valTemplate[0].Reserve(128) valTemplate[1].SetType(PyKCS11.LowLevel.CKA_CLASS) # valTemplate[1].Reserve(4) print( "C_GetAttributeValue(): " + hex(a.C_GetAttributeValue(session, x, valTemplate)) ) print( "CKA_LABEL Len: ", valTemplate[0].GetLen(), " CKA_CLASS Len: ", valTemplate[1].GetLen(), ) print( "C_GetAttributeValue(): " + hex(a.C_GetAttributeValue(session, x, valTemplate)) ) print("\tCKO_CERTIFICATE: " + valTemplate[0].GetString()) print("\tCKA_TOKEN: " + str(valTemplate[1].GetNum())) self.assertEqual(a.C_Logout(session), PyKCS11.LowLevel.CKR_OK) self.assertEqual(a.C_CloseSession(session), PyKCS11.LowLevel.CKR_OK) self.assertEqual(a.C_Finalize(), PyKCS11.LowLevel.CKR_OK) a.Unload() if __name__ == "__main__": unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1724000275.0 pykcs11-1.5.17/test/test_asymetric.py0000644000076500000240000001632614660424023017272 0ustar00rousseaustaffimport unittest from PyKCS11 import PyKCS11 class TestUtil(unittest.TestCase): def setUp(self): self.pkcs11 = PyKCS11.PyKCS11Lib() self.pkcs11.load() # get SoftHSM major version info = self.pkcs11.getInfo() self.SoftHSMversion = info.libraryVersion[0] self.manufacturer = info.manufacturerID self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0] self.session = self.pkcs11.openSession( self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION ) self.session.login("1234") keyID = (0x22,) pubTemplate = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_PUBLIC_KEY), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE), (PyKCS11.CKA_MODULUS_BITS, 0x0400), (PyKCS11.CKA_PUBLIC_EXPONENT, (0x01, 0x00, 0x01)), (PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_VERIFY, PyKCS11.CK_TRUE), (PyKCS11.CKA_VERIFY_RECOVER, PyKCS11.CK_TRUE), (PyKCS11.CKA_WRAP, PyKCS11.CK_TRUE), (PyKCS11.CKA_LABEL, "My Public Key"), (PyKCS11.CKA_ID, keyID), ] privTemplate = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_PRIVATE_KEY), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_TRUE), (PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_SIGN, PyKCS11.CK_TRUE), (PyKCS11.CKA_SIGN_RECOVER, PyKCS11.CK_TRUE), (PyKCS11.CKA_UNWRAP, PyKCS11.CK_TRUE), (PyKCS11.CKA_ID, keyID), ] (self.pubKey, self.privKey) = self.session.generateKeyPair( pubTemplate, privTemplate ) self.assertIsNotNone(self.pubKey) self.assertIsNotNone(self.privKey) def tearDown(self): self.session.destroyObject(self.pubKey) self.session.destroyObject(self.privKey) self.session.logout() self.pkcs11.closeAllSessions(self.slot) self.pkcs11.unload() del self.pkcs11 def test_sign_integer(self): toSign = 1234567890 mecha = PyKCS11.Mechanism(PyKCS11.CKM_SHA1_RSA_PKCS, None) # sign/verify try: self.session.sign(self.privKey, toSign, mecha) except PyKCS11.PyKCS11Error as e: self.assertEqual(e.value, -3) def test_sign_PKCS(self): toSign = "Hello world" mecha = PyKCS11.Mechanism(PyKCS11.CKM_SHA1_RSA_PKCS, None) # sign/verify signature = self.session.sign(self.privKey, toSign, mecha) result = self.session.verify(self.pubKey, toSign, signature, mecha) self.assertTrue(result) def test_sign_PKCS_SHA256(self): toSign = "Hello world" mecha = PyKCS11.Mechanism(PyKCS11.CKM_SHA256_RSA_PKCS, None) # sign/verify signature = self.session.sign(self.privKey, toSign, mecha) result = self.session.verify(self.pubKey, toSign, signature, mecha) self.assertTrue(result) def test_sign_X509(self): toSign = "Hello world" mecha = PyKCS11.Mechanism(PyKCS11.CKM_RSA_X_509, None) if self.SoftHSMversion < 2: self.skipTest("RSA X.509 only supported by SoftHSM >= 2") # sign/verify signature = self.session.sign(self.privKey, toSign, mecha) result = self.session.verify(self.pubKey, toSign, signature, mecha) self.assertTrue(result) def test_encrypt_PKCS(self): # encrypt/decrypt using CMK_RSA_PKCS (default) dataIn = "Hello world" encrypted = self.session.encrypt(self.pubKey, dataIn) decrypted = self.session.decrypt(self.privKey, encrypted) # convert in a string text = "".join(map(chr, decrypted)) self.assertEqual(dataIn, text) def test_encrypt_X509(self): if self.SoftHSMversion < 2: self.skipTest("RSA X.509 only supported by SoftHSM >= 2") # encrypt/decrypt using CKM_RSA_X_509 dataIn = "Hello world!" mecha = PyKCS11.Mechanism(PyKCS11.CKM_RSA_X_509, None) encrypted = self.session.encrypt(self.pubKey, dataIn, mecha=mecha) decrypted = self.session.decrypt(self.privKey, encrypted, mecha=mecha) # remove padding NUL bytes padding_length = 0 for e in decrypted: if e != 0: break padding_length += 1 decrypted = list(decrypted)[padding_length:] # convert in a string text = "".join(map(chr, decrypted)) self.assertEqual(dataIn, text) def test_RSA_OAEP(self): if self.SoftHSMversion < 2: self.skipTest("RSA OAEP only supported by SoftHSM >= 2") # RSA OAEP plainText = "A test string" mech = PyKCS11.RSAOAEPMechanism(PyKCS11.CKM_SHA_1, PyKCS11.CKG_MGF1_SHA1) cipherText = self.session.encrypt(self.pubKey, plainText, mech) decrypted = self.session.decrypt(self.privKey, cipherText, mech) text = "".join(map(chr, decrypted)) self.assertEqual(text, plainText) def test_RSA_OAEPwithAAD(self): # AAD is "Additional Authentication Data" # (pSourceData of CK_RSA_PKCS_OAEP_PARAMS struct) if self.SoftHSMversion < 2: self.skipTest("RSA OAEP only supported by SoftHSM >= 2") if self.manufacturer.startswith("SoftHSM"): # SoftHSM indicates in syslog: # "SoftHSM.cpp(12412): pSourceData must be NULL" # and returns CKR_ARGUMENTS_BAD self.skipTest("'AAD' not (yet) supported.") plainText = "A test string" # RSA OAEP aad = "sample aad".encode("utf-8") mech = PyKCS11.RSAOAEPMechanism(PyKCS11.CKM_SHA_1, PyKCS11.CKG_MGF1_SHA1, aad) cipherText = self.session.encrypt(self.pubKey, plainText, mech) decrypted = self.session.decrypt(self.privKey, cipherText, mech) text = bytes(decrypted).decode("utf-8") self.assertEqual(text, plainText) def test_RSA_PSS_SHA1(self): if self.SoftHSMversion < 2: self.skipTest("RSA PSS only supported by SoftHSM >= 2") # RSA PSS toSign = "test_RSA_sign_PSS SHA1" mech = PyKCS11.RSA_PSS_Mechanism( PyKCS11.CKM_SHA1_RSA_PKCS_PSS, PyKCS11.CKM_SHA_1, PyKCS11.CKG_MGF1_SHA1, 20 # size of SHA1 result ) signature = self.session.sign(self.privKey, toSign, mech) result = self.session.verify(self.pubKey, toSign, signature, mech) self.assertTrue(result) def test_RSA_PSS_SHA256(self): if self.SoftHSMversion < 2: self.skipTest("RSA PSS only supported by SoftHSM >= 2") # RSA PSS toSign = "test_RSA_sign_PSS SHA256" mech = PyKCS11.RSA_PSS_Mechanism( PyKCS11.CKM_SHA256_RSA_PKCS_PSS, PyKCS11.CKM_SHA256, PyKCS11.CKG_MGF1_SHA256, 32 # size of SHA256 result ) signature = self.session.sign(self.privKey, toSign, mech) result = self.session.verify(self.pubKey, toSign, signature, mech) self.assertTrue(result) def test_pubKey(self): # test CK_OBJECT_HANDLE.__repr__() text = str(self.pubKey) self.assertIsNotNone(text) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1695485116.0 pykcs11-1.5.17/test/test_asymetric_ECC.py0000644000076500000240000000637314503606274017753 0ustar00rousseaustaffimport unittest from PyKCS11 import PyKCS11 from asn1crypto.keys import ECDomainParameters, NamedCurve class TestUtil(unittest.TestCase): def setUp(self): self.pkcs11 = PyKCS11.PyKCS11Lib() self.pkcs11.load() # get SoftHSM major version self.SoftHSMversion = self.pkcs11.getInfo().libraryVersion[0] self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0] self.session = self.pkcs11.openSession( self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION ) self.session.login("1234") # Select the curve to be used for the keys curve = u"secp256r1" # Setup the domain parameters, unicode conversion needed # for the curve string domain_params = ECDomainParameters(name="named", value=NamedCurve(curve)) ec_params = domain_params.dump() keyID = (0x22,) label = "test" ec_public_tmpl = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_PUBLIC_KEY), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_VERIFY, PyKCS11.CK_TRUE), (PyKCS11.CKA_WRAP, PyKCS11.CK_TRUE), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_ECDSA), (PyKCS11.CKA_EC_PARAMS, ec_params), (PyKCS11.CKA_LABEL, label), (PyKCS11.CKA_ID, keyID), ] ec_priv_tmpl = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_PRIVATE_KEY), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_ECDSA), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_SENSITIVE, PyKCS11.CK_TRUE), (PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_SIGN, PyKCS11.CK_TRUE), (PyKCS11.CKA_UNWRAP, PyKCS11.CK_TRUE), (PyKCS11.CKA_LABEL, label), (PyKCS11.CKA_ID, keyID), ] if self.SoftHSMversion < 2: self.skipTest("ECDSA only supported by SoftHSM >= 2") (self.pubKey, self.privKey) = self.session.generateKeyPair( ec_public_tmpl, ec_priv_tmpl, mecha=PyKCS11.MechanismECGENERATEKEYPAIR ) self.assertIsNotNone(self.pubKey) self.assertIsNotNone(self.privKey) # test CK_OBJECT_HANDLE.__repr__() text = str(self.pubKey) self.assertIsNotNone(text) def tearDown(self): self.session.destroyObject(self.pubKey) self.session.destroyObject(self.privKey) self.session.logout() self.pkcs11.closeAllSessions(self.slot) del self.pkcs11 def test_sign_integer(self): toSign = 1234567890 mecha = PyKCS11.Mechanism(PyKCS11.CKM_ECDSA, None) # sign/verify try: self.session.sign(self.privKey, toSign, mecha) except PyKCS11.PyKCS11Error as e: # should return PyKCS11.PyKCS11Error: Unknown format () self.assertEqual(e.value, -3) def test_sign_text(self): toSign = "Hello World!" mecha = PyKCS11.Mechanism(PyKCS11.CKM_ECDSA, None) # sign/verify signature = self.session.sign(self.privKey, toSign, mecha) result = self.session.verify(self.pubKey, toSign, signature, mecha) self.assertTrue(result) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1724000275.0 pykcs11-1.5.17/test/test_asymetric_gost.py0000644000076500000240000000562714660424023020330 0ustar00rousseaustaffimport unittest from PyKCS11 import PyKCS11 class TestUtil(unittest.TestCase): def setUp(self): self.pkcs11 = PyKCS11.PyKCS11Lib() self.pkcs11.load() # get SoftHSM major version self.SoftHSMversion = self.pkcs11.getInfo().libraryVersion[0] self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0] self.session = self.pkcs11.openSession( self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION ) self.session.login("1234") def tearDown(self): self.session.logout() self.pkcs11.closeAllSessions(self.slot) self.pkcs11.unload() del self.pkcs11 def test_gost(self): if self.SoftHSMversion < 2: self.skipTest("generateKeyPair() only supported by SoftHSM >= 2") # values from SoftHSMv2 param_a = (0x06, 0x07, 0x2A, 0x85, 0x03, 0x02, 0x02, 0x23, 0x01) param_b = (0x06, 0x07, 0x2A, 0x85, 0x03, 0x02, 0x02, 0x1E, 0x01) keyID = (0x23,) pubTemplate = [ (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE), (PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_VERIFY, PyKCS11.CK_TRUE), (PyKCS11.CKA_WRAP, PyKCS11.CK_TRUE), (PyKCS11.CKA_LABEL, "My Public Key"), (PyKCS11.CKA_ID, keyID), (PyKCS11.CKA_GOSTR3410_PARAMS, param_a), (PyKCS11.CKA_GOSTR3411_PARAMS, param_b), ] privTemplate = [ (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_TRUE), (PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_SIGN, PyKCS11.CK_TRUE), (PyKCS11.CKA_UNWRAP, PyKCS11.CK_TRUE), (PyKCS11.CKA_ID, keyID), ] # test generate gost key pair gen_mechanism = PyKCS11.Mechanism(PyKCS11.CKM_GOSTR3410_KEY_PAIR_GEN, None) try: (self.pubKey, self.privKey) = self.session.generateKeyPair( pubTemplate, privTemplate, gen_mechanism ) except PyKCS11.PyKCS11Error as e: if e.value == PyKCS11.CKR_MECHANISM_INVALID: self.skipTest("GOST not supported by SoftHSMv2 on Windows?") else: raise self.assertIsNotNone(self.pubKey) self.assertIsNotNone(self.privKey) # test sign GOSTR3410_WITH_GOSTR3411 toSign = "Hello world" mecha = PyKCS11.Mechanism(PyKCS11.CKM_GOSTR3410_WITH_GOSTR3411, None) # sign/verify signature = self.session.sign(self.privKey, toSign, mecha) result = self.session.verify(self.pubKey, toSign, signature, mecha) self.assertTrue(result) # test CK_OBJECT_HANDLE.__repr__() text = str(self.pubKey) self.assertIsNotNone(text) self.session.destroyObject(self.pubKey) self.session.destroyObject(self.privKey) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1724417671.0 pykcs11-1.5.17/test/test_ckbytelist.py0000644000076500000240000000440314662103207017440 0ustar00rousseaustaffimport unittest import PyKCS11 class Testutil(unittest.TestCase): def test_empty(self): ck = PyKCS11.ckbytelist() self.assertSequenceEqual(ck, []) def test_resize(self): ck = PyKCS11.ckbytelist() ck.resize(5) self.assertSequenceEqual(ck, [0, 0, 0, 0, 0]) def test_data(self): ck = PyKCS11.ckbytelist([0] * 5) for index in range(5): ck[index] = index self.assertSequenceEqual(ck, [0, 1, 2, 3, 4]) def test_append(self): ck = PyKCS11.ckbytelist() for index in range(5): ck.append(index) self.assertSequenceEqual(ck, [0, 1, 2, 3, 4]) def test_length0(self): ck = PyKCS11.ckbytelist() self.assertEqual(len(ck), 0) def test_length5(self): ck = PyKCS11.ckbytelist([0] * 5) self.assertEqual(len(ck), 5) def test_string(self): ck = PyKCS11.ckbytelist() ck.resize(5) for index in range(5): ck[index] = index self.assertEqual(str(ck), "[0, 1, 2, 3, 4]") def test_init_list0(self): ck = PyKCS11.ckbytelist([]) self.assertSequenceEqual(ck, []) def test_init_list1(self): ck = PyKCS11.ckbytelist([1]) self.assertSequenceEqual(ck, [1]) def test_init_list5(self): ck = PyKCS11.ckbytelist([0, 1, 2, 3, 4]) self.assertSequenceEqual(ck, [0, 1, 2, 3, 4]) def test_init_str(self): ck = PyKCS11.ckbytelist("ABC") self.assertSequenceEqual(ck, [65, 66, 67]) def test_init_bytes(self): ck = PyKCS11.ckbytelist(b"ABC") self.assertSequenceEqual(ck, [65, 66, 67]) def test_init_ckbytelist(self): ck1 = PyKCS11.ckbytelist(b"ABC") ck2 = PyKCS11.ckbytelist(ck1) self.assertSequenceEqual(ck2, [65, 66, 67]) def test_unknown_format(self): with self.assertRaises(PyKCS11.PyKCS11Error) as cm: PyKCS11.ckbytelist(dict()) the_exception = cm.exception self.assertEqual(the_exception.value, -3) # Python 3 and later type_str = "" self.assertEqual(the_exception.text, type_str) self.assertEqual(str(the_exception), "Unknown format (%s)" % type_str) if __name__ == "__main__": unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1724000275.0 pykcs11-1.5.17/test/test_derive.py0000644000076500000240000003114014660424023016537 0ustar00rousseaustaffimport unittest from asn1crypto.keys import ECDomainParameters, NamedCurve from PyKCS11 import PyKCS11 class TestUtil(unittest.TestCase): def setUp(self): self.pkcs11 = PyKCS11.PyKCS11Lib() self.pkcs11.load() # get SoftHSM major version info = self.pkcs11.getInfo() self.SoftHSMversion = info.libraryVersion self.manufacturer = info.manufacturerID self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0] self.session = self.pkcs11.openSession( self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION ) self.session.login("1234") # common templates used in derive test cases self.aesKeyTemplate = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES), (PyKCS11.CKA_VALUE_LEN, 32), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_SENSITIVE, PyKCS11.CK_FALSE), (PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_TRUE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_TRUE), (PyKCS11.CKA_LABEL, "DeriveTestBaseAes256Key"), (PyKCS11.CKA_DERIVE, PyKCS11.CK_TRUE), ] self.genericKeyTemplate = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_GENERIC_SECRET), (PyKCS11.CKA_TOKEN, PyKCS11.CK_FALSE), (PyKCS11.CKA_SENSITIVE, PyKCS11.CK_FALSE), (PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_TRUE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_TRUE), (PyKCS11.CKA_LABEL, "DeriveTestGenericKey"), ] # generate a common symmetric base key for tests keyID = (0x01,) baseKeyTemplate = self.aesKeyTemplate + [(PyKCS11.CKA_ID, keyID)] mechanism = PyKCS11.Mechanism(PyKCS11.CKM_AES_KEY_GEN, None) self.baseKey = self.session.generateKey(baseKeyTemplate, mechanism) self.assertIsNotNone(self.baseKey) # Select the curve to be used for the keys curve = u"secp256r1" # Setup the domain parameters, unicode conversion needed # for the curve string domain_params = ECDomainParameters(name="named", value=NamedCurve(curve)) self.ecParams = domain_params.dump() keyID = (0x01,) baseKeyPubTemplate = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_PUBLIC_KEY), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_VERIFY, PyKCS11.CK_TRUE), (PyKCS11.CKA_WRAP, PyKCS11.CK_TRUE), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_ECDSA), (PyKCS11.CKA_EC_PARAMS, self.ecParams), (PyKCS11.CKA_LABEL, "TestBaseKeyP256"), (PyKCS11.CKA_ID, keyID), ] baseKeyPvtTemplate = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_PRIVATE_KEY), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_ECDSA), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_SENSITIVE, PyKCS11.CK_TRUE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE), (PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_SIGN, PyKCS11.CK_TRUE), (PyKCS11.CKA_UNWRAP, PyKCS11.CK_TRUE), (PyKCS11.CKA_LABEL, "TestBaseKeyP256"), (PyKCS11.CKA_ID, keyID), (PyKCS11.CKA_DERIVE, PyKCS11.CK_TRUE), ] mechanism = PyKCS11.Mechanism(PyKCS11.CKM_EC_KEY_PAIR_GEN, None) self.baseEcPubKey, self.baseEcPvtKey = self.session.generateKeyPair(baseKeyPubTemplate, baseKeyPvtTemplate, mechanism) self.assertIsNotNone(self.baseEcPubKey) self.assertIsNotNone(self.baseEcPvtKey) def tearDown(self): self.session.destroyObject(self.baseEcPubKey) self.session.destroyObject(self.baseEcPvtKey) self.session.logout() self.pkcs11.closeAllSessions(self.slot) self.pkcs11.unload() del self.pkcs11 def getCkaValue(self, key): return list( self.session.getAttributeValue( key, [PyKCS11.CKA_VALUE])[0] ) def test_deriveKey_ECDH1_DERIVE(self): if self.SoftHSMversion[0] < 2: self.skipTest("generateKeyPair() only supported by SoftHSM >= 2") keyID = (0x11,) pubTemplate = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_PUBLIC_KEY), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE), (PyKCS11.CKA_TOKEN, PyKCS11.CK_FALSE), (PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_VERIFY, PyKCS11.CK_TRUE), (PyKCS11.CKA_WRAP, PyKCS11.CK_TRUE), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_ECDSA), (PyKCS11.CKA_EC_PARAMS, self.ecParams), (PyKCS11.CKA_LABEL, "testKeyP256"), (PyKCS11.CKA_ID, keyID), ] pvtTemplate = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_PRIVATE_KEY), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_ECDSA), (PyKCS11.CKA_TOKEN, PyKCS11.CK_FALSE), (PyKCS11.CKA_SENSITIVE, PyKCS11.CK_TRUE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_TRUE), (PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_SIGN, PyKCS11.CK_TRUE), (PyKCS11.CKA_UNWRAP, PyKCS11.CK_TRUE), (PyKCS11.CKA_LABEL, "testKeyP256"), (PyKCS11.CKA_ID, keyID), (PyKCS11.CKA_DERIVE, PyKCS11.CK_TRUE), ] mechanism = PyKCS11.Mechanism(PyKCS11.CKM_EC_KEY_PAIR_GEN, None) pubKey, pvtKey = self.session.generateKeyPair(pubTemplate, pvtTemplate, mechanism) self.assertIsNotNone(pubKey) self.assertIsNotNone(pvtKey) keyID = (0x22,) derivedAESKeyTemplate = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES), (PyKCS11.CKA_TOKEN, PyKCS11.CK_FALSE), (PyKCS11.CKA_SENSITIVE, PyKCS11.CK_TRUE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_TRUE), (PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_SIGN, PyKCS11.CK_FALSE), (PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_TRUE), (PyKCS11.CKA_VERIFY, PyKCS11.CK_FALSE), (PyKCS11.CKA_VALUE_LEN, 24), (PyKCS11.CKA_LABEL, "derivedAESKey"), (PyKCS11.CKA_ID, keyID), ] # derive key 1 : self.basePvtKey + pubKey attrs = self.session.getAttributeValue(pubKey, [PyKCS11.CKA_EC_POINT], True) mechanism = PyKCS11.ECDH1_DERIVE_Mechanism(bytes(attrs[0])) derivedKey = self.session.deriveKey(self.baseEcPvtKey, derivedAESKeyTemplate, mechanism) self.assertIsNotNone(derivedKey) # derive key 2 : pvtKey + self.basePubKey attrs = self.session.getAttributeValue(self.baseEcPubKey, [PyKCS11.CKA_EC_POINT], True) mechanism = PyKCS11.ECDH1_DERIVE_Mechanism(bytes(attrs[0])) derivedKey2 = self.session.deriveKey(pvtKey, derivedAESKeyTemplate, mechanism) self.assertIsNotNone(derivedKey2) DataIn = "Sample data to test ecdh1 derive".encode("utf-8") mechanism = PyKCS11.Mechanism(PyKCS11.CKM_AES_CBC, "1234567812345678") DataOut = self.session.encrypt(derivedKey, DataIn, mechanism) DataCheck = self.session.decrypt(derivedKey2, DataOut, mechanism) # match check values self.assertSequenceEqual(DataIn, DataCheck) # cleanup self.session.destroyObject(derivedKey) self.session.destroyObject(derivedKey2) self.session.destroyObject(pubKey) self.session.destroyObject(pvtKey) def test_deriveKey_CKM_CONCATENATE_BASE_AND_KEY(self): # This mechanism is not supported in the current release of SoftHSM (2.6.1), however available in develop branch, # see https://github.com/opendnssec/SoftHSMv2/commit/fa595c07a185656382c18ea2a6a12cad825d48b4 if self.SoftHSMversion <= (2,6): self.skipTest("CKM_CONCATENATE_BASE_AND_KEY is not supported by SoftHSM <= 2.6") # generate a key to concatenate with keyID = (0x11,) concatenateKeyTemplate = self.aesKeyTemplate + [(PyKCS11.CKA_ID, keyID)] mechanism = PyKCS11.Mechanism(PyKCS11.CKM_AES_KEY_GEN, None) concKey = self.session.generateKey(concatenateKeyTemplate, mechanism) self.assertIsNotNone(concKey) # concatenate two keys keyID = (0x22,) derivedKeyTemplate = self.genericKeyTemplate + [ (PyKCS11.CKA_VALUE_LEN, 64), (PyKCS11.CKA_ID, keyID) ] mechanism = PyKCS11.CONCATENATE_BASE_AND_KEY_Mechanism(concKey) derivedKey = self.session.deriveKey( self.baseKey, derivedKeyTemplate, mechanism) self.assertIsNotNone(derivedKey) # check derived key's value baseKeyValue = self.getCkaValue(self.baseKey) concKeyValue = self.getCkaValue(concKey) derivedKeyValue = self.getCkaValue(derivedKey) # match: check values self.assertSequenceEqual(baseKeyValue + concKeyValue, derivedKeyValue) # cleanup self.session.destroyObject(derivedKey) self.session.destroyObject(concKey) def test_deriveKey_CKM_CONCATENATE_BASE_AND_DATA(self): # This mechanism is not supported in the current release of SoftHSM (2.6.1), however available in develop branch, # see https://github.com/opendnssec/SoftHSMv2/commit/dba00d73e1b69f65b68397d235e7f73bbf59ab6a if self.SoftHSMversion <= (2,6): self.skipTest("CKM_CONCATENATE_BASE_AND_DATA is not supported by SoftHSM <= 2.6") # generate data to concatenate with concData = list(self.session.generateRandom(32)) # concatenate key with data keyID = (0x22,) derivedKeyTemplate = self.genericKeyTemplate + [ (PyKCS11.CKA_VALUE_LEN, 64), (PyKCS11.CKA_ID, keyID) ] mechanism = PyKCS11.CONCATENATE_BASE_AND_DATA_Mechanism(concData) derivedKey = self.session.deriveKey( self.baseKey, derivedKeyTemplate, mechanism) self.assertIsNotNone(derivedKey) # check derived key's value baseKeyValue = self.getCkaValue(self.baseKey) derivedKeyValue = self.getCkaValue(derivedKey) # match: check values self.assertSequenceEqual(baseKeyValue + concData, derivedKeyValue) # cleanup self.session.destroyObject(derivedKey) def test_deriveKey_CKM_CONCATENATE_DATA_AND_BASE(self): # This mechanism is not supported in the current release of SoftHSM (2.6.1), however available in develop branch, # see https://github.com/opendnssec/SoftHSMv2/commit/fae0d9f769ac30d25f563c5fc6c417e9199e4403 if self.SoftHSMversion <= (2,6): self.skipTest("CKM_CONCATENATE_DATA_AND_BASE is not supported by SoftHSM <= 2.6") # generate data to concatenate with concData = list(self.session.generateRandom(32)) # concatenate data with key keyID = (0x22,) derivedKeyTemplate = self.genericKeyTemplate + [ (PyKCS11.CKA_VALUE_LEN, 64), (PyKCS11.CKA_ID, keyID) ] mechanism = PyKCS11.CONCATENATE_DATA_AND_BASE_Mechanism(concData) derivedKey = self.session.deriveKey( self.baseKey, derivedKeyTemplate, mechanism) self.assertIsNotNone(derivedKey) # check derived key's value baseKeyValue = self.getCkaValue(self.baseKey) derivedKeyValue = self.getCkaValue(derivedKey) # match: check values self.assertSequenceEqual(concData + baseKeyValue, derivedKeyValue) # cleanup self.session.destroyObject(derivedKey) def test_deriveKey_CKM_XOR_BASE_AND_DATA(self): if self.manufacturer.startswith("SoftHSM"): self.skipTest("SoftHSM does not support CKM_XOR_BASE_AND_DATA") # generate data to xor with xorData = list(self.session.generateRandom(32)) # xor key with data keyID = (0x22,) derivedKeyTemplate = self.genericKeyTemplate + [ (PyKCS11.CKA_VALUE_LEN, 32), (PyKCS11.CKA_ID, keyID) ] mechanism = PyKCS11.XOR_BASE_AND_DATA_Mechanism(xorData) derivedKey = self.session.deriveKey( self.baseKey, derivedKeyTemplate, mechanism) self.assertIsNotNone(derivedKey) # check derived key's value baseKeyValue = self.getCkaValue(self.baseKey) derivedKeyValue = self.getCkaValue(derivedKey) expectedValue = map(lambda x, y: x ^ y, baseKeyValue, xorData) # match: check values self.assertSequenceEqual(list(expectedValue), derivedKeyValue) # cleanup self.session.destroyObject(derivedKey) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1555508732.0 pykcs11-1.5.17/test/test_digest.py0000644000076500000240000000204613455626774016565 0ustar00rousseaustaff#! /usr/bin/env python import unittest from PyKCS11 import PyKCS11 # SHA1 of "abc" SHA1_abc = [ 0xA9, 0x99, 0x3E, 0x36, 0x47, 0x6, 0x81, 0x6A, 0xBA, 0x3E, 0x25, 0x71, 0x78, 0x50, 0xC2, 0x6C, 0x9C, 0xD0, 0xD8, 0x9D, ] class TestUtil(unittest.TestCase): def setUp(self): self.pkcs11 = PyKCS11.PyKCS11Lib() self.pkcs11.load() self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0] self.session = self.pkcs11.openSession(self.slot, PyKCS11.CKF_SERIAL_SESSION) def tearDown(self): self.pkcs11.closeAllSessions(self.slot) del self.pkcs11 def test_digest(self): digest = self.session.digest("abc") self.assertSequenceEqual(digest, SHA1_abc) def test_digestSession(self): digestSession = self.session.digestSession() digestSession.update("abc") digest = digestSession.final() self.assertSequenceEqual(digest, SHA1_abc) if __name__ == "__main__": unittest.main() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1555508732.0 pykcs11-1.5.17/test/test_exception.py0000644000076500000240000000262013455626774017302 0ustar00rousseaustaffimport unittest import PyKCS11 class Testutil(unittest.TestCase): def test_empty(self): e = PyKCS11.PyKCS11Error(0) self.assertEqual(e.value, 0) def test_CKR_OK(self): e = PyKCS11.PyKCS11Error(PyKCS11.CKR_OK) self.assertEqual(e.value, 0) self.assertEqual(str(e), "CKR_OK (0x00000000)") def test_CKR_PIN_INVALID(self): e = PyKCS11.PyKCS11Error(PyKCS11.CKR_PIN_INVALID) self.assertEqual(e.value, 0xA1) self.assertEqual(str(e), "CKR_PIN_INVALID (0x000000A1)") def test_Load(self): e = PyKCS11.PyKCS11Error(-1, "Pouet") self.assertEqual(e.value, -1) self.assertEqual(str(e), "Load (Pouet)") def test_raise(self): with self.assertRaises(PyKCS11.PyKCS11Error): raise PyKCS11.PyKCS11Error(0) def test_unknown(self): e = PyKCS11.PyKCS11Error(PyKCS11.CKR_VENDOR_DEFINED - 1) self.assertEqual(str(e), "Unknown error (0x7FFFFFFF)") def test_vendor0(self): e = PyKCS11.PyKCS11Error(PyKCS11.CKR_VENDOR_DEFINED, "Pouet") self.assertEqual(e.value, PyKCS11.CKR_VENDOR_DEFINED) self.assertEqual(str(e), "Vendor error (0x00000000)") def test_vendor10(self): e = PyKCS11.PyKCS11Error(PyKCS11.CKR_VENDOR_DEFINED + 10) self.assertEqual(e.value, PyKCS11.CKR_VENDOR_DEFINED + 10) self.assertEqual(str(e), "Vendor error (0x0000000A)") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1704624694.0 pykcs11-1.5.17/test/test_gc.py0000644000076500000240000000167714546501066015674 0ustar00rousseaustaffimport unittest from PyKCS11 import PyKCS11 import gc class TestUtil(unittest.TestCase): def test_gc(self): res = list() # we must use at least 2 sessions for n in range(2): p11, session = self.createSession() res.append([p11, session]) for p11, session in res: self.closeSession(session) del p11 # force the call to __del__() on p11 now gc.collect() def createSession(self): pkcs11 = PyKCS11.PyKCS11Lib() pkcs11.load() slot = pkcs11.getSlotList(tokenPresent=True)[0] session = pkcs11.openSession( slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION ) return (pkcs11, session) def closeSession(self, session): # this call generated a CKR_CRYPTOKI_NOT_INITIALIZED for the # second session because C_Finalize() was already called session.logout() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1662224118.0 pykcs11-1.5.17/test/test_info.py0000644000076500000240000000321414304703366016222 0ustar00rousseaustaffimport unittest from PyKCS11 import PyKCS11 class TestUtil(unittest.TestCase): def setUp(self): self.pkcs11 = PyKCS11.PyKCS11Lib() self.pkcs11.load() self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0] self.manufacturerIDs = ("SoftHSM".ljust(32), "SoftHSM project".ljust(32)) def test_getInfo(self): info = self.pkcs11.getInfo() # check the CK_UTF8CHAR to string convertion self.assertEqual(info.manufacturerID, "SoftHSM".ljust(32)) self.assertEqual(info.libraryDescription, "Implementation of PKCS11".ljust(32)) text = str(info) self.assertIsNotNone(text) def test_getSlotInfo(self): info = self.pkcs11.getSlotInfo(self.slot) self.assertIn(info.manufacturerID, self.manufacturerIDs) text = str(info) self.assertIsNotNone(text) def test_getTokenInfo(self): info = self.pkcs11.getTokenInfo(self.slot) self.assertIn(info.manufacturerID, self.manufacturerIDs) text = str(info) self.assertIsNotNone(text) def test_getSessionInfo(self): self.session = self.pkcs11.openSession(self.slot, PyKCS11.CKF_SERIAL_SESSION) info = self.session.getSessionInfo() text = str(info) self.assertIsNotNone(text) self.session.closeSession() def test_getMechanismList(self): mechanisms = self.pkcs11.getMechanismList(self.slot) text = str(mechanisms) self.assertIsNotNone(text) # info for the first mechanism info = self.pkcs11.getMechanismInfo(self.slot, mechanisms[0]) text = str(info) self.assertIsNotNone(text) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1724417671.0 pykcs11-1.5.17/test/test_init.py0000644000076500000240000000477614662103207016243 0ustar00rousseaustaff# -*- coding: utf-8 -*- import unittest from PyKCS11 import PyKCS11 class TestUtil(unittest.TestCase): def setUp(self): self.pkcs11 = PyKCS11.PyKCS11Lib() self.pkcs11.load() self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0] self.session = self.pkcs11.openSession( self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION ) def tearDown(self): self.pkcs11.closeAllSessions(self.slot) del self.pkcs11 def test_initPin(self): # use admin pin self.session.login("123456", user_type=PyKCS11.CKU_SO) # change PIN self.session.initPin("4321") self.session.logout() # check new PIN self.session.login("4321") self.session.logout() # reset to old PIN self.session.login("123456", user_type=PyKCS11.CKU_SO) self.session.initPin("1234") self.session.logout() # check old PIN self.session.login("1234") self.session.logout() def test_setPin(self): self.session.login("1234") # change PIN self.session.setPin("1234", "4321") self.session.logout() # test new PIN self.session.login("4321") # revert to old PIN self.session.setPin("4321", "1234") self.session.logout() def test_initToken(self): self.pkcs11.closeAllSessions(self.slot) # use admin PIN self.pkcs11.initToken(self.slot, "123456", "my label") self.session = self.pkcs11.openSession( self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION ) self.session.login("123456", user_type=PyKCS11.CKU_SO) # set user PIN self.session.initPin("1234") self.session.logout() def test_initToken_utf8(self): self.pkcs11.closeAllSessions(self.slot) # Create a label using UTF-8 label = "abcéàç" # padding with spaces up to 32 _bytes_ (not characters) label += " " * (32 - len(label.encode("utf-8"))) # use admin PIN self.pkcs11.initToken(self.slot, "123456", label) self.session = self.pkcs11.openSession( self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION ) self.session.login("123456", user_type=PyKCS11.CKU_SO) # set user PIN self.session.initPin("1234") token_info = self.pkcs11.getTokenInfo(self.slot) self.assertEqual(token_info.label, label) self.session.logout() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1724417671.0 pykcs11-1.5.17/test/test_load.py0000644000076500000240000001213314662103207016201 0ustar00rousseaustaff# -*- coding: utf-8 -*- import unittest from PyKCS11 import PyKCS11 import platform import shutil import gc import os from pathlib import Path from tempfile import TemporaryDirectory class TestUtil(unittest.TestCase): def setUp(self): self.pkcs11 = PyKCS11.PyKCS11Lib() self.tmpdir = TemporaryDirectory() self.lib1_name = os.environ["PYKCS11LIB"] # create a tmp copy of the main lib # to use as a different library in tests self.lib2_name = str(Path(self.tmpdir.name) / Path(self.lib1_name).name) shutil.copy(self.lib1_name, self.tmpdir.name) def tearDown(self): del self.pkcs11 if platform.system() != 'Windows': self.tmpdir.cleanup() del self.tmpdir del self.lib1_name del self.lib2_name def openSession(self, lib): slot = lib.getSlotList(tokenPresent=True)[0] return lib.openSession(slot, PyKCS11.CKF_SERIAL_SESSION) def test_load(self): # create two instances with default library lib1 = PyKCS11.PyKCS11Lib().load() lib2 = PyKCS11.PyKCS11Lib().load() # expect two instances with the same library loaded self.assertTrue(hasattr(lib1, "pkcs11dll_filename")) self.assertTrue(hasattr(lib2, "pkcs11dll_filename")) self.assertEqual(len(lib1._loaded_libs), 1) self.assertEqual(len(lib2._loaded_libs), 1) self.openSession(lib1) # unload the first library del lib1 gc.collect() # one instance remaining, the library is still in use self.openSession(lib2) self.assertEqual(len(lib2._loaded_libs), 1) def test_multiple_load(self): # load two different libraries lib1 = PyKCS11.PyKCS11Lib().load(self.lib1_name) lib2 = PyKCS11.PyKCS11Lib().load(self.lib2_name) # _loaded_libs is shared across all instances # check the value in self.pkcs11 self.assertEqual(len(self.pkcs11._loaded_libs), 2) lib1 = PyKCS11.PyKCS11Lib() # unload lib1 self.assertEqual(len(self.pkcs11._loaded_libs), 1) lib2 = PyKCS11.PyKCS11Lib() # unload lib2 self.assertEqual(len(self.pkcs11._loaded_libs), 0) def test_invalid_load(self): # Library not found lib = "nolib" with self.assertRaises(PyKCS11.PyKCS11Error) as cm: self.pkcs11.load(lib) the_exception = cm.exception self.assertEqual(the_exception.value, -1) self.assertEqual(the_exception.text, lib) self.assertEqual(str(the_exception), "Load (%s)" % lib) self.assertEqual(len(self.pkcs11._loaded_libs), 0) # C_GetFunctionList() not found if platform.system() == 'Linux': # GNU/Linux lib = "libc.so.6" elif platform.system() == 'Darwin': # macOS lib = "/usr/lib/libSystem.B.dylib" else: # Windows lib = "WinSCard.dll" with self.assertRaises(PyKCS11.PyKCS11Error) as cm: self.pkcs11.load(lib) the_exception = cm.exception self.assertEqual(the_exception.value, -4) self.assertEqual(the_exception.text, lib) self.assertEqual(str(the_exception), "C_GetFunctionList() not found (%s)" % lib) self.assertEqual(len(self.pkcs11._loaded_libs), 0) # try to load the improper lib another time with self.assertRaises(PyKCS11.PyKCS11Error) as cm: self.pkcs11.load(lib) the_exception = cm.exception self.assertEqual(the_exception.value, -4) self.assertEqual(the_exception.text, lib) self.assertEqual(str(the_exception), "C_GetFunctionList() not found (%s)" % lib) self.assertEqual(len(self.pkcs11._loaded_libs), 0) # finally, load a valid library self.pkcs11.load() self.assertEqual(len(self.pkcs11._loaded_libs), 1) def test_specific_load(self): # load two different libraries sequentially self.pkcs11.load(self.lib1_name) self.pkcs11.load(self.lib2_name) # the second load should've unloaded the first library self.assertEqual(len(self.pkcs11._loaded_libs), 1) self.assertEqual(self.pkcs11.pkcs11dll_filename, self.lib2_name) # reload the first library self.pkcs11 = PyKCS11.PyKCS11Lib() self.pkcs11.load(self.lib1_name) # try to open a session self.assertIsNotNone(self.openSession(self.pkcs11)) def test_unload(self): self.pkcs11.load().unload() # no pkcs11dll_filename should remain after unload self.assertFalse(hasattr(self.pkcs11, "pkcs11dll_filename")) self.pkcs11.load() self.openSession(self.pkcs11) # one library has been loaded self.assertEqual(len(self.pkcs11._loaded_libs), 1) self.assertTrue(hasattr(self.pkcs11, "pkcs11dll_filename")) self.pkcs11.unload() gc.collect() # manually unloaded the library using gc.collect() self.assertEqual(len(self.pkcs11._loaded_libs), 0) self.assertFalse(hasattr(self.pkcs11, "pkcs11dll_filename")) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1716554236.0 pykcs11-1.5.17/test/test_objects.py0000644000076500000240000002060114624104774016722 0ustar00rousseaustaffimport unittest from PyKCS11 import PyKCS11 # those shortcuts make the testing code more readable CK_FALSE = PyKCS11.CK_FALSE CK_TRUE = PyKCS11.CK_TRUE class TestUtil(unittest.TestCase): def setUp(self): self.pkcs11 = PyKCS11.PyKCS11Lib() self.pkcs11.load() # get SoftHSM major version self.SoftHSMversion = self.pkcs11.getInfo().libraryVersion[0] self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0] self.session = self.pkcs11.openSession( self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION ) self.session.login("1234") def tearDown(self): self.session.logout() self.pkcs11.closeAllSessions(self.slot) del self.pkcs11 def test_objects(self): if self.SoftHSMversion < 2: self.skipTest("generateKey() only supported by SoftHSM >= 2") AESKeyTemplate = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE), (PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_SIGN, PyKCS11.CK_FALSE), (PyKCS11.CKA_VERIFY, PyKCS11.CK_FALSE), (PyKCS11.CKA_VALUE_LEN, 32), (PyKCS11.CKA_LABEL, "TestAESKey"), (PyKCS11.CKA_ID, (0x01,)), ] # generate AES key AESKey = self.session.generateKey(AESKeyTemplate) self.assertIsNotNone(AESKey) # find the first secret key symKey = self.session.findObjects( [(PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY)] )[0] # test object handle text = str(symKey) self.assertIsNotNone(text) # test createObject() template = [(PyKCS11.CKA_CLASS, PyKCS11.CKO_DATA), (PyKCS11.CKA_LABEL, "data")] handle = self.session.createObject(template) self.assertIsNotNone(handle) self.session.destroyObject(handle) # test getAttributeValue # attributes as define by AESKeyTemplate all_attributes = [ PyKCS11.CKA_CLASS, PyKCS11.CKA_KEY_TYPE, PyKCS11.CKA_TOKEN, PyKCS11.CKA_LABEL, PyKCS11.CKA_ID, ] values = self.session.getAttributeValue(AESKey, all_attributes) self.assertEqual( values, [ PyKCS11.CKO_SECRET_KEY, PyKCS11.CKK_AES, PyKCS11.CK_TRUE, "TestAESKey", (0x01,), ], ) # clean up self.session.destroyObject(AESKey) template = [(PyKCS11.CKA_HW_FEATURE_TYPE, PyKCS11.CKH_USER_INTERFACE)] o = self.session.findObjects(template) def test_BoolAttributes(self): # dictionary of attributes expected to be bool and their expected values boolAttributes = { PyKCS11.CKA_TOKEN : PyKCS11.CK_FALSE, PyKCS11.CKA_PRIVATE : PyKCS11.CK_FALSE, # The attributes below are defaulted to CK_TRUE # ( according to the PKCS#11 standard ) PyKCS11.CKA_MODIFIABLE : PyKCS11.CK_TRUE, PyKCS11.CKA_COPYABLE : PyKCS11.CK_TRUE, PyKCS11.CKA_DESTROYABLE : PyKCS11.CK_TRUE, } CkoDataTemplate = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_DATA), (PyKCS11.CKA_TOKEN, PyKCS11.CK_FALSE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE), (PyKCS11.CKA_LABEL, "TestData"), ] # create a CKO_DATA object ckoData = self.session.createObject(CkoDataTemplate) self.assertIsNotNone(ckoData) attrValues = self.session.getAttributeValue( ckoData, list(boolAttributes.keys()) ) # check that attributes are of bool type # and have expected values for i, attr in enumerate(boolAttributes): self.assertIsInstance(attrValues[i], bool) self.assertEqual(attrValues[i], boolAttributes[attr]) # clean up self.session.destroyObject(ckoData) class TestGetSetAttributeValues(unittest.TestCase): def setUp(self) -> None: self.pkcs11 = PyKCS11.PyKCS11Lib() self.pkcs11.load() # get SoftHSM major version self.SoftHSMversion = self.pkcs11.getInfo().libraryVersion[0] if self.SoftHSMversion < 2: self.skipTest("generateKey() only supported by SoftHSM >= 2") self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0] self.session = self.pkcs11.openSession( self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION ) self.session.login("1234") AESKeyTemplate = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES), (PyKCS11.CKA_TOKEN, CK_TRUE), (PyKCS11.CKA_PRIVATE, CK_FALSE), (PyKCS11.CKA_ENCRYPT, CK_TRUE), (PyKCS11.CKA_DECRYPT, CK_TRUE), (PyKCS11.CKA_SIGN, CK_FALSE), (PyKCS11.CKA_VERIFY, CK_FALSE), (PyKCS11.CKA_VALUE_LEN, 32), (PyKCS11.CKA_LABEL, "TestAESKey"), (PyKCS11.CKA_ID, (0x01,)), ] # generate AES key self.AESKey = self.session.generateKey(AESKeyTemplate) self.assertIsNotNone(self.AESKey) def tearDown(self): self.session.destroyObject(self.AESKey) self.session.logout() self.pkcs11.closeAllSessions(self.slot) del self.pkcs11 def test_getAttributeValue(self): # attributes as defined by AESKeyTemplate in setUp all_attributes = [ PyKCS11.CKA_CLASS, PyKCS11.CKA_KEY_TYPE, PyKCS11.CKA_TOKEN, PyKCS11.CKA_LABEL, PyKCS11.CKA_ID, ] values = self.session.getAttributeValue(self.AESKey, all_attributes) self.assertEqual( values, [ PyKCS11.CKO_SECRET_KEY, PyKCS11.CKK_AES, CK_TRUE, "TestAESKey", (0x01,), ], ) def test_setAttributeValue_with_single_binary_attribute(self): # test setAttributeValue with a binary attribute _ATTR = PyKCS11.CKA_SIGN # which attribute to test with. use a binary attribute old_state = self.session.getAttributeValue(self.AESKey, [_ATTR])[0] new_state = CK_TRUE if old_state == CK_FALSE else CK_FALSE # switch the state rv = self.session.setAttributeValue(self.AESKey, [(_ATTR, new_state)]) assert rv is None # test to see if object is really modified test_state = self.session.getAttributeValue(self.AESKey, [_ATTR])[0] assert test_state == new_state assert test_state != old_state def test_setAttributeValue_with_a_list_of_attributes(self): # which binary attributes to flip? attributes_to_switch = [ PyKCS11.CKA_SIGN, PyKCS11.CKA_ENCRYPT, PyKCS11.CKA_DECRYPT, PyKCS11.CKA_VERIFY, PyKCS11.CKA_WRAP, PyKCS11.CKA_UNWRAP ] old_attributes = self.session.getAttributeValue(self.AESKey, attributes_to_switch) flipped_attributes = [] for i, attr in enumerate(attributes_to_switch): new_value = CK_TRUE if old_attributes[i] == CK_FALSE else CK_FALSE flipped_attributes.append((attributes_to_switch[i], new_value)) rv = self.session.setAttributeValue(self.AESKey, flipped_attributes) assert rv is None new_attributes = self.session.getAttributeValue(self.AESKey, attributes_to_switch) for new, old in zip(new_attributes, old_attributes): assert new != old assert (new == CK_TRUE and old == CK_FALSE) or (new == CK_FALSE and old == CK_TRUE) def test_setAttributeValue_with_label_attribute(self): # test setAttributeValue with the text field `CKA_Label` by appending some text old_label = self.session.getAttributeValue(self.AESKey, [PyKCS11.CKA_LABEL])[0] new_label = old_label + "-mod" self.session.setAttributeValue(self.AESKey, [(PyKCS11.CKA_LABEL, new_label)]) test_label = self.session.getAttributeValue(self.AESKey, [PyKCS11.CKA_LABEL])[0] assert new_label != old_label assert test_label == new_label assert test_label != old_label ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1570392551.0 pykcs11-1.5.17/test/test_pin.py0000644000076500000240000000345113546444747016074 0ustar00rousseaustaffimport unittest from PyKCS11 import PyKCS11 # use OpenSC PKCS#11 Spy to check what PIN value is sent to the PKCS#11 # library class TestUtil(unittest.TestCase): def setUp(self): self.pkcs11 = PyKCS11.PyKCS11Lib() self.pkcs11.load() self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0] self.session = self.pkcs11.openSession( self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION ) def tearDown(self): self.pkcs11.closeAllSessions(self.slot) del self.pkcs11 def test_login(self): self.session.login("1234") self.session.logout() def test_wrong(self): with self.assertRaises(PyKCS11.PyKCS11Error) as cm: self.session.login("wrong PIN") the_exception = cm.exception self.assertEqual(the_exception.value, PyKCS11.CKR_PIN_INCORRECT) self.assertEqual(str(the_exception), "CKR_PIN_INCORRECT (0x000000A0)") def test_ckbytelist(self): pin = PyKCS11.ckbytelist("1234") self.session.login(pin) self.session.logout() def test_binary(self): with self.assertRaises(PyKCS11.PyKCS11Error) as cm: pin = PyKCS11.ckbytelist([1, 2, 3, 4]) self.session.login(pin) the_exception = cm.exception self.assertEqual(the_exception.value, PyKCS11.CKR_PIN_INCORRECT) self.assertEqual(str(the_exception), "CKR_PIN_INCORRECT (0x000000A0)") def test_null(self): # SoftHSM2 does not support pinpad (pin = NULL) with self.assertRaises(PyKCS11.PyKCS11Error) as cm: self.session.login(None) the_exception = cm.exception self.assertEqual(the_exception.value, PyKCS11.CKR_ARGUMENTS_BAD) self.assertEqual(str(the_exception), "CKR_ARGUMENTS_BAD (0x00000007)") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1555508732.0 pykcs11-1.5.17/test/test_random.py0000644000076500000240000000132413455626774016564 0ustar00rousseaustaffimport unittest from PyKCS11 import PyKCS11 class TestUtil(unittest.TestCase): def setUp(self): self.pkcs11 = PyKCS11.PyKCS11Lib() self.pkcs11.load() self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0] self.session = self.pkcs11.openSession(self.slot, PyKCS11.CKF_SERIAL_SESSION) def tearDown(self): self.pkcs11.closeAllSessions(self.slot) del self.pkcs11 def test_seedRandom(self): seed = [1, 2, 3, 4] self.session.seedRandom(seed) def test_generateRandom(self): rnd = self.session.generateRandom() self.assertEqual(len(rnd), 16) rnd = self.session.generateRandom(32) self.assertEqual(len(rnd), 32) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1723045668.0 pykcs11-1.5.17/test/test_symetric.py0000644000076500000240000001044714654713444017142 0ustar00rousseaustafffrom __future__ import print_function import unittest from PyKCS11 import PyKCS11 class TestUtil(unittest.TestCase): def setUp(self): self.pkcs11 = PyKCS11.PyKCS11Lib() self.pkcs11.load() # get SoftHSM major version self.SoftHSMversion = self.pkcs11.getInfo().libraryVersion self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0] self.session = self.pkcs11.openSession( self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION ) self.session.login("1234") def tearDown(self): self.session.logout() self.pkcs11.closeAllSessions(self.slot) del self.pkcs11 def test_symetric(self): # AES CBC with IV mechanism = PyKCS11.Mechanism(PyKCS11.CKM_AES_CBC, "1234567812345678") self.assertIsNotNone(mechanism) if self.SoftHSMversion < (2,0): self.skipTest("generateKey() only supported by SoftHSM >= 2.0") keyID = (0x01,) AESKeyTemplate = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE), (PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_SIGN, PyKCS11.CK_FALSE), (PyKCS11.CKA_VERIFY, PyKCS11.CK_FALSE), (PyKCS11.CKA_VALUE_LEN, 32), (PyKCS11.CKA_LABEL, "TestAESKey"), (PyKCS11.CKA_ID, keyID), ] AESKey = self.session.generateKey(AESKeyTemplate) self.assertIsNotNone(AESKey) # buffer of 32 bytes 0x00 DataIn = [0] * 32 # print("DataIn:", DataIn) # AES CBC with IV mechanism = PyKCS11.Mechanism(PyKCS11.CKM_AES_CBC, "1234567812345678") # find the first secret key symKey = self.session.findObjects( [(PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY), (PyKCS11.CKA_ID, keyID)] )[0] DataOut = self.session.encrypt(symKey, DataIn, mechanism) # print("DataOut", DataOut) DataCheck = self.session.decrypt(symKey, DataOut, mechanism) # print("DataCheck:", DataCheck) self.assertSequenceEqual(DataIn, DataCheck) # AES ECB with previous IV as Data mechanism = PyKCS11.Mechanism(PyKCS11.CKM_AES_ECB) # same as '1234567812345678' (the IV) but as a list DataECBIn = [49, 50, 51, 52, 53, 54, 55, 56, 49, 50, 51, 52, 53, 54, 55, 56] # print("DataECBIn:", DataECBIn) DataECBOut = self.session.encrypt(symKey, DataECBIn, mechanism) # print("DataECBOut:", DataECBOut) DataECBCheck = self.session.decrypt(symKey, DataECBOut, mechanism) # print("DataECBCheck:", DataECBCheck) self.assertSequenceEqual(DataECBIn, DataECBCheck) # check the AES CBC computation is the same as the AES ECB # 1st block self.assertSequenceEqual(DataOut[:16], DataECBOut) # since the input is full of 0 we just pass the previous output DataECBOut2 = self.session.encrypt(symKey, DataECBOut, mechanism) # print("DataECBOut2", DataECBOut2) # 2nd block self.assertSequenceEqual(DataOut[16:], DataECBOut2) # AES CTR with IV mechanism = PyKCS11.AES_CTR_Mechanism(128, "1234567812345678") DataOut = self.session.encrypt(symKey, DataIn, mechanism) # print("DataOut", DataOut) DataCheck = self.session.decrypt(symKey, DataOut, mechanism) # print("DataCheck:", DataCheck) self.assertSequenceEqual(DataIn, DataCheck) # # test CK_GCM_PARAMS # if self.SoftHSMversion <= (2,2): self.skipTest("CKM_AES_GCM only supported by SoftHSM > 2.2") AES_GCM_IV_SIZE = 12 AES_GCM_TAG_SIZE = 16 iv = [42] * AES_GCM_IV_SIZE aad = "plaintext aad" tagBits = AES_GCM_TAG_SIZE * 8 mechanism = PyKCS11.AES_GCM_Mechanism(iv, aad, tagBits) DataOut = self.session.encrypt(symKey, DataIn, mechanism) # print("DataOut", DataOut) DataCheck = self.session.decrypt(symKey, DataOut, mechanism) # print("DataCheck:", DataCheck) self.assertSequenceEqual(DataIn, DataCheck) self.session.destroyObject(AESKey) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1588606483.0 pykcs11-1.5.17/test/test_wrap.py0000644000076500000240000002676713654033023016253 0ustar00rousseaustaffimport unittest from PyKCS11 import PyKCS11 class TestUtil(unittest.TestCase): def setUp(self): self.pkcs11 = PyKCS11.PyKCS11Lib() self.pkcs11.load() # get SoftHSM major version self.SoftHSMversion = self.pkcs11.getInfo().libraryVersion[0] self.slot = self.pkcs11.getSlotList(tokenPresent=True)[0] self.session = self.pkcs11.openSession( self.slot, PyKCS11.CKF_SERIAL_SESSION | PyKCS11.CKF_RW_SESSION ) self.session.login("1234") def tearDown(self): self.session.logout() self.pkcs11.closeAllSessions(self.slot) del self.pkcs11 def test_wrapKey(self): keyID = (0x01,) AESKeyTemplate = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE), (PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_SIGN, PyKCS11.CK_FALSE), (PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_TRUE), (PyKCS11.CKA_VERIFY, PyKCS11.CK_FALSE), (PyKCS11.CKA_VALUE_LEN, 32), (PyKCS11.CKA_LABEL, "TestAESKey"), (PyKCS11.CKA_ID, keyID), ] if self.SoftHSMversion < 2: self.skipTest("generateKey() only supported by SoftHSM >= 2") self.wrapKey = self.session.generateKey(AESKeyTemplate) self.assertIsNotNone(self.wrapKey) keyID = (0x02,) # make the key extractable AESKeyTemplate.append((PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_TRUE)) self.AESKey = self.session.generateKey(AESKeyTemplate) self.assertIsNotNone(self.AESKey) # buffer of 32 bytes 0x42 DataIn = [42] * 32 mechanism = PyKCS11.Mechanism(PyKCS11.CKM_AES_ECB) DataOut = self.session.encrypt(self.AESKey, DataIn, mechanism) # print("DataOut", DataOut) DataCheck = self.session.decrypt(self.AESKey, DataOut, mechanism) # print("DataCheck:", DataCheck) # check we can encrypt/decrypt with the AES key self.assertSequenceEqual(DataIn, DataCheck) # wrap using CKM_AES_KEY_WRAP mechanismWrap = PyKCS11.Mechanism(PyKCS11.CKM_AES_KEY_WRAP) wrapped = self.session.wrapKey(self.wrapKey, self.AESKey, mechanismWrap) self.assertIsNotNone(wrapped) # destroy the original key self.session.destroyObject(self.AESKey) # unwrap template = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE), (PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_SIGN, PyKCS11.CK_FALSE), (PyKCS11.CKA_VERIFY, PyKCS11.CK_FALSE), ] unwrapped = self.session.unwrapKey( self.wrapKey, wrapped, template, mechanismWrap ) self.assertIsNotNone(unwrapped) DataCheck = self.session.decrypt(unwrapped, DataOut, mechanism) # print("DataCheck:", DataCheck) # check we can decrypt with the unwrapped AES key self.assertSequenceEqual(DataIn, DataCheck) # cleanup self.session.destroyObject(unwrapped) self.session.destroyObject(self.wrapKey) def test_wrapKey_OAEP(self): if self.SoftHSMversion < 2: self.skipTest("generateKey() only supported by SoftHSM >= 2") keyID = (0x22,) pubTemplate = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_PUBLIC_KEY), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE), (PyKCS11.CKA_MODULUS_BITS, 0x0400), (PyKCS11.CKA_PUBLIC_EXPONENT, (0x01, 0x00, 0x01)), (PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_VERIFY, PyKCS11.CK_TRUE), (PyKCS11.CKA_VERIFY_RECOVER, PyKCS11.CK_TRUE), (PyKCS11.CKA_WRAP, PyKCS11.CK_TRUE), (PyKCS11.CKA_LABEL, "My Public Key"), (PyKCS11.CKA_ID, keyID), ] privTemplate = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_PRIVATE_KEY), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_TRUE), (PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_SIGN, PyKCS11.CK_TRUE), (PyKCS11.CKA_SIGN_RECOVER, PyKCS11.CK_TRUE), (PyKCS11.CKA_UNWRAP, PyKCS11.CK_TRUE), (PyKCS11.CKA_ID, keyID), ] self.pubKey, self.privKey = self.session.generateKeyPair( pubTemplate, privTemplate ) self.assertIsNotNone(self.pubKey) self.assertIsNotNone(self.privKey) keyID = (0x02,) AESKeyTemplate = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE), (PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_SIGN, PyKCS11.CK_FALSE), (PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_TRUE), (PyKCS11.CKA_VERIFY, PyKCS11.CK_FALSE), (PyKCS11.CKA_VALUE_LEN, 32), (PyKCS11.CKA_LABEL, "TestAESKey"), (PyKCS11.CKA_ID, keyID), ] # make the key extractable AESKeyTemplate.append((PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_TRUE)) self.AESKey = self.session.generateKey(AESKeyTemplate) self.assertIsNotNone(self.AESKey) # buffer of 32 bytes 0x42 DataIn = [42] * 32 mechanism = PyKCS11.Mechanism(PyKCS11.CKM_AES_ECB) DataOut = self.session.encrypt(self.AESKey, DataIn, mechanism) # print("DataOut", DataOut) DataCheck = self.session.decrypt(self.AESKey, DataOut, mechanism) # print("DataCheck:", DataCheck) # check we can encrypt/decrypt with the AES key self.assertSequenceEqual(DataIn, DataCheck) # wrap using CKM_RSA_PKCS_OAEP + CKG_MGF1_SHA1 mechanismWrap = PyKCS11.RSAOAEPMechanism( PyKCS11.CKM_SHA_1, PyKCS11.CKG_MGF1_SHA1 ) wrapped = self.session.wrapKey(self.pubKey, self.AESKey, mechanismWrap) self.assertIsNotNone(wrapped) # destroy the original key self.session.destroyObject(self.AESKey) # unwrap template = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE), (PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_SIGN, PyKCS11.CK_FALSE), (PyKCS11.CKA_VERIFY, PyKCS11.CK_FALSE), ] unwrapped = self.session.unwrapKey( self.privKey, wrapped, template, mechanismWrap ) self.assertIsNotNone(unwrapped) DataCheck = self.session.decrypt(unwrapped, DataOut, mechanism) # print("DataCheck:", DataCheck) # check we can decrypt with the unwrapped AES key self.assertSequenceEqual(DataIn, DataCheck) # cleanup self.session.destroyObject(unwrapped) self.session.destroyObject(self.pubKey) self.session.destroyObject(self.privKey) def test_wrapKey_UNWRAP_TEMPLATE(self): keyID = (0x01,) pubTemplate = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_PUBLIC_KEY), (PyKCS11.CKA_LABEL, "RSA Public Key"), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_RSA), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_TRUE), (PyKCS11.CKA_VERIFY, PyKCS11.CK_TRUE), (PyKCS11.CKA_MODULUS_BITS, 2048), (PyKCS11.CKA_PUBLIC_EXPONENT, (0x01, 0x00, 0x01)), (PyKCS11.CKA_ID, keyID), (PyKCS11.CKA_WRAP, PyKCS11.CK_TRUE), ] unwrap_template = [ (PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_FALSE), ] privTemplate = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_PRIVATE_KEY), (PyKCS11.CKA_LABEL, "RSA Private Key"), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_RSA), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_TRUE), (PyKCS11.CKA_SIGN, PyKCS11.CK_TRUE), (PyKCS11.CKA_ID, keyID), (PyKCS11.CKA_UNWRAP, PyKCS11.CK_TRUE), (PyKCS11.CKA_UNWRAP_TEMPLATE, unwrap_template), ] if self.SoftHSMversion < 2: self.skipTest("generateKey() only supported by SoftHSM >= 2") self.pubKey, self.privKey = self.session.generateKeyPair(pubTemplate, privTemplate) self.assertIsNotNone(self.pubKey) self.assertIsNotNone(self.privKey) keyID = (0x02,) AESKeyTemplate = [ (PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES), (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_PRIVATE, PyKCS11.CK_FALSE), (PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_DECRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_SIGN, PyKCS11.CK_FALSE), (PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_TRUE), (PyKCS11.CKA_VERIFY, PyKCS11.CK_FALSE), (PyKCS11.CKA_VALUE_LEN, 32), (PyKCS11.CKA_LABEL, "TestAESKey"), (PyKCS11.CKA_ID, keyID), ] # make the key extractable AESKeyTemplate.append((PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_TRUE)) self.AESKey = self.session.generateKey(AESKeyTemplate) self.assertIsNotNone(self.AESKey) # buffer of 32 bytes 0x42 DataIn = [42] * 32 mechanism = PyKCS11.Mechanism(PyKCS11.CKM_AES_ECB) DataOut = self.session.encrypt(self.AESKey, DataIn, mechanism) # print("DataOut", DataOut) DataCheck = self.session.decrypt(self.AESKey, DataOut, mechanism) # print("DataCheck:", DataCheck) # check we can encrypt/decrypt with the AES key self.assertSequenceEqual(DataIn, DataCheck) # wrap mechanismWrap = PyKCS11.RSAOAEPMechanism( PyKCS11.CKM_SHA_1, PyKCS11.CKG_MGF1_SHA1 ) wrapped = self.session.wrapKey(self.pubKey, self.AESKey, mechanismWrap) self.assertIsNotNone(wrapped) # destroy the original key self.session.destroyObject(self.AESKey) # unwrap template = [ (PyKCS11.CKA_TOKEN, PyKCS11.CK_TRUE), (PyKCS11.CKA_CLASS, PyKCS11.CKO_SECRET_KEY), (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_AES), (PyKCS11.CKA_EXTRACTABLE, PyKCS11.CK_FALSE), ] unwrapped = self.session.unwrapKey( self.privKey, wrapped, template, mechanismWrap ) self.assertIsNotNone(unwrapped) DataCheck = self.session.decrypt(unwrapped, DataOut, mechanism) # print("DataCheck:", DataCheck) # check we can decrypt with the unwrapped AES key self.assertSequenceEqual(DataIn, DataCheck) attributes = self.session.getAttributeValue(unwrapped, [PyKCS11.CKA_EXTRACTABLE]) self.assertSequenceEqual(attributes, [False]) # cleanup self.session.destroyObject(unwrapped) self.session.destroyObject(self.pubKey) self.session.destroyObject(self.privKey) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1704624376.0 pykcs11-1.5.17/tox.ini0000644000076500000240000000120014546500370014201 0ustar00rousseaustaff# Tox (https://tox.readthedocs.io/) is a tool for running tests # in multiple virtualenvs. This configuration file will run the # test suite on all supported python versions. To use it, "pip install tox" # and then run "tox" from this directory. [tox] envlist = py311 py312 [testenv] description = run test suite allowlist_externals = ln deps = -r{toxinidir}/dev-requirements.txt changedir = {envdir} setenv = file|tox.env commands = ln -sf {toxinidir}/test {envpython} -m unittest discover coverage erase coverage run -m unittest discover coverage report coverage html