PyKCS11-1.5.7/0000755000076500000240000000000013576454261013625 5ustar rousseaustaff00000000000000PyKCS11-1.5.7/COPYING0000644000076500000240000004310313421700724014644 0ustar rousseaustaff00000000000000 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. PyKCS11-1.5.7/Changes.txt0000644000076500000240000001611413576454106015737 0ustar rousseaustaff00000000000000History ======= 1.5.7 - Devember 2019, Ludovic Rousseau - add missing files in the .tar.gz 1.5.6 - Devember 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 diffrent 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 PyKCS11-1.5.7/MANIFEST.in0000644000076500000240000000035613576453573015374 0ustar rousseaustaff00000000000000include src/* include src/opensc/* recursive-include samples *.py include Changes.txt include Makefile* include run_test.py include tox.ini include pykcs11.rc include resource.h include dev-requirements.txt include docs/* include COPYING PyKCS11-1.5.7/Makefile0000644000076500000240000000230713455650567015272 0ustar rousseaustaff00000000000000# give some default values DESTDIR ?= / ifeq (, $(PYTHON)) PYTHON=python endif PREFIX ?= $(shell $(PYTHON) -c 'import sys; print(sys.prefix)') COVERAGE ?= coverage build: build-stamp build-stamp: $(PYTHON) setup.py build touch build-stamp install: build $(PYTHON) setup.py install --prefix=$(PREFIX) --root=$(DESTDIR) clean distclean: $(PYTHON) setup.py clean rm -f src/pykcs11_wrap.cpp 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 rebuild: clean build src/pykcs11.i: src/opensc/pkcs11.h src/pkcs11lib.h src/pykcs11string.h src/ck_attribute_smart.h touch $@ dist: clean $(PYTHON) setup.py sdist bdist_wheel pypi: clean rm -rf dist $(PYTHON) setup.py sdist bdist_wheel $(PYTHON) -m twine upload dist/* prepare4test: build cd PyKCS11 ; ln -sf ../build/lib.*/PyKCS11/_LowLevel*.so tests: prepare4test $(PYTHON) run_test.py coverage: prepare4test $(COVERAGE) run run_test.py $(COVERAGE) report $(COVERAGE) html doc: cd docs ; ./generate.sh doc-upload: doc rm -r api mv docs/_build/html api scp -r api ludov@web.sourceforge.net:/home/project-web/pkcs11wrap/htdocs .PHONY: build install clean rebuild dist doc PyKCS11-1.5.7/Makefile.win320000644000076500000240000000077113421700724016216 0ustar rousseaustaff00000000000000 build: src/pykcs11_wrap.cpp python setup.py build install: build python setup.py install clean: python setup.py clean DEL /F /Q src\pykcs11_wrap.cpp DEL /S /F /Q build DEL /F /Q *.pyc PyKCS11\*.pyc DEL /F /Q PyKCS11\LowLevel.py rebuild: clean build src/pykcs11_wrap.cpp: src/pykcs11.i swig.exe -c++ -Fmicrosoft -o src\pykcs11_wrap.cpp -python src\pykcs11.i move src\LowLevel.py PyKCS11\ src/pykcs11.i: src/opensc/pkcs11.h src/pkcs11lib.h src/pykcs11string.h src/ck_attribute_smart.h PyKCS11-1.5.7/PKG-INFO0000644000076500000240000000253613576454261014730 0ustar rousseaustaff00000000000000Metadata-Version: 1.2 Name: PyKCS11 Version: 1.5.7 Summary: A Full PKCS#11 wrapper for Python Home-page: https://github.com/LudovicRousseau/PyKCS11 Author: Giuseppe Amato (Midori) Author-email: paipai@tiscali.it Maintainer: Ludovic Rousseau Maintainer-email: ludovic.rousseau@free.fr License: GPL Download-URL: http://sourceforge.net/projects/pkcs11wrap/files/pykcs11/ 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. 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 PyKCS11-1.5.7/PyKCS11/0000755000076500000240000000000013576454261014720 5ustar rousseaustaff00000000000000PyKCS11-1.5.7/PyKCS11/__init__.py0000644000076500000240000014760313546444747017051 0ustar rousseaustaff00000000000000# 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 CKM = {} CKR = {} CKA = {} CKO = {} CKU = {} CKK = {} CKC = {} CKF = {} CKS = {} CKG = {} CKZ = {} # redefine PKCS#11 constants using well known prefixes for x in PyKCS11.LowLevel.__dict__.keys(): if x[:4] == 'CKM_' \ or x[:4] == 'CKR_' \ or x[:4] == 'CKA_' \ or x[:4] == 'CKO_' \ or x[:4] == 'CKU_' \ or x[:4] == 'CKK_' \ or x[:4] == 'CKC_' \ or x[:4] == 'CKF_' \ or x[:4] == 'CKS_' \ or x[:4] == 'CKG_' \ or x[:4] == 'CKZ_': a = "%s=PyKCS11.LowLevel.%s" % (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=[]): # default size of the vector size = 0 super(ckbytelist, self).__init__(size) # No value to initialize if data is None: return # b'abc' if isinstance(data, bytes): self.reserve(len(data)) for x in data: if sys.version_info[0] <= 2: # Python 2 v = ord(x) else: # Python 3 and more v = x self.append(v) # "abc" elif isinstance(data, str): tmp = bytes(data, "utf-8") self.reserve(len(tmp)) for x in tmp: self.append(x) # [141, 142, 143] elif isinstance(data, list) or isinstance(data, ckbytelist): self.reserve(len(data)) for c in range(len(data)): self.append(data[c]) else: raise PyKCS11.PyKCS11Error(-3, text=str(type(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("%s: %s" % (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("%s: %s" % (key, ", ".join(dico[key]))) elif type == "pair": lines.append("%s: " % key + "%d.%d" % dico[key]) else: lines.append("%s: %s" % (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 """ 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__: self.lib.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)") rv = self.lib.Load(pkcs11dll_filename) if rv != CKR_OK: raise PyKCS11Error(rv, 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 = 'CKR_VENDOR_DEFINED_%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 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 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 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_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_SENSITIVE, CKA_DECRYPT, CKA_DERIVE, CKA_ENCRYPT, CKA_EXTRACTABLE, CKA_HAS_RESET, CKA_LOCAL, CKA_MODIFIABLE, 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 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() PyKCS11-1.5.7/PyKCS11.egg-info/0000755000076500000240000000000013576454261016412 5ustar rousseaustaff00000000000000PyKCS11-1.5.7/PyKCS11.egg-info/PKG-INFO0000644000076500000240000000253613576454261017515 0ustar rousseaustaff00000000000000Metadata-Version: 1.2 Name: PyKCS11 Version: 1.5.7 Summary: A Full PKCS#11 wrapper for Python Home-page: https://github.com/LudovicRousseau/PyKCS11 Author: Giuseppe Amato (Midori) Author-email: paipai@tiscali.it Maintainer: Ludovic Rousseau Maintainer-email: ludovic.rousseau@free.fr License: GPL Download-URL: http://sourceforge.net/projects/pkcs11wrap/files/pykcs11/ 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. 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 PyKCS11-1.5.7/PyKCS11.egg-info/SOURCES.txt0000644000076500000240000000265713576454261020310 0ustar rousseaustaff00000000000000COPYING Changes.txt MANIFEST.in Makefile Makefile.win32 README.md dev-requirements.txt pykcs11.rc resource.h 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/LowLevel.py 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.h src/pykcs11.i src/pykcs11string.cpp src/pykcs11string.h src/stdafx.cpp src/stdafx.h src/utility.cpp src/utility.h 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_digest.py test/test_exception.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.pyPyKCS11-1.5.7/PyKCS11.egg-info/dependency_links.txt0000644000076500000240000000000113576454261022460 0ustar rousseaustaff00000000000000 PyKCS11-1.5.7/PyKCS11.egg-info/top_level.txt0000644000076500000240000000001013576454261021133 0ustar rousseaustaff00000000000000PyKCS11 PyKCS11-1.5.7/README.md0000644000076500000240000000421413421701653015072 0ustar rousseaustaff00000000000000PyKCS11 - 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 ====== [![Build Status](https://travis-ci.org/LudovicRousseau/PyKCS11.svg?branch=master)](https://travis-ci.org/LudovicRousseau/PyKCS11) [![Coverage Status](https://coveralls.io/repos/github/LudovicRousseau/PyKCS11/badge.svg?branch=master)](https://coveralls.io/github/LudovicRousseau/PyKCS11?branch=master) [![Build status](https://ci.appveyor.com/api/projects/status/32k1lg805scl0tt3?svg=true)](https://ci.appveyor.com/project/LudovicRousseau/pykcs11) API === The API documentation is available at http://pkcs11wrap.sourceforge.net/api/ Unix Howto ========== To install:: $ make build $ make install (or make install DESTDIR=/foo/bar) Windows 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: Open "Visual Studio command prompt (2010)" cd to PyKCS11 folder and run:: > nmake -f Makefile.win32 build > nmake -f Makefile.win32 install Windows binaries ---------------- You can get (untested) Windows binaries from https://ci.appveyor.com/project/LudovicRousseau/pykcs11 in "artifacts". PyKCS11-1.5.7/dev-requirements.txt0000644000076500000240000000003613455626774017672 0ustar rousseaustaff00000000000000coverage coveralls asn1crypto PyKCS11-1.5.7/docs/0000755000076500000240000000000013576454261014555 5ustar rousseaustaff00000000000000PyKCS11-1.5.7/docs/Makefile0000644000076500000240000000113413421701653016201 0ustar rousseaustaff00000000000000# 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)PyKCS11-1.5.7/docs/api.rst0000644000076500000240000000013613421701653016045 0ustar rousseaustaff00000000000000API documentation ***************** .. automodule:: PyKCS11 :members: :undoc-members: PyKCS11-1.5.7/docs/conf.py0000644000076500000240000001207613421701653016047 0ustar rousseaustaff00000000000000# -*- 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.2' # -- 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 = None # 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 = ['_static'] # 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 ------------------------------------------------- PyKCS11-1.5.7/docs/generate.sh0000755000076500000240000000037613421701653016701 0ustar rousseaustaff00000000000000#!/bin/bash # Enable a virtualenv before running the script to avoid modifying # the system Python libraries if [ ! "$VIRTUAL_ENV" ] then echo "Run it from inside a virtualenv" exit 1 fi cd $(dirname $0) (cd .. ; python setup.py install) make html PyKCS11-1.5.7/docs/index.rst0000644000076500000240000000161613421701653016407 0ustar rousseaustaff00000000000000.. 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 `_ .. toctree:: :maxdepth: 4 :caption: Contents: api samples license Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` PyKCS11-1.5.7/docs/license.rst0000644000076500000240000000132513421701653016717 0ustar rousseaustaff00000000000000License ####### 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 PyKCS11-1.5.7/docs/samples.rst0000644000076500000240000000133713421701653016744 0ustar rousseaustaff00000000000000PyKCS11 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 PyKCS11-1.5.7/pykcs11.rc0000644000076500000240000000536113421700724015436 0ustar rousseaustaff00000000000000// Microsoft Visual C++ generated resource script. // #include "resource.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // #include "WinResrc.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // English (U.S.) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) #ifdef _WIN32 LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #pragma code_page(1252) #endif //_WIN32 #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE BEGIN "resource.h\0" END 2 TEXTINCLUDE BEGIN "#include ""afxres.h""\r\n" "\0" END 3 TEXTINCLUDE BEGIN "\r\n" "\0" END #endif // APSTUDIO_INVOKED #endif // English (U.S.) resources ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // Italian (Italy) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ITA) #ifdef _WIN32 LANGUAGE LANG_ITALIAN, SUBLANG_ITALIAN #pragma code_page(1252) #endif //_WIN32 ///////////////////////////////////////////////////////////////////////////// // // Version // VS_VERSION_INFO VERSIONINFO FILEVERSION 1,2,0,0 PRODUCTVERSION 1,2,0,0 FILEFLAGSMASK 0x17L #ifdef _DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L #endif FILEOS 0x4L FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "000004b0" BEGIN VALUE "Comments", "_LowLevel module" VALUE "FileDescription", "PKCS#11 wrapper for Python (_LowLevel)" VALUE "FileVersion", "1, 1, 1, 0" VALUE "InternalName", "pykcs11" VALUE "LegalCopyright", "Copyright (C) 2004-2006 Giuseppe Amato (paipai -at- tiscali dot it)" VALUE "OriginalFilename", "pykcs11.dll" VALUE "ProductName", " pykcs11 Dynamic Link Library" VALUE "ProductVersion", "1, 1, 1, 0" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0, 1200 END END #endif // Italian (Italy) resources ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED PyKCS11-1.5.7/resource.h0000644000076500000240000000062113421700724015607 0ustar rousseaustaff00000000000000//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by pykcs11.rc // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif PyKCS11-1.5.7/run_test.py0000755000076500000240000000271413455626774016057 0ustar rousseaustaff00000000000000#!/usr/bin/env python # use: # ./run_test.py # ./run_test.py test_ckbytelist.py from __future__ import print_function import unittest import os import sys pattern = "test*.py" if len(sys.argv) > 1: pattern = sys.argv[1] 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 ] 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 "/usr/lib/softhsm/libsofthsm2.so", # Debian libsofthsm2 "/usr/lib/softhsm/libsofthsm.so", # Debian libsofthsm "/usr/lib/libsofthsm.so", # Ubuntu 12.04 libsofthsm WINDOWS_SOFTHSM, # Windows ] for lib in LIBS: if os.path.isfile(lib): print("Using lib:", lib) os.environ["PYKCS11LIB"] = lib break try: os.environ["PYKCS11LIB"] except KeyError: raise Exception("PYKCS11LIB is not defined. No SoftHSM library found?") 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) PyKCS11-1.5.7/samples/0000755000076500000240000000000013576454261015271 5ustar rousseaustaff00000000000000PyKCS11-1.5.7/samples/LowLevel/0000755000076500000240000000000013576454261017022 5ustar rousseaustaff00000000000000PyKCS11-1.5.7/samples/LowLevel/InitTokenPin.py0000755000076500000240000000763513421701653021752 0ustar rousseaustaff00000000000000#!/usr/bin/env python # 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. from __future__ import print_function 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()) PyKCS11-1.5.7/samples/LowLevel/dumpit.py0000755000076500000240000001403513421701653020671 0ustar rousseaustaff00000000000000#!/usr/bin/env python # 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 __future__ import print_function 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()) PyKCS11-1.5.7/samples/LowLevel/rand.py0000755000076500000240000000404213421701653020310 0ustar rousseaustaff00000000000000#!/usr/bin/env python # 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. from __future__ import print_function 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()) PyKCS11-1.5.7/samples/LowLevel/test.py0000755000076500000240000001101313421701653020337 0ustar rousseaustaff00000000000000#!/usr/bin/env python # 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. from __future__ import print_function 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()) PyKCS11-1.5.7/samples/LowLevel/test1.py0000755000076500000240000001130613421701653020425 0ustar rousseaustaff00000000000000#!/usr/bin/env python # 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. from __future__ import print_function 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()) PyKCS11-1.5.7/samples/destroy_by_ID.py0000755000076500000240000000242013421700724020366 0ustar rousseaustaff00000000000000#!/usr/bin/env python # 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() PyKCS11-1.5.7/samples/dumpit.py0000755000076500000240000002715713421701653017151 0ustar rousseaustaff00000000000000#!/usr/bin/env python # 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 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 hexx(intval): x = hex(intval)[2:] if x[-1:].upper() == "L": x = x[:-1] if len(x) % 2 != 0: return "0%s" % x return x def dump(src, length=16): FILTER = "".join([(len(repr(chr(x))) == 3) and chr(x) or "." for x in range(256)]) N = 0 result = "" while src: s, src = src[:length], src[length:] hexa = " ".join(["%02X" % ord(x) for x in s]) s = s.translate(FILTER) result += "%04X %-*s %s\n" % (N, length * 3, hexa, s) 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][--sign]", end=" ") print("[-s slot][--slot=slot]", end=" ") print("[-d][--decrypt]", end=" ") print("[-h][--help]", end=" ") print() try: opts, args = getopt.getopt( sys.argv[1:], "p:c:Sdhs:a", ["pin=", "lib=", "sign", "decrypt", "slot=", "help", "all"], ) except getopt.GetoptError: # print help information and exit: usage() sys.exit(2) pin_available = False decrypt = sign = 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", "--sign"): sign = True elif o in ("-d", "--decrypt"): decrypt = True 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))) if ( attrDict[PyKCS11.CKA_CLASS] == PyKCS11.CKO_PRIVATE_KEY and attrDict[PyKCS11.CKA_KEY_TYPE] == PyKCS11.CKK_RSA ): m = attrDict[PyKCS11.CKA_MODULUS] e = attrDict[PyKCS11.CKA_PUBLIC_EXPONENT] if m and e: mx = eval(b"0x" + str.encode("".join("%02X" % c for c in m))) ex = eval(b"0x" + str.encode("".join("%02X" % c for c in e))) if sign: try: toSign = b"12345678901234567890" # 20 bytes, SHA1 digest print( "* Signing with object 0x%08X following data: %s" % (o.value(), toSign) ) signature = session.sign(o, toSign) sx = eval(b"0x" + "".join("%02X" % c for c in signature)) print("Signature:") print(dump("".join(map(chr, signature)))) if m and e: print("Verifying using following public key:") print("Modulus:") print(dump("".join(map(chr, m)))) print("Exponent:") print(dump("".join(map(chr, e)))) decrypted = pow(sx, ex, mx) # RSA print("Decrypted:") d = binascii.unhexlify(hexx(decrypted)) print(dump(d)) if toSign == d[-20:]: print("*** signature VERIFIED!\n") else: print("*** signature NOT VERIFIED; decrypted value:") print(hex(decrypted), "\n") else: print( "Unable to verify signature: MODULUS/PUBLIC_EXP not found" ) except PyKCS11.PyKCS11Error as e: print("Sign failed, exception:", e) break if decrypt: if m and e: try: toEncrypt = "12345678901234567890" # note: PKCS1 BT2 padding should be random data, # but this is just a test and we use 0xFF... padded = "0002%s00%s" % ( "FF" * (128 - (len(toEncrypt)) - 3), toEncrypt, ) padded = binascii.unhexlify(padded) print( "* Decrypting with 0x%08X following data: %s" % (o.value(), toEncrypt) ) print("padded:") print(dump(padded)) encrypted = pow( eval("0x%sL" % binascii.hexlify(padded)), ex, mx ) # RSA encrypted1 = binascii.unhexlify(hexx(encrypted)) print("encrypted:") print(dump(encrypted1)) decrypted = session.decrypt(o, encrypted1) decrypted1 = "".join(chr(i) for i in decrypted) print("decrypted:") print(dump(decrypted1)) if decrypted1 == toEncrypt: print("decryption SUCCESSFULL!\n") else: print("decryption FAILED!\n") except PyKCS11.PyKCS11Error as e: print("Decrypt failed, exception:", e) break else: print("ERROR: Private key don't have MODULUS/PUBLIC_EXP") 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("".join(map(chr, 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 PyKCS11-1.5.7/samples/ec_generate.py0000755000076500000240000000444113455626774020120 0ustar rousseaustaff00000000000000#!/usr/bin/env python # 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() PyKCS11-1.5.7/samples/ec_signature.py0000755000076500000240000000360313455626774020326 0ustar rousseaustaff00000000000000#!/usr/bin/env python # 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() PyKCS11-1.5.7/samples/encrypt.py0000755000076500000240000000311313421700724017313 0ustar rousseaustaff00000000000000#!/usr/bin/env python # 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() PyKCS11-1.5.7/samples/events.py0000755000076500000240000000535213466734664017165 0ustar rousseaustaff00000000000000#!/usr/bin/env python # 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) PyKCS11-1.5.7/samples/generate.py0000755000076500000240000000344213421701653017430 0ustar rousseaustaff00000000000000#!/usr/bin/env python # 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() PyKCS11-1.5.7/samples/genkeypair_import_cert.py0000755000076500000240000001144013421701653022400 0ustar rousseaustaff00000000000000#!/usr/bin/env python # 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 = "1111" 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_SENSITIVE, PyKCS11.CK_FALSE), (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 = "replace this with the raw certificate itself" # 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_TRUSTED, PyKCS11.CK_TRUE), (PyKCS11.CKA_SENSITIVE, PyKCS11.CK_FALSE), (PyKCS11.CKA_ENCRYPT, PyKCS11.CK_TRUE), (PyKCS11.CKA_VERIFY, PyKCS11.CK_TRUE), (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. PyKCS11-1.5.7/samples/getinfo.py0000755000076500000240000001214013421701653017264 0ustar rousseaustaff00000000000000#!/usr/bin/env python # 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) PyKCS11-1.5.7/samples/modulus.py0000755000076500000240000000267313421700724017331 0ustar rousseaustaff00000000000000#!/usr/bin/env python # 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() PyKCS11-1.5.7/samples/rsa_encrypt.py0000755000076500000240000000374713421701653020177 0ustar rousseaustaff00000000000000#!/usr/bin/env python # 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!") PyKCS11-1.5.7/samples/signature.py0000755000076500000240000000335113421701653017636 0ustar rousseaustaff00000000000000#!/usr/bin/env python # 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 __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 toSign = "48656c6c6f20776f726c640d0a" mechanism = Mechanism(CKM_SHA1_RSA_PKCS, None) # find first private key and compute signature privKey = session.findObjects([(CKA_CLASS, CKO_PRIVATE_KEY)])[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([(CKA_CLASS, CKO_PUBLIC_KEY)])[0] result = session.verify(pubKey, binascii.unhexlify(toSign), signature, mechanism) print("\nVerified:", result) # logout session.logout() session.closeSession() PyKCS11-1.5.7/samples/unblock.py0000755000076500000240000000214513421700724017270 0ustar rousseaustaff00000000000000#!/usr/bin/env python # 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() PyKCS11-1.5.7/setup.cfg0000644000076500000240000000004613576454261015446 0ustar rousseaustaff00000000000000[egg_info] tag_build = tag_date = 0 PyKCS11-1.5.7/setup.py0000755000076500000240000000641113576454051015341 0ustar rousseaustaff00000000000000#! /usr/bin/env python # python setup.py install --root=/tmp/p # PYTHONPATH=/tmp/p/usr/lib/python2.4/site-packages python test.py from setuptools import setup, Extension from distutils.command.build import build from distutils.file_util import copy_file from sys import version_info as pyver from os import path, system import platform 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") source_files.append("pykcs11.rc") 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 my_build(build): def run(self): self.run_command("build_ext") copy_file("src/LowLevel.py", "PyKCS11") self.run_command("build_py") build.run(self) setup( name="PyKCS11", version="1.5.7", 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": my_build}, ext_modules=[ Extension( "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"], ) PyKCS11-1.5.7/src/0000755000076500000240000000000013576454261014414 5ustar rousseaustaff00000000000000PyKCS11-1.5.7/src/LowLevel.py0000644000076500000240000021137013576453600016517 0ustar rousseaustaff00000000000000# This file was automatically generated by SWIG (http://www.swig.org). # Version 4.0.1 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info as _swig_python_version_info if _swig_python_version_info < (2, 7, 0): raise RuntimeError("Python 2.7 or later required") # Import the low-level C/C++ module if __package__ or "." in __name__: from . import _LowLevel else: import _LowLevel try: import builtins as __builtin__ except ImportError: import __builtin__ def _swig_repr(self): try: strthis = "proxy of " + self.this.__repr__() except __builtin__.Exception: strthis = "" return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) def _swig_setattr_nondynamic_instance_variable(set): def set_instance_attr(self, name, value): if name == "thisown": self.this.own(value) elif name == "this": set(self, name, value) elif hasattr(self, name) and isinstance(getattr(type(self), name), property): set(self, name, value) else: raise AttributeError("You cannot add instance attributes to %s" % self) return set_instance_attr def _swig_setattr_nondynamic_class_variable(set): def set_class_attr(cls, name, value): if hasattr(cls, name) and not isinstance(getattr(cls, name), property): set(cls, name, value) else: raise AttributeError("You cannot add class attributes to %s" % cls) return set_class_attr def _swig_add_metaclass(metaclass): """Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass""" def wrapper(cls): return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy()) return wrapper class _SwigNonDynamicMeta(type): """Meta class to enforce nondynamic attributes (no new attributes) for a class""" __setattr__ = _swig_setattr_nondynamic_class_variable(type.__setattr__) def cdata(ptr, nelements=1): return _LowLevel.cdata(ptr, nelements) def memmove(data, indata): return _LowLevel.memmove(data, indata) class SwigPyIterator(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract") __repr__ = _swig_repr __swig_destroy__ = _LowLevel.delete_SwigPyIterator def value(self): return _LowLevel.SwigPyIterator_value(self) def incr(self, n=1): return _LowLevel.SwigPyIterator_incr(self, n) def decr(self, n=1): return _LowLevel.SwigPyIterator_decr(self, n) def distance(self, x): return _LowLevel.SwigPyIterator_distance(self, x) def equal(self, x): return _LowLevel.SwigPyIterator_equal(self, x) def copy(self): return _LowLevel.SwigPyIterator_copy(self) def next(self): return _LowLevel.SwigPyIterator_next(self) def __next__(self): return _LowLevel.SwigPyIterator___next__(self) def previous(self): return _LowLevel.SwigPyIterator_previous(self) def advance(self, n): return _LowLevel.SwigPyIterator_advance(self, n) def __eq__(self, x): return _LowLevel.SwigPyIterator___eq__(self, x) def __ne__(self, x): return _LowLevel.SwigPyIterator___ne__(self, x) def __iadd__(self, n): return _LowLevel.SwigPyIterator___iadd__(self, n) def __isub__(self, n): return _LowLevel.SwigPyIterator___isub__(self, n) def __add__(self, n): return _LowLevel.SwigPyIterator___add__(self, n) def __sub__(self, *args): return _LowLevel.SwigPyIterator___sub__(self, *args) def __iter__(self): return self # Register SwigPyIterator in _LowLevel: _LowLevel.SwigPyIterator_swigregister(SwigPyIterator) class ckintlist(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def iterator(self): return _LowLevel.ckintlist_iterator(self) def __iter__(self): return self.iterator() def __nonzero__(self): return _LowLevel.ckintlist___nonzero__(self) def __bool__(self): return _LowLevel.ckintlist___bool__(self) def __len__(self): return _LowLevel.ckintlist___len__(self) def __getslice__(self, i, j): return _LowLevel.ckintlist___getslice__(self, i, j) def __setslice__(self, *args): return _LowLevel.ckintlist___setslice__(self, *args) def __delslice__(self, i, j): return _LowLevel.ckintlist___delslice__(self, i, j) def __delitem__(self, *args): return _LowLevel.ckintlist___delitem__(self, *args) def __getitem__(self, *args): return _LowLevel.ckintlist___getitem__(self, *args) def __setitem__(self, *args): return _LowLevel.ckintlist___setitem__(self, *args) def pop(self): return _LowLevel.ckintlist_pop(self) def append(self, x): return _LowLevel.ckintlist_append(self, x) def empty(self): return _LowLevel.ckintlist_empty(self) def size(self): return _LowLevel.ckintlist_size(self) def swap(self, v): return _LowLevel.ckintlist_swap(self, v) def begin(self): return _LowLevel.ckintlist_begin(self) def end(self): return _LowLevel.ckintlist_end(self) def rbegin(self): return _LowLevel.ckintlist_rbegin(self) def rend(self): return _LowLevel.ckintlist_rend(self) def clear(self): return _LowLevel.ckintlist_clear(self) def get_allocator(self): return _LowLevel.ckintlist_get_allocator(self) def pop_back(self): return _LowLevel.ckintlist_pop_back(self) def erase(self, *args): return _LowLevel.ckintlist_erase(self, *args) def __init__(self, *args): _LowLevel.ckintlist_swiginit(self, _LowLevel.new_ckintlist(*args)) def push_back(self, x): return _LowLevel.ckintlist_push_back(self, x) def front(self): return _LowLevel.ckintlist_front(self) def back(self): return _LowLevel.ckintlist_back(self) def assign(self, n, x): return _LowLevel.ckintlist_assign(self, n, x) def resize(self, *args): return _LowLevel.ckintlist_resize(self, *args) def insert(self, *args): return _LowLevel.ckintlist_insert(self, *args) def reserve(self, n): return _LowLevel.ckintlist_reserve(self, n) def capacity(self): return _LowLevel.ckintlist_capacity(self) __swig_destroy__ = _LowLevel.delete_ckintlist # Register ckintlist in _LowLevel: _LowLevel.ckintlist_swigregister(ckintlist) class ckbytelist(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def iterator(self): return _LowLevel.ckbytelist_iterator(self) def __iter__(self): return self.iterator() def __nonzero__(self): return _LowLevel.ckbytelist___nonzero__(self) def __bool__(self): return _LowLevel.ckbytelist___bool__(self) def __len__(self): return _LowLevel.ckbytelist___len__(self) def __getslice__(self, i, j): return _LowLevel.ckbytelist___getslice__(self, i, j) def __setslice__(self, *args): return _LowLevel.ckbytelist___setslice__(self, *args) def __delslice__(self, i, j): return _LowLevel.ckbytelist___delslice__(self, i, j) def __delitem__(self, *args): return _LowLevel.ckbytelist___delitem__(self, *args) def __getitem__(self, *args): return _LowLevel.ckbytelist___getitem__(self, *args) def __setitem__(self, *args): return _LowLevel.ckbytelist___setitem__(self, *args) def pop(self): return _LowLevel.ckbytelist_pop(self) def append(self, x): return _LowLevel.ckbytelist_append(self, x) def empty(self): return _LowLevel.ckbytelist_empty(self) def size(self): return _LowLevel.ckbytelist_size(self) def swap(self, v): return _LowLevel.ckbytelist_swap(self, v) def begin(self): return _LowLevel.ckbytelist_begin(self) def end(self): return _LowLevel.ckbytelist_end(self) def rbegin(self): return _LowLevel.ckbytelist_rbegin(self) def rend(self): return _LowLevel.ckbytelist_rend(self) def clear(self): return _LowLevel.ckbytelist_clear(self) def get_allocator(self): return _LowLevel.ckbytelist_get_allocator(self) def pop_back(self): return _LowLevel.ckbytelist_pop_back(self) def erase(self, *args): return _LowLevel.ckbytelist_erase(self, *args) def __init__(self, *args): _LowLevel.ckbytelist_swiginit(self, _LowLevel.new_ckbytelist(*args)) def push_back(self, x): return _LowLevel.ckbytelist_push_back(self, x) def front(self): return _LowLevel.ckbytelist_front(self) def back(self): return _LowLevel.ckbytelist_back(self) def assign(self, n, x): return _LowLevel.ckbytelist_assign(self, n, x) def resize(self, *args): return _LowLevel.ckbytelist_resize(self, *args) def insert(self, *args): return _LowLevel.ckbytelist_insert(self, *args) def reserve(self, n): return _LowLevel.ckbytelist_reserve(self, n) def capacity(self): return _LowLevel.ckbytelist_capacity(self) __swig_destroy__ = _LowLevel.delete_ckbytelist # Register ckbytelist in _LowLevel: _LowLevel.ckbytelist_swigregister(ckbytelist) class ckattrlist(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def iterator(self): return _LowLevel.ckattrlist_iterator(self) def __iter__(self): return self.iterator() def __nonzero__(self): return _LowLevel.ckattrlist___nonzero__(self) def __bool__(self): return _LowLevel.ckattrlist___bool__(self) def __len__(self): return _LowLevel.ckattrlist___len__(self) def __getslice__(self, i, j): return _LowLevel.ckattrlist___getslice__(self, i, j) def __setslice__(self, *args): return _LowLevel.ckattrlist___setslice__(self, *args) def __delslice__(self, i, j): return _LowLevel.ckattrlist___delslice__(self, i, j) def __delitem__(self, *args): return _LowLevel.ckattrlist___delitem__(self, *args) def __getitem__(self, *args): return _LowLevel.ckattrlist___getitem__(self, *args) def __setitem__(self, *args): return _LowLevel.ckattrlist___setitem__(self, *args) def pop(self): return _LowLevel.ckattrlist_pop(self) def append(self, x): return _LowLevel.ckattrlist_append(self, x) def empty(self): return _LowLevel.ckattrlist_empty(self) def size(self): return _LowLevel.ckattrlist_size(self) def swap(self, v): return _LowLevel.ckattrlist_swap(self, v) def begin(self): return _LowLevel.ckattrlist_begin(self) def end(self): return _LowLevel.ckattrlist_end(self) def rbegin(self): return _LowLevel.ckattrlist_rbegin(self) def rend(self): return _LowLevel.ckattrlist_rend(self) def clear(self): return _LowLevel.ckattrlist_clear(self) def get_allocator(self): return _LowLevel.ckattrlist_get_allocator(self) def pop_back(self): return _LowLevel.ckattrlist_pop_back(self) def erase(self, *args): return _LowLevel.ckattrlist_erase(self, *args) def __init__(self, *args): _LowLevel.ckattrlist_swiginit(self, _LowLevel.new_ckattrlist(*args)) def push_back(self, x): return _LowLevel.ckattrlist_push_back(self, x) def front(self): return _LowLevel.ckattrlist_front(self) def back(self): return _LowLevel.ckattrlist_back(self) def assign(self, n, x): return _LowLevel.ckattrlist_assign(self, n, x) def resize(self, *args): return _LowLevel.ckattrlist_resize(self, *args) def insert(self, *args): return _LowLevel.ckattrlist_insert(self, *args) def reserve(self, n): return _LowLevel.ckattrlist_reserve(self, n) def capacity(self): return _LowLevel.ckattrlist_capacity(self) __swig_destroy__ = _LowLevel.delete_ckattrlist # Register ckattrlist in _LowLevel: _LowLevel.ckattrlist_swigregister(ckattrlist) class ckobjlist(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def iterator(self): return _LowLevel.ckobjlist_iterator(self) def __iter__(self): return self.iterator() def __nonzero__(self): return _LowLevel.ckobjlist___nonzero__(self) def __bool__(self): return _LowLevel.ckobjlist___bool__(self) def __len__(self): return _LowLevel.ckobjlist___len__(self) def __getslice__(self, i, j): return _LowLevel.ckobjlist___getslice__(self, i, j) def __setslice__(self, *args): return _LowLevel.ckobjlist___setslice__(self, *args) def __delslice__(self, i, j): return _LowLevel.ckobjlist___delslice__(self, i, j) def __delitem__(self, *args): return _LowLevel.ckobjlist___delitem__(self, *args) def __getitem__(self, *args): return _LowLevel.ckobjlist___getitem__(self, *args) def __setitem__(self, *args): return _LowLevel.ckobjlist___setitem__(self, *args) def pop(self): return _LowLevel.ckobjlist_pop(self) def append(self, x): return _LowLevel.ckobjlist_append(self, x) def empty(self): return _LowLevel.ckobjlist_empty(self) def size(self): return _LowLevel.ckobjlist_size(self) def swap(self, v): return _LowLevel.ckobjlist_swap(self, v) def begin(self): return _LowLevel.ckobjlist_begin(self) def end(self): return _LowLevel.ckobjlist_end(self) def rbegin(self): return _LowLevel.ckobjlist_rbegin(self) def rend(self): return _LowLevel.ckobjlist_rend(self) def clear(self): return _LowLevel.ckobjlist_clear(self) def get_allocator(self): return _LowLevel.ckobjlist_get_allocator(self) def pop_back(self): return _LowLevel.ckobjlist_pop_back(self) def erase(self, *args): return _LowLevel.ckobjlist_erase(self, *args) def __init__(self, *args): _LowLevel.ckobjlist_swiginit(self, _LowLevel.new_ckobjlist(*args)) def push_back(self, x): return _LowLevel.ckobjlist_push_back(self, x) def front(self): return _LowLevel.ckobjlist_front(self) def back(self): return _LowLevel.ckobjlist_back(self) def assign(self, n, x): return _LowLevel.ckobjlist_assign(self, n, x) def resize(self, *args): return _LowLevel.ckobjlist_resize(self, *args) def insert(self, *args): return _LowLevel.ckobjlist_insert(self, *args) def reserve(self, n): return _LowLevel.ckobjlist_reserve(self, n) def capacity(self): return _LowLevel.ckobjlist_capacity(self) __swig_destroy__ = _LowLevel.delete_ckobjlist # Register ckobjlist in _LowLevel: _LowLevel.ckobjlist_swigregister(ckobjlist) class CK_SESSION_HANDLE(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): _LowLevel.CK_SESSION_HANDLE_swiginit(self, _LowLevel.new_CK_SESSION_HANDLE()) __swig_destroy__ = _LowLevel.delete_CK_SESSION_HANDLE def assign(self, value): return _LowLevel.CK_SESSION_HANDLE_assign(self, value) def value(self): return _LowLevel.CK_SESSION_HANDLE_value(self) def cast(self): return _LowLevel.CK_SESSION_HANDLE_cast(self) @staticmethod def frompointer(t): return _LowLevel.CK_SESSION_HANDLE_frompointer(t) # Register CK_SESSION_HANDLE in _LowLevel: _LowLevel.CK_SESSION_HANDLE_swigregister(CK_SESSION_HANDLE) def CK_SESSION_HANDLE_frompointer(t): return _LowLevel.CK_SESSION_HANDLE_frompointer(t) class CK_OBJECT_HANDLE(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): _LowLevel.CK_OBJECT_HANDLE_swiginit(self, _LowLevel.new_CK_OBJECT_HANDLE()) __swig_destroy__ = _LowLevel.delete_CK_OBJECT_HANDLE def assign(self, value): return _LowLevel.CK_OBJECT_HANDLE_assign(self, value) def value(self): return _LowLevel.CK_OBJECT_HANDLE_value(self) def cast(self): return _LowLevel.CK_OBJECT_HANDLE_cast(self) @staticmethod def frompointer(t): return _LowLevel.CK_OBJECT_HANDLE_frompointer(t) # Register CK_OBJECT_HANDLE in _LowLevel: _LowLevel.CK_OBJECT_HANDLE_swigregister(CK_OBJECT_HANDLE) def CK_OBJECT_HANDLE_frompointer(t): return _LowLevel.CK_OBJECT_HANDLE_frompointer(t) class CK_VERSION(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr major = property(_LowLevel.CK_VERSION_major_get) minor = property(_LowLevel.CK_VERSION_minor_get) def __init__(self): _LowLevel.CK_VERSION_swiginit(self, _LowLevel.new_CK_VERSION()) __swig_destroy__ = _LowLevel.delete_CK_VERSION # Register CK_VERSION in _LowLevel: _LowLevel.CK_VERSION_swigregister(CK_VERSION) class CK_INFO(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr cryptokiVersion = property(_LowLevel.CK_INFO_cryptokiVersion_get) manufacturerID = property(_LowLevel.CK_INFO_manufacturerID_get) flags = property(_LowLevel.CK_INFO_flags_get) libraryDescription = property(_LowLevel.CK_INFO_libraryDescription_get) libraryVersion = property(_LowLevel.CK_INFO_libraryVersion_get) def GetManufacturerID(self): return _LowLevel.CK_INFO_GetManufacturerID(self) def GetLibraryDescription(self): return _LowLevel.CK_INFO_GetLibraryDescription(self) def GetLibraryVersion(self): return _LowLevel.CK_INFO_GetLibraryVersion(self) def __init__(self): _LowLevel.CK_INFO_swiginit(self, _LowLevel.new_CK_INFO()) __swig_destroy__ = _LowLevel.delete_CK_INFO # Register CK_INFO in _LowLevel: _LowLevel.CK_INFO_swigregister(CK_INFO) class CK_SLOT_INFO(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr flags = property(_LowLevel.CK_SLOT_INFO_flags_get) hardwareVersion = property(_LowLevel.CK_SLOT_INFO_hardwareVersion_get) firmwareVersion = property(_LowLevel.CK_SLOT_INFO_firmwareVersion_get) def GetManufacturerID(self): return _LowLevel.CK_SLOT_INFO_GetManufacturerID(self) def GetSlotDescription(self): return _LowLevel.CK_SLOT_INFO_GetSlotDescription(self) def GetHardwareVersion(self): return _LowLevel.CK_SLOT_INFO_GetHardwareVersion(self) def GetFirmwareVersion(self): return _LowLevel.CK_SLOT_INFO_GetFirmwareVersion(self) def __init__(self): _LowLevel.CK_SLOT_INFO_swiginit(self, _LowLevel.new_CK_SLOT_INFO()) __swig_destroy__ = _LowLevel.delete_CK_SLOT_INFO # Register CK_SLOT_INFO in _LowLevel: _LowLevel.CK_SLOT_INFO_swigregister(CK_SLOT_INFO) class CK_TOKEN_INFO(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr flags = property(_LowLevel.CK_TOKEN_INFO_flags_get) ulMaxSessionCount = property(_LowLevel.CK_TOKEN_INFO_ulMaxSessionCount_get) ulSessionCount = property(_LowLevel.CK_TOKEN_INFO_ulSessionCount_get) ulMaxRwSessionCount = property(_LowLevel.CK_TOKEN_INFO_ulMaxRwSessionCount_get) ulRwSessionCount = property(_LowLevel.CK_TOKEN_INFO_ulRwSessionCount_get) ulMaxPinLen = property(_LowLevel.CK_TOKEN_INFO_ulMaxPinLen_get) ulMinPinLen = property(_LowLevel.CK_TOKEN_INFO_ulMinPinLen_get) ulTotalPublicMemory = property(_LowLevel.CK_TOKEN_INFO_ulTotalPublicMemory_get) ulFreePublicMemory = property(_LowLevel.CK_TOKEN_INFO_ulFreePublicMemory_get) ulTotalPrivateMemory = property(_LowLevel.CK_TOKEN_INFO_ulTotalPrivateMemory_get) ulFreePrivateMemory = property(_LowLevel.CK_TOKEN_INFO_ulFreePrivateMemory_get) hardwareVersion = property(_LowLevel.CK_TOKEN_INFO_hardwareVersion_get) firmwareVersion = property(_LowLevel.CK_TOKEN_INFO_firmwareVersion_get) def GetLabel(self): return _LowLevel.CK_TOKEN_INFO_GetLabel(self) def GetManufacturerID(self): return _LowLevel.CK_TOKEN_INFO_GetManufacturerID(self) def GetModel(self): return _LowLevel.CK_TOKEN_INFO_GetModel(self) def GetSerialNumber(self): return _LowLevel.CK_TOKEN_INFO_GetSerialNumber(self) def GetFirmwareVersion(self): return _LowLevel.CK_TOKEN_INFO_GetFirmwareVersion(self) def GetUtcTime(self): return _LowLevel.CK_TOKEN_INFO_GetUtcTime(self) def __init__(self): _LowLevel.CK_TOKEN_INFO_swiginit(self, _LowLevel.new_CK_TOKEN_INFO()) __swig_destroy__ = _LowLevel.delete_CK_TOKEN_INFO # Register CK_TOKEN_INFO in _LowLevel: _LowLevel.CK_TOKEN_INFO_swigregister(CK_TOKEN_INFO) class CK_SESSION_INFO(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr slotID = property(_LowLevel.CK_SESSION_INFO_slotID_get) state = property(_LowLevel.CK_SESSION_INFO_state_get) flags = property(_LowLevel.CK_SESSION_INFO_flags_get) ulDeviceError = property(_LowLevel.CK_SESSION_INFO_ulDeviceError_get) def __init__(self): _LowLevel.CK_SESSION_INFO_swiginit(self, _LowLevel.new_CK_SESSION_INFO()) __swig_destroy__ = _LowLevel.delete_CK_SESSION_INFO # Register CK_SESSION_INFO in _LowLevel: _LowLevel.CK_SESSION_INFO_swigregister(CK_SESSION_INFO) class CK_DATE(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def GetYear(self): return _LowLevel.CK_DATE_GetYear(self) def GetMonth(self): return _LowLevel.CK_DATE_GetMonth(self) def GetDay(self): return _LowLevel.CK_DATE_GetDay(self) def __init__(self): _LowLevel.CK_DATE_swiginit(self, _LowLevel.new_CK_DATE()) __swig_destroy__ = _LowLevel.delete_CK_DATE # Register CK_DATE in _LowLevel: _LowLevel.CK_DATE_swigregister(CK_DATE) class CK_MECHANISM(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr mechanism = property(_LowLevel.CK_MECHANISM_mechanism_get, _LowLevel.CK_MECHANISM_mechanism_set) pParameter = property(_LowLevel.CK_MECHANISM_pParameter_get, _LowLevel.CK_MECHANISM_pParameter_set) ulParameterLen = property(_LowLevel.CK_MECHANISM_ulParameterLen_get, _LowLevel.CK_MECHANISM_ulParameterLen_set) def __init__(self): _LowLevel.CK_MECHANISM_swiginit(self, _LowLevel.new_CK_MECHANISM()) __swig_destroy__ = _LowLevel.delete_CK_MECHANISM # Register CK_MECHANISM in _LowLevel: _LowLevel.CK_MECHANISM_swigregister(CK_MECHANISM) class CK_GCM_PARAMS(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr pIv = property(_LowLevel.CK_GCM_PARAMS_pIv_get, _LowLevel.CK_GCM_PARAMS_pIv_set) ulIvLen = property(_LowLevel.CK_GCM_PARAMS_ulIvLen_get, _LowLevel.CK_GCM_PARAMS_ulIvLen_set) pAAD = property(_LowLevel.CK_GCM_PARAMS_pAAD_get, _LowLevel.CK_GCM_PARAMS_pAAD_set) ulAADLen = property(_LowLevel.CK_GCM_PARAMS_ulAADLen_get, _LowLevel.CK_GCM_PARAMS_ulAADLen_set) ulTagBits = property(_LowLevel.CK_GCM_PARAMS_ulTagBits_get, _LowLevel.CK_GCM_PARAMS_ulTagBits_set) def __init__(self): _LowLevel.CK_GCM_PARAMS_swiginit(self, _LowLevel.new_CK_GCM_PARAMS()) __swig_destroy__ = _LowLevel.delete_CK_GCM_PARAMS # Register CK_GCM_PARAMS in _LowLevel: _LowLevel.CK_GCM_PARAMS_swigregister(CK_GCM_PARAMS) CK_GCM_PARAMS_LENGTH = _LowLevel.CK_GCM_PARAMS_LENGTH class CK_RSA_PKCS_OAEP_PARAMS(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr hashAlg = property(_LowLevel.CK_RSA_PKCS_OAEP_PARAMS_hashAlg_get, _LowLevel.CK_RSA_PKCS_OAEP_PARAMS_hashAlg_set) mgf = property(_LowLevel.CK_RSA_PKCS_OAEP_PARAMS_mgf_get, _LowLevel.CK_RSA_PKCS_OAEP_PARAMS_mgf_set) src = property(_LowLevel.CK_RSA_PKCS_OAEP_PARAMS_src_get, _LowLevel.CK_RSA_PKCS_OAEP_PARAMS_src_set) pSourceData = property(_LowLevel.CK_RSA_PKCS_OAEP_PARAMS_pSourceData_get, _LowLevel.CK_RSA_PKCS_OAEP_PARAMS_pSourceData_set) ulSourceDataLen = property(_LowLevel.CK_RSA_PKCS_OAEP_PARAMS_ulSourceDataLen_get, _LowLevel.CK_RSA_PKCS_OAEP_PARAMS_ulSourceDataLen_set) def __init__(self): _LowLevel.CK_RSA_PKCS_OAEP_PARAMS_swiginit(self, _LowLevel.new_CK_RSA_PKCS_OAEP_PARAMS()) __swig_destroy__ = _LowLevel.delete_CK_RSA_PKCS_OAEP_PARAMS # Register CK_RSA_PKCS_OAEP_PARAMS in _LowLevel: _LowLevel.CK_RSA_PKCS_OAEP_PARAMS_swigregister(CK_RSA_PKCS_OAEP_PARAMS) CK_RSA_PKCS_OAEP_PARAMS_LENGTH = _LowLevel.CK_RSA_PKCS_OAEP_PARAMS_LENGTH class CK_RSA_PKCS_PSS_PARAMS(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr hashAlg = property(_LowLevel.CK_RSA_PKCS_PSS_PARAMS_hashAlg_get, _LowLevel.CK_RSA_PKCS_PSS_PARAMS_hashAlg_set) mgf = property(_LowLevel.CK_RSA_PKCS_PSS_PARAMS_mgf_get, _LowLevel.CK_RSA_PKCS_PSS_PARAMS_mgf_set) sLen = property(_LowLevel.CK_RSA_PKCS_PSS_PARAMS_sLen_get, _LowLevel.CK_RSA_PKCS_PSS_PARAMS_sLen_set) def __init__(self): _LowLevel.CK_RSA_PKCS_PSS_PARAMS_swiginit(self, _LowLevel.new_CK_RSA_PKCS_PSS_PARAMS()) __swig_destroy__ = _LowLevel.delete_CK_RSA_PKCS_PSS_PARAMS # Register CK_RSA_PKCS_PSS_PARAMS in _LowLevel: _LowLevel.CK_RSA_PKCS_PSS_PARAMS_swigregister(CK_RSA_PKCS_PSS_PARAMS) CK_RSA_PKCS_PSS_PARAMS_LENGTH = _LowLevel.CK_RSA_PKCS_PSS_PARAMS_LENGTH class CK_MECHANISM_INFO(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr ulMinKeySize = property(_LowLevel.CK_MECHANISM_INFO_ulMinKeySize_get) ulMaxKeySize = property(_LowLevel.CK_MECHANISM_INFO_ulMaxKeySize_get) flags = property(_LowLevel.CK_MECHANISM_INFO_flags_get) def __init__(self): _LowLevel.CK_MECHANISM_INFO_swiginit(self, _LowLevel.new_CK_MECHANISM_INFO()) __swig_destroy__ = _LowLevel.delete_CK_MECHANISM_INFO # Register CK_MECHANISM_INFO in _LowLevel: _LowLevel.CK_MECHANISM_INFO_swigregister(CK_MECHANISM_INFO) FALSE = _LowLevel.FALSE TRUE = _LowLevel.TRUE CK_TRUE = _LowLevel.CK_TRUE CK_FALSE = _LowLevel.CK_FALSE CK_UNAVAILABLE_INFORMATION = _LowLevel.CK_UNAVAILABLE_INFORMATION CK_EFFECTIVELY_INFINITE = _LowLevel.CK_EFFECTIVELY_INFINITE CK_INVALID_HANDLE = _LowLevel.CK_INVALID_HANDLE CKN_SURRENDER = _LowLevel.CKN_SURRENDER CKF_TOKEN_PRESENT = _LowLevel.CKF_TOKEN_PRESENT CKF_REMOVABLE_DEVICE = _LowLevel.CKF_REMOVABLE_DEVICE CKF_HW_SLOT = _LowLevel.CKF_HW_SLOT CKF_RNG = _LowLevel.CKF_RNG CKF_WRITE_PROTECTED = _LowLevel.CKF_WRITE_PROTECTED CKF_LOGIN_REQUIRED = _LowLevel.CKF_LOGIN_REQUIRED CKF_USER_PIN_INITIALIZED = _LowLevel.CKF_USER_PIN_INITIALIZED CKF_RESTORE_KEY_NOT_NEEDED = _LowLevel.CKF_RESTORE_KEY_NOT_NEEDED CKF_CLOCK_ON_TOKEN = _LowLevel.CKF_CLOCK_ON_TOKEN CKF_PROTECTED_AUTHENTICATION_PATH = _LowLevel.CKF_PROTECTED_AUTHENTICATION_PATH CKF_DUAL_CRYPTO_OPERATIONS = _LowLevel.CKF_DUAL_CRYPTO_OPERATIONS CKF_TOKEN_INITIALIZED = _LowLevel.CKF_TOKEN_INITIALIZED CKF_SECONDARY_AUTHENTICATION = _LowLevel.CKF_SECONDARY_AUTHENTICATION CKF_USER_PIN_COUNT_LOW = _LowLevel.CKF_USER_PIN_COUNT_LOW CKF_USER_PIN_FINAL_TRY = _LowLevel.CKF_USER_PIN_FINAL_TRY CKF_USER_PIN_LOCKED = _LowLevel.CKF_USER_PIN_LOCKED CKF_USER_PIN_TO_BE_CHANGED = _LowLevel.CKF_USER_PIN_TO_BE_CHANGED CKF_SO_PIN_COUNT_LOW = _LowLevel.CKF_SO_PIN_COUNT_LOW CKF_SO_PIN_FINAL_TRY = _LowLevel.CKF_SO_PIN_FINAL_TRY CKF_SO_PIN_LOCKED = _LowLevel.CKF_SO_PIN_LOCKED CKF_SO_PIN_TO_BE_CHANGED = _LowLevel.CKF_SO_PIN_TO_BE_CHANGED CKF_ARRAY_ATTRIBUTE = _LowLevel.CKF_ARRAY_ATTRIBUTE CKU_SO = _LowLevel.CKU_SO CKU_USER = _LowLevel.CKU_USER CKU_CONTEXT_SPECIFIC = _LowLevel.CKU_CONTEXT_SPECIFIC CKS_RO_PUBLIC_SESSION = _LowLevel.CKS_RO_PUBLIC_SESSION CKS_RO_USER_FUNCTIONS = _LowLevel.CKS_RO_USER_FUNCTIONS CKS_RW_PUBLIC_SESSION = _LowLevel.CKS_RW_PUBLIC_SESSION CKS_RW_USER_FUNCTIONS = _LowLevel.CKS_RW_USER_FUNCTIONS CKS_RW_SO_FUNCTIONS = _LowLevel.CKS_RW_SO_FUNCTIONS CKF_RW_SESSION = _LowLevel.CKF_RW_SESSION CKF_SERIAL_SESSION = _LowLevel.CKF_SERIAL_SESSION CKO_DATA = _LowLevel.CKO_DATA CKO_CERTIFICATE = _LowLevel.CKO_CERTIFICATE CKO_PUBLIC_KEY = _LowLevel.CKO_PUBLIC_KEY CKO_PRIVATE_KEY = _LowLevel.CKO_PRIVATE_KEY CKO_SECRET_KEY = _LowLevel.CKO_SECRET_KEY CKO_HW_FEATURE = _LowLevel.CKO_HW_FEATURE CKO_DOMAIN_PARAMETERS = _LowLevel.CKO_DOMAIN_PARAMETERS CKO_MECHANISM = _LowLevel.CKO_MECHANISM CKO_OTP_KEY = _LowLevel.CKO_OTP_KEY CKO_VENDOR_DEFINED = _LowLevel.CKO_VENDOR_DEFINED CKH_MONOTONIC_COUNTER = _LowLevel.CKH_MONOTONIC_COUNTER CKH_CLOCK = _LowLevel.CKH_CLOCK CKH_USER_INTERFACE = _LowLevel.CKH_USER_INTERFACE CKH_VENDOR_DEFINED = _LowLevel.CKH_VENDOR_DEFINED CKK_RSA = _LowLevel.CKK_RSA CKK_DSA = _LowLevel.CKK_DSA CKK_DH = _LowLevel.CKK_DH CKK_ECDSA = _LowLevel.CKK_ECDSA CKK_EC = _LowLevel.CKK_EC CKK_X9_42_DH = _LowLevel.CKK_X9_42_DH CKK_KEA = _LowLevel.CKK_KEA CKK_GENERIC_SECRET = _LowLevel.CKK_GENERIC_SECRET CKK_RC2 = _LowLevel.CKK_RC2 CKK_RC4 = _LowLevel.CKK_RC4 CKK_DES = _LowLevel.CKK_DES CKK_DES2 = _LowLevel.CKK_DES2 CKK_DES3 = _LowLevel.CKK_DES3 CKK_CAST = _LowLevel.CKK_CAST CKK_CAST3 = _LowLevel.CKK_CAST3 CKK_CAST5 = _LowLevel.CKK_CAST5 CKK_CAST128 = _LowLevel.CKK_CAST128 CKK_RC5 = _LowLevel.CKK_RC5 CKK_IDEA = _LowLevel.CKK_IDEA CKK_SKIPJACK = _LowLevel.CKK_SKIPJACK CKK_BATON = _LowLevel.CKK_BATON CKK_JUNIPER = _LowLevel.CKK_JUNIPER CKK_CDMF = _LowLevel.CKK_CDMF CKK_AES = _LowLevel.CKK_AES CKK_BLOWFISH = _LowLevel.CKK_BLOWFISH CKK_TWOFISH = _LowLevel.CKK_TWOFISH CKK_SECURID = _LowLevel.CKK_SECURID CKK_HOTP = _LowLevel.CKK_HOTP CKK_ACTI = _LowLevel.CKK_ACTI CKK_CAMELLIA = _LowLevel.CKK_CAMELLIA CKK_ARIA = _LowLevel.CKK_ARIA CKK_MD5_HMAC = _LowLevel.CKK_MD5_HMAC CKK_SHA_1_HMAC = _LowLevel.CKK_SHA_1_HMAC CKK_RIPEMD128_HMAC = _LowLevel.CKK_RIPEMD128_HMAC CKK_RIPEMD160_HMAC = _LowLevel.CKK_RIPEMD160_HMAC CKK_SHA256_HMAC = _LowLevel.CKK_SHA256_HMAC CKK_SHA384_HMAC = _LowLevel.CKK_SHA384_HMAC CKK_SHA512_HMAC = _LowLevel.CKK_SHA512_HMAC CKK_SHA224_HMAC = _LowLevel.CKK_SHA224_HMAC CKK_GOSTR3410 = _LowLevel.CKK_GOSTR3410 CKK_GOSTR3411 = _LowLevel.CKK_GOSTR3411 CKK_GOST28147 = _LowLevel.CKK_GOST28147 CKK_VENDOR_DEFINED = _LowLevel.CKK_VENDOR_DEFINED CKC_X_509 = _LowLevel.CKC_X_509 CKC_X_509_ATTR_CERT = _LowLevel.CKC_X_509_ATTR_CERT CKC_WTLS = _LowLevel.CKC_WTLS CKC_VENDOR_DEFINED = _LowLevel.CKC_VENDOR_DEFINED CKA_CLASS = _LowLevel.CKA_CLASS CKA_TOKEN = _LowLevel.CKA_TOKEN CKA_PRIVATE = _LowLevel.CKA_PRIVATE CKA_LABEL = _LowLevel.CKA_LABEL CKA_APPLICATION = _LowLevel.CKA_APPLICATION CKA_VALUE = _LowLevel.CKA_VALUE CKA_OBJECT_ID = _LowLevel.CKA_OBJECT_ID CKA_CERTIFICATE_TYPE = _LowLevel.CKA_CERTIFICATE_TYPE CKA_ISSUER = _LowLevel.CKA_ISSUER CKA_SERIAL_NUMBER = _LowLevel.CKA_SERIAL_NUMBER CKA_AC_ISSUER = _LowLevel.CKA_AC_ISSUER CKA_OWNER = _LowLevel.CKA_OWNER CKA_ATTR_TYPES = _LowLevel.CKA_ATTR_TYPES CKA_TRUSTED = _LowLevel.CKA_TRUSTED CKA_CERTIFICATE_CATEGORY = _LowLevel.CKA_CERTIFICATE_CATEGORY CKA_JAVA_MIDP_SECURITY_DOMAIN = _LowLevel.CKA_JAVA_MIDP_SECURITY_DOMAIN CKA_URL = _LowLevel.CKA_URL CKA_HASH_OF_SUBJECT_PUBLIC_KEY = _LowLevel.CKA_HASH_OF_SUBJECT_PUBLIC_KEY CKA_HASH_OF_ISSUER_PUBLIC_KEY = _LowLevel.CKA_HASH_OF_ISSUER_PUBLIC_KEY CKA_CHECK_VALUE = _LowLevel.CKA_CHECK_VALUE CKA_KEY_TYPE = _LowLevel.CKA_KEY_TYPE CKA_SUBJECT = _LowLevel.CKA_SUBJECT CKA_ID = _LowLevel.CKA_ID CKA_SENSITIVE = _LowLevel.CKA_SENSITIVE CKA_ENCRYPT = _LowLevel.CKA_ENCRYPT CKA_DECRYPT = _LowLevel.CKA_DECRYPT CKA_WRAP = _LowLevel.CKA_WRAP CKA_UNWRAP = _LowLevel.CKA_UNWRAP CKA_SIGN = _LowLevel.CKA_SIGN CKA_SIGN_RECOVER = _LowLevel.CKA_SIGN_RECOVER CKA_VERIFY = _LowLevel.CKA_VERIFY CKA_VERIFY_RECOVER = _LowLevel.CKA_VERIFY_RECOVER CKA_DERIVE = _LowLevel.CKA_DERIVE CKA_START_DATE = _LowLevel.CKA_START_DATE CKA_END_DATE = _LowLevel.CKA_END_DATE CKA_MODULUS = _LowLevel.CKA_MODULUS CKA_MODULUS_BITS = _LowLevel.CKA_MODULUS_BITS CKA_PUBLIC_EXPONENT = _LowLevel.CKA_PUBLIC_EXPONENT CKA_PRIVATE_EXPONENT = _LowLevel.CKA_PRIVATE_EXPONENT CKA_PRIME_1 = _LowLevel.CKA_PRIME_1 CKA_PRIME_2 = _LowLevel.CKA_PRIME_2 CKA_EXPONENT_1 = _LowLevel.CKA_EXPONENT_1 CKA_EXPONENT_2 = _LowLevel.CKA_EXPONENT_2 CKA_COEFFICIENT = _LowLevel.CKA_COEFFICIENT CKA_PRIME = _LowLevel.CKA_PRIME CKA_SUBPRIME = _LowLevel.CKA_SUBPRIME CKA_BASE = _LowLevel.CKA_BASE CKA_PRIME_BITS = _LowLevel.CKA_PRIME_BITS CKA_SUBPRIME_BITS = _LowLevel.CKA_SUBPRIME_BITS CKA_SUB_PRIME_BITS = _LowLevel.CKA_SUB_PRIME_BITS CKA_VALUE_BITS = _LowLevel.CKA_VALUE_BITS CKA_VALUE_LEN = _LowLevel.CKA_VALUE_LEN CKA_EXTRACTABLE = _LowLevel.CKA_EXTRACTABLE CKA_LOCAL = _LowLevel.CKA_LOCAL CKA_NEVER_EXTRACTABLE = _LowLevel.CKA_NEVER_EXTRACTABLE CKA_ALWAYS_SENSITIVE = _LowLevel.CKA_ALWAYS_SENSITIVE CKA_KEY_GEN_MECHANISM = _LowLevel.CKA_KEY_GEN_MECHANISM CKA_MODIFIABLE = _LowLevel.CKA_MODIFIABLE CKA_ECDSA_PARAMS = _LowLevel.CKA_ECDSA_PARAMS CKA_EC_PARAMS = _LowLevel.CKA_EC_PARAMS CKA_EC_POINT = _LowLevel.CKA_EC_POINT CKA_SECONDARY_AUTH = _LowLevel.CKA_SECONDARY_AUTH CKA_AUTH_PIN_FLAGS = _LowLevel.CKA_AUTH_PIN_FLAGS CKA_ALWAYS_AUTHENTICATE = _LowLevel.CKA_ALWAYS_AUTHENTICATE CKA_WRAP_WITH_TRUSTED = _LowLevel.CKA_WRAP_WITH_TRUSTED CKA_WRAP_TEMPLATE = _LowLevel.CKA_WRAP_TEMPLATE CKA_UNWRAP_TEMPLATE = _LowLevel.CKA_UNWRAP_TEMPLATE CKA_OTP_FORMAT = _LowLevel.CKA_OTP_FORMAT CKA_OTP_LENGTH = _LowLevel.CKA_OTP_LENGTH CKA_OTP_TIME_INTERVAL = _LowLevel.CKA_OTP_TIME_INTERVAL CKA_OTP_USER_FRIENDLY_MODE = _LowLevel.CKA_OTP_USER_FRIENDLY_MODE CKA_OTP_CHALLENGE_REQUIREMENT = _LowLevel.CKA_OTP_CHALLENGE_REQUIREMENT CKA_OTP_TIME_REQUIREMENT = _LowLevel.CKA_OTP_TIME_REQUIREMENT CKA_OTP_COUNTER_REQUIREMENT = _LowLevel.CKA_OTP_COUNTER_REQUIREMENT CKA_OTP_PIN_REQUIREMENT = _LowLevel.CKA_OTP_PIN_REQUIREMENT CKA_OTP_COUNTER = _LowLevel.CKA_OTP_COUNTER CKA_OTP_TIME = _LowLevel.CKA_OTP_TIME CKA_OTP_USER_IDENTIFIER = _LowLevel.CKA_OTP_USER_IDENTIFIER CKA_OTP_SERVICE_IDENTIFIER = _LowLevel.CKA_OTP_SERVICE_IDENTIFIER CKA_OTP_SERVICE_LOGO = _LowLevel.CKA_OTP_SERVICE_LOGO CKA_OTP_SERVICE_LOGO_TYPE = _LowLevel.CKA_OTP_SERVICE_LOGO_TYPE CKA_GOSTR3410_PARAMS = _LowLevel.CKA_GOSTR3410_PARAMS CKA_GOSTR3411_PARAMS = _LowLevel.CKA_GOSTR3411_PARAMS CKA_GOST28147_PARAMS = _LowLevel.CKA_GOST28147_PARAMS CKA_HW_FEATURE_TYPE = _LowLevel.CKA_HW_FEATURE_TYPE CKA_RESET_ON_INIT = _LowLevel.CKA_RESET_ON_INIT CKA_HAS_RESET = _LowLevel.CKA_HAS_RESET CKA_PIXEL_X = _LowLevel.CKA_PIXEL_X CKA_PIXEL_Y = _LowLevel.CKA_PIXEL_Y CKA_RESOLUTION = _LowLevel.CKA_RESOLUTION CKA_CHAR_ROWS = _LowLevel.CKA_CHAR_ROWS CKA_CHAR_COLUMNS = _LowLevel.CKA_CHAR_COLUMNS CKA_COLOR = _LowLevel.CKA_COLOR CKA_BITS_PER_PIXEL = _LowLevel.CKA_BITS_PER_PIXEL CKA_CHAR_SETS = _LowLevel.CKA_CHAR_SETS CKA_ENCODING_METHODS = _LowLevel.CKA_ENCODING_METHODS CKA_MIME_TYPES = _LowLevel.CKA_MIME_TYPES CKA_MECHANISM_TYPE = _LowLevel.CKA_MECHANISM_TYPE CKA_REQUIRED_CMS_ATTRIBUTES = _LowLevel.CKA_REQUIRED_CMS_ATTRIBUTES CKA_DEFAULT_CMS_ATTRIBUTES = _LowLevel.CKA_DEFAULT_CMS_ATTRIBUTES CKA_SUPPORTED_CMS_ATTRIBUTES = _LowLevel.CKA_SUPPORTED_CMS_ATTRIBUTES CKA_ALLOWED_MECHANISMS = _LowLevel.CKA_ALLOWED_MECHANISMS CKA_VENDOR_DEFINED = _LowLevel.CKA_VENDOR_DEFINED CKM_RSA_PKCS_KEY_PAIR_GEN = _LowLevel.CKM_RSA_PKCS_KEY_PAIR_GEN CKM_RSA_PKCS = _LowLevel.CKM_RSA_PKCS CKM_RSA_9796 = _LowLevel.CKM_RSA_9796 CKM_RSA_X_509 = _LowLevel.CKM_RSA_X_509 CKM_MD2_RSA_PKCS = _LowLevel.CKM_MD2_RSA_PKCS CKM_MD5_RSA_PKCS = _LowLevel.CKM_MD5_RSA_PKCS CKM_SHA1_RSA_PKCS = _LowLevel.CKM_SHA1_RSA_PKCS CKM_RIPEMD128_RSA_PKCS = _LowLevel.CKM_RIPEMD128_RSA_PKCS CKM_RIPEMD160_RSA_PKCS = _LowLevel.CKM_RIPEMD160_RSA_PKCS CKM_RSA_PKCS_OAEP = _LowLevel.CKM_RSA_PKCS_OAEP CKM_RSA_X9_31_KEY_PAIR_GEN = _LowLevel.CKM_RSA_X9_31_KEY_PAIR_GEN CKM_RSA_X9_31 = _LowLevel.CKM_RSA_X9_31 CKM_SHA1_RSA_X9_31 = _LowLevel.CKM_SHA1_RSA_X9_31 CKM_RSA_PKCS_PSS = _LowLevel.CKM_RSA_PKCS_PSS CKM_SHA1_RSA_PKCS_PSS = _LowLevel.CKM_SHA1_RSA_PKCS_PSS CKM_DSA_KEY_PAIR_GEN = _LowLevel.CKM_DSA_KEY_PAIR_GEN CKM_DSA = _LowLevel.CKM_DSA CKM_DSA_SHA1 = _LowLevel.CKM_DSA_SHA1 CKM_DSA_SHA224 = _LowLevel.CKM_DSA_SHA224 CKM_DSA_SHA256 = _LowLevel.CKM_DSA_SHA256 CKM_DSA_SHA384 = _LowLevel.CKM_DSA_SHA384 CKM_DSA_SHA512 = _LowLevel.CKM_DSA_SHA512 CKM_DH_PKCS_KEY_PAIR_GEN = _LowLevel.CKM_DH_PKCS_KEY_PAIR_GEN CKM_DH_PKCS_DERIVE = _LowLevel.CKM_DH_PKCS_DERIVE CKM_X9_42_DH_KEY_PAIR_GEN = _LowLevel.CKM_X9_42_DH_KEY_PAIR_GEN CKM_X9_42_DH_DERIVE = _LowLevel.CKM_X9_42_DH_DERIVE CKM_X9_42_DH_HYBRID_DERIVE = _LowLevel.CKM_X9_42_DH_HYBRID_DERIVE CKM_X9_42_MQV_DERIVE = _LowLevel.CKM_X9_42_MQV_DERIVE CKM_SHA256_RSA_PKCS = _LowLevel.CKM_SHA256_RSA_PKCS CKM_SHA384_RSA_PKCS = _LowLevel.CKM_SHA384_RSA_PKCS CKM_SHA512_RSA_PKCS = _LowLevel.CKM_SHA512_RSA_PKCS CKM_SHA256_RSA_PKCS_PSS = _LowLevel.CKM_SHA256_RSA_PKCS_PSS CKM_SHA384_RSA_PKCS_PSS = _LowLevel.CKM_SHA384_RSA_PKCS_PSS CKM_SHA512_RSA_PKCS_PSS = _LowLevel.CKM_SHA512_RSA_PKCS_PSS CKM_SHA224_RSA_PKCS = _LowLevel.CKM_SHA224_RSA_PKCS CKM_SHA224_RSA_PKCS_PSS = _LowLevel.CKM_SHA224_RSA_PKCS_PSS CKM_SHA512_224 = _LowLevel.CKM_SHA512_224 CKM_SHA512_224_HMAC = _LowLevel.CKM_SHA512_224_HMAC CKM_SHA512_224_HMAC_GENERAL = _LowLevel.CKM_SHA512_224_HMAC_GENERAL CKM_SHA512_224_KEY_DERIVATION = _LowLevel.CKM_SHA512_224_KEY_DERIVATION CKM_SHA512_256 = _LowLevel.CKM_SHA512_256 CKM_SHA512_256_HMAC = _LowLevel.CKM_SHA512_256_HMAC CKM_SHA512_256_HMAC_GENERAL = _LowLevel.CKM_SHA512_256_HMAC_GENERAL CKM_SHA512_256_KEY_DERIVATION = _LowLevel.CKM_SHA512_256_KEY_DERIVATION CKM_SHA512_T = _LowLevel.CKM_SHA512_T CKM_SHA512_T_HMAC = _LowLevel.CKM_SHA512_T_HMAC CKM_SHA512_T_HMAC_GENERAL = _LowLevel.CKM_SHA512_T_HMAC_GENERAL CKM_SHA512_T_KEY_DERIVATION = _LowLevel.CKM_SHA512_T_KEY_DERIVATION CKM_RC2_KEY_GEN = _LowLevel.CKM_RC2_KEY_GEN CKM_RC2_ECB = _LowLevel.CKM_RC2_ECB CKM_RC2_CBC = _LowLevel.CKM_RC2_CBC CKM_RC2_MAC = _LowLevel.CKM_RC2_MAC CKM_RC2_MAC_GENERAL = _LowLevel.CKM_RC2_MAC_GENERAL CKM_RC2_CBC_PAD = _LowLevel.CKM_RC2_CBC_PAD CKM_RC4_KEY_GEN = _LowLevel.CKM_RC4_KEY_GEN CKM_RC4 = _LowLevel.CKM_RC4 CKM_DES_KEY_GEN = _LowLevel.CKM_DES_KEY_GEN CKM_DES_ECB = _LowLevel.CKM_DES_ECB CKM_DES_CBC = _LowLevel.CKM_DES_CBC CKM_DES_MAC = _LowLevel.CKM_DES_MAC CKM_DES_MAC_GENERAL = _LowLevel.CKM_DES_MAC_GENERAL CKM_DES_CBC_PAD = _LowLevel.CKM_DES_CBC_PAD CKM_DES2_KEY_GEN = _LowLevel.CKM_DES2_KEY_GEN CKM_DES3_KEY_GEN = _LowLevel.CKM_DES3_KEY_GEN CKM_DES3_ECB = _LowLevel.CKM_DES3_ECB CKM_DES3_CBC = _LowLevel.CKM_DES3_CBC CKM_DES3_MAC = _LowLevel.CKM_DES3_MAC CKM_DES3_MAC_GENERAL = _LowLevel.CKM_DES3_MAC_GENERAL CKM_DES3_CBC_PAD = _LowLevel.CKM_DES3_CBC_PAD CKM_DES3_CMAC_GENERAL = _LowLevel.CKM_DES3_CMAC_GENERAL CKM_DES3_CMAC = _LowLevel.CKM_DES3_CMAC CKM_CDMF_KEY_GEN = _LowLevel.CKM_CDMF_KEY_GEN CKM_CDMF_ECB = _LowLevel.CKM_CDMF_ECB CKM_CDMF_CBC = _LowLevel.CKM_CDMF_CBC CKM_CDMF_MAC = _LowLevel.CKM_CDMF_MAC CKM_CDMF_MAC_GENERAL = _LowLevel.CKM_CDMF_MAC_GENERAL CKM_CDMF_CBC_PAD = _LowLevel.CKM_CDMF_CBC_PAD CKM_DES_OFB64 = _LowLevel.CKM_DES_OFB64 CKM_DES_OFB8 = _LowLevel.CKM_DES_OFB8 CKM_DES_CFB64 = _LowLevel.CKM_DES_CFB64 CKM_DES_CFB8 = _LowLevel.CKM_DES_CFB8 CKM_MD2 = _LowLevel.CKM_MD2 CKM_MD2_HMAC = _LowLevel.CKM_MD2_HMAC CKM_MD2_HMAC_GENERAL = _LowLevel.CKM_MD2_HMAC_GENERAL CKM_MD5 = _LowLevel.CKM_MD5 CKM_MD5_HMAC = _LowLevel.CKM_MD5_HMAC CKM_MD5_HMAC_GENERAL = _LowLevel.CKM_MD5_HMAC_GENERAL CKM_SHA_1 = _LowLevel.CKM_SHA_1 CKM_SHA_1_HMAC = _LowLevel.CKM_SHA_1_HMAC CKM_SHA_1_HMAC_GENERAL = _LowLevel.CKM_SHA_1_HMAC_GENERAL CKM_RIPEMD128 = _LowLevel.CKM_RIPEMD128 CKM_RIPEMD128_HMAC = _LowLevel.CKM_RIPEMD128_HMAC CKM_RIPEMD128_HMAC_GENERAL = _LowLevel.CKM_RIPEMD128_HMAC_GENERAL CKM_RIPEMD160 = _LowLevel.CKM_RIPEMD160 CKM_RIPEMD160_HMAC = _LowLevel.CKM_RIPEMD160_HMAC CKM_RIPEMD160_HMAC_GENERAL = _LowLevel.CKM_RIPEMD160_HMAC_GENERAL CKM_SHA256 = _LowLevel.CKM_SHA256 CKM_SHA256_HMAC = _LowLevel.CKM_SHA256_HMAC CKM_SHA256_HMAC_GENERAL = _LowLevel.CKM_SHA256_HMAC_GENERAL CKM_SHA224 = _LowLevel.CKM_SHA224 CKM_SHA224_HMAC = _LowLevel.CKM_SHA224_HMAC CKM_SHA224_HMAC_GENERAL = _LowLevel.CKM_SHA224_HMAC_GENERAL CKM_SHA384 = _LowLevel.CKM_SHA384 CKM_SHA384_HMAC = _LowLevel.CKM_SHA384_HMAC CKM_SHA384_HMAC_GENERAL = _LowLevel.CKM_SHA384_HMAC_GENERAL CKM_SHA512 = _LowLevel.CKM_SHA512 CKM_SHA512_HMAC = _LowLevel.CKM_SHA512_HMAC CKM_SHA512_HMAC_GENERAL = _LowLevel.CKM_SHA512_HMAC_GENERAL CKM_SECURID_KEY_GEN = _LowLevel.CKM_SECURID_KEY_GEN CKM_SECURID = _LowLevel.CKM_SECURID CKM_HOTP_KEY_GEN = _LowLevel.CKM_HOTP_KEY_GEN CKM_HOTP = _LowLevel.CKM_HOTP CKM_ACTI = _LowLevel.CKM_ACTI CKM_ACTI_KEY_GEN = _LowLevel.CKM_ACTI_KEY_GEN CKM_CAST_KEY_GEN = _LowLevel.CKM_CAST_KEY_GEN CKM_CAST_ECB = _LowLevel.CKM_CAST_ECB CKM_CAST_CBC = _LowLevel.CKM_CAST_CBC CKM_CAST_MAC = _LowLevel.CKM_CAST_MAC CKM_CAST_MAC_GENERAL = _LowLevel.CKM_CAST_MAC_GENERAL CKM_CAST_CBC_PAD = _LowLevel.CKM_CAST_CBC_PAD CKM_CAST3_KEY_GEN = _LowLevel.CKM_CAST3_KEY_GEN CKM_CAST3_ECB = _LowLevel.CKM_CAST3_ECB CKM_CAST3_CBC = _LowLevel.CKM_CAST3_CBC CKM_CAST3_MAC = _LowLevel.CKM_CAST3_MAC CKM_CAST3_MAC_GENERAL = _LowLevel.CKM_CAST3_MAC_GENERAL CKM_CAST3_CBC_PAD = _LowLevel.CKM_CAST3_CBC_PAD CKM_CAST5_KEY_GEN = _LowLevel.CKM_CAST5_KEY_GEN CKM_CAST128_KEY_GEN = _LowLevel.CKM_CAST128_KEY_GEN CKM_CAST5_ECB = _LowLevel.CKM_CAST5_ECB CKM_CAST128_ECB = _LowLevel.CKM_CAST128_ECB CKM_CAST5_CBC = _LowLevel.CKM_CAST5_CBC CKM_CAST128_CBC = _LowLevel.CKM_CAST128_CBC CKM_CAST5_MAC = _LowLevel.CKM_CAST5_MAC CKM_CAST128_MAC = _LowLevel.CKM_CAST128_MAC CKM_CAST5_MAC_GENERAL = _LowLevel.CKM_CAST5_MAC_GENERAL CKM_CAST128_MAC_GENERAL = _LowLevel.CKM_CAST128_MAC_GENERAL CKM_CAST5_CBC_PAD = _LowLevel.CKM_CAST5_CBC_PAD CKM_CAST128_CBC_PAD = _LowLevel.CKM_CAST128_CBC_PAD CKM_RC5_KEY_GEN = _LowLevel.CKM_RC5_KEY_GEN CKM_RC5_ECB = _LowLevel.CKM_RC5_ECB CKM_RC5_CBC = _LowLevel.CKM_RC5_CBC CKM_RC5_MAC = _LowLevel.CKM_RC5_MAC CKM_RC5_MAC_GENERAL = _LowLevel.CKM_RC5_MAC_GENERAL CKM_RC5_CBC_PAD = _LowLevel.CKM_RC5_CBC_PAD CKM_IDEA_KEY_GEN = _LowLevel.CKM_IDEA_KEY_GEN CKM_IDEA_ECB = _LowLevel.CKM_IDEA_ECB CKM_IDEA_CBC = _LowLevel.CKM_IDEA_CBC CKM_IDEA_MAC = _LowLevel.CKM_IDEA_MAC CKM_IDEA_MAC_GENERAL = _LowLevel.CKM_IDEA_MAC_GENERAL CKM_IDEA_CBC_PAD = _LowLevel.CKM_IDEA_CBC_PAD CKM_GENERIC_SECRET_KEY_GEN = _LowLevel.CKM_GENERIC_SECRET_KEY_GEN CKM_CONCATENATE_BASE_AND_KEY = _LowLevel.CKM_CONCATENATE_BASE_AND_KEY CKM_CONCATENATE_BASE_AND_DATA = _LowLevel.CKM_CONCATENATE_BASE_AND_DATA CKM_CONCATENATE_DATA_AND_BASE = _LowLevel.CKM_CONCATENATE_DATA_AND_BASE CKM_XOR_BASE_AND_DATA = _LowLevel.CKM_XOR_BASE_AND_DATA CKM_EXTRACT_KEY_FROM_KEY = _LowLevel.CKM_EXTRACT_KEY_FROM_KEY CKM_SSL3_PRE_MASTER_KEY_GEN = _LowLevel.CKM_SSL3_PRE_MASTER_KEY_GEN CKM_SSL3_MASTER_KEY_DERIVE = _LowLevel.CKM_SSL3_MASTER_KEY_DERIVE CKM_SSL3_KEY_AND_MAC_DERIVE = _LowLevel.CKM_SSL3_KEY_AND_MAC_DERIVE CKM_SSL3_MASTER_KEY_DERIVE_DH = _LowLevel.CKM_SSL3_MASTER_KEY_DERIVE_DH CKM_TLS_PRE_MASTER_KEY_GEN = _LowLevel.CKM_TLS_PRE_MASTER_KEY_GEN CKM_TLS_MASTER_KEY_DERIVE = _LowLevel.CKM_TLS_MASTER_KEY_DERIVE CKM_TLS_KEY_AND_MAC_DERIVE = _LowLevel.CKM_TLS_KEY_AND_MAC_DERIVE CKM_TLS_MASTER_KEY_DERIVE_DH = _LowLevel.CKM_TLS_MASTER_KEY_DERIVE_DH CKM_TLS_PRF = _LowLevel.CKM_TLS_PRF CKM_SSL3_MD5_MAC = _LowLevel.CKM_SSL3_MD5_MAC CKM_SSL3_SHA1_MAC = _LowLevel.CKM_SSL3_SHA1_MAC CKM_MD5_KEY_DERIVATION = _LowLevel.CKM_MD5_KEY_DERIVATION CKM_MD2_KEY_DERIVATION = _LowLevel.CKM_MD2_KEY_DERIVATION CKM_SHA1_KEY_DERIVATION = _LowLevel.CKM_SHA1_KEY_DERIVATION CKM_SHA256_KEY_DERIVATION = _LowLevel.CKM_SHA256_KEY_DERIVATION CKM_SHA384_KEY_DERIVATION = _LowLevel.CKM_SHA384_KEY_DERIVATION CKM_SHA512_KEY_DERIVATION = _LowLevel.CKM_SHA512_KEY_DERIVATION CKM_SHA224_KEY_DERIVATION = _LowLevel.CKM_SHA224_KEY_DERIVATION CKM_PBE_MD2_DES_CBC = _LowLevel.CKM_PBE_MD2_DES_CBC CKM_PBE_MD5_DES_CBC = _LowLevel.CKM_PBE_MD5_DES_CBC CKM_PBE_MD5_CAST_CBC = _LowLevel.CKM_PBE_MD5_CAST_CBC CKM_PBE_MD5_CAST3_CBC = _LowLevel.CKM_PBE_MD5_CAST3_CBC CKM_PBE_MD5_CAST5_CBC = _LowLevel.CKM_PBE_MD5_CAST5_CBC CKM_PBE_MD5_CAST128_CBC = _LowLevel.CKM_PBE_MD5_CAST128_CBC CKM_PBE_SHA1_CAST5_CBC = _LowLevel.CKM_PBE_SHA1_CAST5_CBC CKM_PBE_SHA1_CAST128_CBC = _LowLevel.CKM_PBE_SHA1_CAST128_CBC CKM_PBE_SHA1_RC4_128 = _LowLevel.CKM_PBE_SHA1_RC4_128 CKM_PBE_SHA1_RC4_40 = _LowLevel.CKM_PBE_SHA1_RC4_40 CKM_PBE_SHA1_DES3_EDE_CBC = _LowLevel.CKM_PBE_SHA1_DES3_EDE_CBC CKM_PBE_SHA1_DES2_EDE_CBC = _LowLevel.CKM_PBE_SHA1_DES2_EDE_CBC CKM_PBE_SHA1_RC2_128_CBC = _LowLevel.CKM_PBE_SHA1_RC2_128_CBC CKM_PBE_SHA1_RC2_40_CBC = _LowLevel.CKM_PBE_SHA1_RC2_40_CBC CKM_PKCS5_PBKD2 = _LowLevel.CKM_PKCS5_PBKD2 CKM_PBA_SHA1_WITH_SHA1_HMAC = _LowLevel.CKM_PBA_SHA1_WITH_SHA1_HMAC CKM_WTLS_PRE_MASTER_KEY_GEN = _LowLevel.CKM_WTLS_PRE_MASTER_KEY_GEN CKM_WTLS_MASTER_KEY_DERIVE = _LowLevel.CKM_WTLS_MASTER_KEY_DERIVE CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC = _LowLevel.CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC CKM_WTLS_PRF = _LowLevel.CKM_WTLS_PRF CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE = _LowLevel.CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE = _LowLevel.CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE CKM_TLS10_MAC_SERVER = _LowLevel.CKM_TLS10_MAC_SERVER CKM_TLS10_MAC_CLIENT = _LowLevel.CKM_TLS10_MAC_CLIENT CKM_TLS12_MAC = _LowLevel.CKM_TLS12_MAC CKM_TLS12_KDF = _LowLevel.CKM_TLS12_KDF CKM_TLS12_MASTER_KEY_DERIVE = _LowLevel.CKM_TLS12_MASTER_KEY_DERIVE CKM_TLS12_KEY_AND_MAC_DERIVE = _LowLevel.CKM_TLS12_KEY_AND_MAC_DERIVE CKM_TLS12_MASTER_KEY_DERIVE_DH = _LowLevel.CKM_TLS12_MASTER_KEY_DERIVE_DH CKM_TLS12_KEY_SAFE_DERIVE = _LowLevel.CKM_TLS12_KEY_SAFE_DERIVE CKM_TLS_MAC = _LowLevel.CKM_TLS_MAC CKM_TLS_KDF = _LowLevel.CKM_TLS_KDF CKM_KEY_WRAP_LYNKS = _LowLevel.CKM_KEY_WRAP_LYNKS CKM_KEY_WRAP_SET_OAEP = _LowLevel.CKM_KEY_WRAP_SET_OAEP CKM_CMS_SIG = _LowLevel.CKM_CMS_SIG CKM_KIP_DERIVE = _LowLevel.CKM_KIP_DERIVE CKM_KIP_WRAP = _LowLevel.CKM_KIP_WRAP CKM_KIP_MAC = _LowLevel.CKM_KIP_MAC CKM_CAMELLIA_KEY_GEN = _LowLevel.CKM_CAMELLIA_KEY_GEN CKM_CAMELLIA_ECB = _LowLevel.CKM_CAMELLIA_ECB CKM_CAMELLIA_CBC = _LowLevel.CKM_CAMELLIA_CBC CKM_CAMELLIA_MAC = _LowLevel.CKM_CAMELLIA_MAC CKM_CAMELLIA_MAC_GENERAL = _LowLevel.CKM_CAMELLIA_MAC_GENERAL CKM_CAMELLIA_CBC_PAD = _LowLevel.CKM_CAMELLIA_CBC_PAD CKM_CAMELLIA_ECB_ENCRYPT_DATA = _LowLevel.CKM_CAMELLIA_ECB_ENCRYPT_DATA CKM_CAMELLIA_CBC_ENCRYPT_DATA = _LowLevel.CKM_CAMELLIA_CBC_ENCRYPT_DATA CKM_CAMELLIA_CTR = _LowLevel.CKM_CAMELLIA_CTR CKM_ARIA_KEY_GEN = _LowLevel.CKM_ARIA_KEY_GEN CKM_ARIA_ECB = _LowLevel.CKM_ARIA_ECB CKM_ARIA_CBC = _LowLevel.CKM_ARIA_CBC CKM_ARIA_MAC = _LowLevel.CKM_ARIA_MAC CKM_ARIA_MAC_GENERAL = _LowLevel.CKM_ARIA_MAC_GENERAL CKM_ARIA_CBC_PAD = _LowLevel.CKM_ARIA_CBC_PAD CKM_ARIA_ECB_ENCRYPT_DATA = _LowLevel.CKM_ARIA_ECB_ENCRYPT_DATA CKM_ARIA_CBC_ENCRYPT_DATA = _LowLevel.CKM_ARIA_CBC_ENCRYPT_DATA CKM_SEED_KEY_GEN = _LowLevel.CKM_SEED_KEY_GEN CKM_SEED_ECB = _LowLevel.CKM_SEED_ECB CKM_SEED_CBC = _LowLevel.CKM_SEED_CBC CKM_SEED_MAC = _LowLevel.CKM_SEED_MAC CKM_SEED_MAC_GENERAL = _LowLevel.CKM_SEED_MAC_GENERAL CKM_SEED_CBC_PAD = _LowLevel.CKM_SEED_CBC_PAD CKM_SEED_ECB_ENCRYPT_DATA = _LowLevel.CKM_SEED_ECB_ENCRYPT_DATA CKM_SEED_CBC_ENCRYPT_DATA = _LowLevel.CKM_SEED_CBC_ENCRYPT_DATA CKM_SKIPJACK_KEY_GEN = _LowLevel.CKM_SKIPJACK_KEY_GEN CKM_SKIPJACK_ECB64 = _LowLevel.CKM_SKIPJACK_ECB64 CKM_SKIPJACK_CBC64 = _LowLevel.CKM_SKIPJACK_CBC64 CKM_SKIPJACK_OFB64 = _LowLevel.CKM_SKIPJACK_OFB64 CKM_SKIPJACK_CFB64 = _LowLevel.CKM_SKIPJACK_CFB64 CKM_SKIPJACK_CFB32 = _LowLevel.CKM_SKIPJACK_CFB32 CKM_SKIPJACK_CFB16 = _LowLevel.CKM_SKIPJACK_CFB16 CKM_SKIPJACK_CFB8 = _LowLevel.CKM_SKIPJACK_CFB8 CKM_SKIPJACK_WRAP = _LowLevel.CKM_SKIPJACK_WRAP CKM_SKIPJACK_PRIVATE_WRAP = _LowLevel.CKM_SKIPJACK_PRIVATE_WRAP CKM_SKIPJACK_RELAYX = _LowLevel.CKM_SKIPJACK_RELAYX CKM_KEA_KEY_PAIR_GEN = _LowLevel.CKM_KEA_KEY_PAIR_GEN CKM_KEA_KEY_DERIVE = _LowLevel.CKM_KEA_KEY_DERIVE CKM_KEA_DERIVE = _LowLevel.CKM_KEA_DERIVE CKM_FORTEZZA_TIMESTAMP = _LowLevel.CKM_FORTEZZA_TIMESTAMP CKM_BATON_KEY_GEN = _LowLevel.CKM_BATON_KEY_GEN CKM_BATON_ECB128 = _LowLevel.CKM_BATON_ECB128 CKM_BATON_ECB96 = _LowLevel.CKM_BATON_ECB96 CKM_BATON_CBC128 = _LowLevel.CKM_BATON_CBC128 CKM_BATON_COUNTER = _LowLevel.CKM_BATON_COUNTER CKM_BATON_SHUFFLE = _LowLevel.CKM_BATON_SHUFFLE CKM_BATON_WRAP = _LowLevel.CKM_BATON_WRAP CKM_ECDSA_KEY_PAIR_GEN = _LowLevel.CKM_ECDSA_KEY_PAIR_GEN CKM_EC_KEY_PAIR_GEN = _LowLevel.CKM_EC_KEY_PAIR_GEN CKM_ECDSA = _LowLevel.CKM_ECDSA CKM_ECDSA_SHA1 = _LowLevel.CKM_ECDSA_SHA1 CKM_ECDSA_SHA224 = _LowLevel.CKM_ECDSA_SHA224 CKM_ECDSA_SHA256 = _LowLevel.CKM_ECDSA_SHA256 CKM_ECDSA_SHA384 = _LowLevel.CKM_ECDSA_SHA384 CKM_ECDSA_SHA512 = _LowLevel.CKM_ECDSA_SHA512 CKM_ECDH1_DERIVE = _LowLevel.CKM_ECDH1_DERIVE CKM_ECDH1_COFACTOR_DERIVE = _LowLevel.CKM_ECDH1_COFACTOR_DERIVE CKM_ECMQV_DERIVE = _LowLevel.CKM_ECMQV_DERIVE CKM_ECDH_AES_KEY_WRAP = _LowLevel.CKM_ECDH_AES_KEY_WRAP CKM_RSA_AES_KEY_WRAP = _LowLevel.CKM_RSA_AES_KEY_WRAP CKM_JUNIPER_KEY_GEN = _LowLevel.CKM_JUNIPER_KEY_GEN CKM_JUNIPER_ECB128 = _LowLevel.CKM_JUNIPER_ECB128 CKM_JUNIPER_CBC128 = _LowLevel.CKM_JUNIPER_CBC128 CKM_JUNIPER_COUNTER = _LowLevel.CKM_JUNIPER_COUNTER CKM_JUNIPER_SHUFFLE = _LowLevel.CKM_JUNIPER_SHUFFLE CKM_JUNIPER_WRAP = _LowLevel.CKM_JUNIPER_WRAP CKM_FASTHASH = _LowLevel.CKM_FASTHASH CKM_AES_KEY_GEN = _LowLevel.CKM_AES_KEY_GEN CKM_AES_ECB = _LowLevel.CKM_AES_ECB CKM_AES_CBC = _LowLevel.CKM_AES_CBC CKM_AES_MAC = _LowLevel.CKM_AES_MAC CKM_AES_MAC_GENERAL = _LowLevel.CKM_AES_MAC_GENERAL CKM_AES_CBC_PAD = _LowLevel.CKM_AES_CBC_PAD CKM_AES_CTR = _LowLevel.CKM_AES_CTR CKM_AES_GCM = _LowLevel.CKM_AES_GCM CKM_AES_CCM = _LowLevel.CKM_AES_CCM CKM_AES_CTS = _LowLevel.CKM_AES_CTS CKM_AES_CMAC = _LowLevel.CKM_AES_CMAC CKM_AES_CMAC_GENERAL = _LowLevel.CKM_AES_CMAC_GENERAL CKM_AES_XCBC_MAC = _LowLevel.CKM_AES_XCBC_MAC CKM_AES_XCBC_MAC_96 = _LowLevel.CKM_AES_XCBC_MAC_96 CKM_AES_GMAC = _LowLevel.CKM_AES_GMAC CKM_BLOWFISH_KEY_GEN = _LowLevel.CKM_BLOWFISH_KEY_GEN CKM_BLOWFISH_CBC = _LowLevel.CKM_BLOWFISH_CBC CKM_TWOFISH_KEY_GEN = _LowLevel.CKM_TWOFISH_KEY_GEN CKM_TWOFISH_CBC = _LowLevel.CKM_TWOFISH_CBC CKM_BLOWFISH_CBC_PAD = _LowLevel.CKM_BLOWFISH_CBC_PAD CKM_TWOFISH_CBC_PAD = _LowLevel.CKM_TWOFISH_CBC_PAD CKM_DES_ECB_ENCRYPT_DATA = _LowLevel.CKM_DES_ECB_ENCRYPT_DATA CKM_DES_CBC_ENCRYPT_DATA = _LowLevel.CKM_DES_CBC_ENCRYPT_DATA CKM_DES3_ECB_ENCRYPT_DATA = _LowLevel.CKM_DES3_ECB_ENCRYPT_DATA CKM_DES3_CBC_ENCRYPT_DATA = _LowLevel.CKM_DES3_CBC_ENCRYPT_DATA CKM_AES_ECB_ENCRYPT_DATA = _LowLevel.CKM_AES_ECB_ENCRYPT_DATA CKM_AES_CBC_ENCRYPT_DATA = _LowLevel.CKM_AES_CBC_ENCRYPT_DATA CKM_GOSTR3410_KEY_PAIR_GEN = _LowLevel.CKM_GOSTR3410_KEY_PAIR_GEN CKM_GOSTR3410 = _LowLevel.CKM_GOSTR3410 CKM_GOSTR3410_WITH_GOSTR3411 = _LowLevel.CKM_GOSTR3410_WITH_GOSTR3411 CKM_GOSTR3410_KEY_WRAP = _LowLevel.CKM_GOSTR3410_KEY_WRAP CKM_GOSTR3410_DERIVE = _LowLevel.CKM_GOSTR3410_DERIVE CKM_GOSTR3411 = _LowLevel.CKM_GOSTR3411 CKM_GOSTR3411_HMAC = _LowLevel.CKM_GOSTR3411_HMAC CKM_GOST28147_KEY_GEN = _LowLevel.CKM_GOST28147_KEY_GEN CKM_GOST28147_ECB = _LowLevel.CKM_GOST28147_ECB CKM_GOST28147 = _LowLevel.CKM_GOST28147 CKM_GOST28147_MAC = _LowLevel.CKM_GOST28147_MAC CKM_GOST28147_KEY_WRAP = _LowLevel.CKM_GOST28147_KEY_WRAP CKM_DSA_PARAMETER_GEN = _LowLevel.CKM_DSA_PARAMETER_GEN CKM_DH_PKCS_PARAMETER_GEN = _LowLevel.CKM_DH_PKCS_PARAMETER_GEN CKM_X9_42_DH_PARAMETER_GEN = _LowLevel.CKM_X9_42_DH_PARAMETER_GEN CKM_DSA_PROBABLISTIC_PARAMETER_GEN = _LowLevel.CKM_DSA_PROBABLISTIC_PARAMETER_GEN CKM_DSA_SHAWE_TAYLOR_PARAMETER_GEN = _LowLevel.CKM_DSA_SHAWE_TAYLOR_PARAMETER_GEN CKM_AES_OFB = _LowLevel.CKM_AES_OFB CKM_AES_CFB64 = _LowLevel.CKM_AES_CFB64 CKM_AES_CFB8 = _LowLevel.CKM_AES_CFB8 CKM_AES_CFB128 = _LowLevel.CKM_AES_CFB128 CKM_AES_CFB1 = _LowLevel.CKM_AES_CFB1 CKM_AES_KEY_WRAP = _LowLevel.CKM_AES_KEY_WRAP CKM_AES_KEY_WRAP_PAD = _LowLevel.CKM_AES_KEY_WRAP_PAD CKM_RSA_PKCS_TPM_1_1 = _LowLevel.CKM_RSA_PKCS_TPM_1_1 CKM_RSA_PKCS_OAEP_TPM_1_1 = _LowLevel.CKM_RSA_PKCS_OAEP_TPM_1_1 CKM_VENDOR_DEFINED = _LowLevel.CKM_VENDOR_DEFINED CKG_MGF1_SHA1 = _LowLevel.CKG_MGF1_SHA1 CKG_MGF1_SHA256 = _LowLevel.CKG_MGF1_SHA256 CKG_MGF1_SHA384 = _LowLevel.CKG_MGF1_SHA384 CKG_MGF1_SHA512 = _LowLevel.CKG_MGF1_SHA512 CKF_HW = _LowLevel.CKF_HW CKF_ENCRYPT = _LowLevel.CKF_ENCRYPT CKF_DECRYPT = _LowLevel.CKF_DECRYPT CKF_DIGEST = _LowLevel.CKF_DIGEST CKF_SIGN = _LowLevel.CKF_SIGN CKF_SIGN_RECOVER = _LowLevel.CKF_SIGN_RECOVER CKF_VERIFY = _LowLevel.CKF_VERIFY CKF_VERIFY_RECOVER = _LowLevel.CKF_VERIFY_RECOVER CKF_GENERATE = _LowLevel.CKF_GENERATE CKF_GENERATE_KEY_PAIR = _LowLevel.CKF_GENERATE_KEY_PAIR CKF_WRAP = _LowLevel.CKF_WRAP CKF_UNWRAP = _LowLevel.CKF_UNWRAP CKF_DERIVE = _LowLevel.CKF_DERIVE CKF_EC_F_P = _LowLevel.CKF_EC_F_P CKF_EC_F_2M = _LowLevel.CKF_EC_F_2M CKF_EC_ECPARAMETERS = _LowLevel.CKF_EC_ECPARAMETERS CKF_EC_NAMEDCURVE = _LowLevel.CKF_EC_NAMEDCURVE CKF_EC_UNCOMPRESS = _LowLevel.CKF_EC_UNCOMPRESS CKF_EC_COMPRESS = _LowLevel.CKF_EC_COMPRESS CKF_EXTENSION = _LowLevel.CKF_EXTENSION CKR_OK = _LowLevel.CKR_OK CKR_CANCEL = _LowLevel.CKR_CANCEL CKR_HOST_MEMORY = _LowLevel.CKR_HOST_MEMORY CKR_SLOT_ID_INVALID = _LowLevel.CKR_SLOT_ID_INVALID CKR_GENERAL_ERROR = _LowLevel.CKR_GENERAL_ERROR CKR_FUNCTION_FAILED = _LowLevel.CKR_FUNCTION_FAILED CKR_ARGUMENTS_BAD = _LowLevel.CKR_ARGUMENTS_BAD CKR_NO_EVENT = _LowLevel.CKR_NO_EVENT CKR_NEED_TO_CREATE_THREADS = _LowLevel.CKR_NEED_TO_CREATE_THREADS CKR_CANT_LOCK = _LowLevel.CKR_CANT_LOCK CKR_ATTRIBUTE_READ_ONLY = _LowLevel.CKR_ATTRIBUTE_READ_ONLY CKR_ATTRIBUTE_SENSITIVE = _LowLevel.CKR_ATTRIBUTE_SENSITIVE CKR_ATTRIBUTE_TYPE_INVALID = _LowLevel.CKR_ATTRIBUTE_TYPE_INVALID CKR_ATTRIBUTE_VALUE_INVALID = _LowLevel.CKR_ATTRIBUTE_VALUE_INVALID CKR_DATA_INVALID = _LowLevel.CKR_DATA_INVALID CKR_DATA_LEN_RANGE = _LowLevel.CKR_DATA_LEN_RANGE CKR_DEVICE_ERROR = _LowLevel.CKR_DEVICE_ERROR CKR_DEVICE_MEMORY = _LowLevel.CKR_DEVICE_MEMORY CKR_DEVICE_REMOVED = _LowLevel.CKR_DEVICE_REMOVED CKR_ENCRYPTED_DATA_INVALID = _LowLevel.CKR_ENCRYPTED_DATA_INVALID CKR_ENCRYPTED_DATA_LEN_RANGE = _LowLevel.CKR_ENCRYPTED_DATA_LEN_RANGE CKR_FUNCTION_CANCELED = _LowLevel.CKR_FUNCTION_CANCELED CKR_FUNCTION_NOT_PARALLEL = _LowLevel.CKR_FUNCTION_NOT_PARALLEL CKR_FUNCTION_NOT_SUPPORTED = _LowLevel.CKR_FUNCTION_NOT_SUPPORTED CKR_KEY_HANDLE_INVALID = _LowLevel.CKR_KEY_HANDLE_INVALID CKR_KEY_SIZE_RANGE = _LowLevel.CKR_KEY_SIZE_RANGE CKR_KEY_TYPE_INCONSISTENT = _LowLevel.CKR_KEY_TYPE_INCONSISTENT CKR_KEY_NOT_NEEDED = _LowLevel.CKR_KEY_NOT_NEEDED CKR_KEY_CHANGED = _LowLevel.CKR_KEY_CHANGED CKR_KEY_NEEDED = _LowLevel.CKR_KEY_NEEDED CKR_KEY_INDIGESTIBLE = _LowLevel.CKR_KEY_INDIGESTIBLE CKR_KEY_FUNCTION_NOT_PERMITTED = _LowLevel.CKR_KEY_FUNCTION_NOT_PERMITTED CKR_KEY_NOT_WRAPPABLE = _LowLevel.CKR_KEY_NOT_WRAPPABLE CKR_KEY_UNEXTRACTABLE = _LowLevel.CKR_KEY_UNEXTRACTABLE CKR_MECHANISM_INVALID = _LowLevel.CKR_MECHANISM_INVALID CKR_MECHANISM_PARAM_INVALID = _LowLevel.CKR_MECHANISM_PARAM_INVALID CKR_OBJECT_HANDLE_INVALID = _LowLevel.CKR_OBJECT_HANDLE_INVALID CKR_OPERATION_ACTIVE = _LowLevel.CKR_OPERATION_ACTIVE CKR_OPERATION_NOT_INITIALIZED = _LowLevel.CKR_OPERATION_NOT_INITIALIZED CKR_PIN_INCORRECT = _LowLevel.CKR_PIN_INCORRECT CKR_PIN_INVALID = _LowLevel.CKR_PIN_INVALID CKR_PIN_LEN_RANGE = _LowLevel.CKR_PIN_LEN_RANGE CKR_PIN_EXPIRED = _LowLevel.CKR_PIN_EXPIRED CKR_PIN_LOCKED = _LowLevel.CKR_PIN_LOCKED CKR_SESSION_CLOSED = _LowLevel.CKR_SESSION_CLOSED CKR_SESSION_COUNT = _LowLevel.CKR_SESSION_COUNT CKR_SESSION_HANDLE_INVALID = _LowLevel.CKR_SESSION_HANDLE_INVALID CKR_SESSION_PARALLEL_NOT_SUPPORTED = _LowLevel.CKR_SESSION_PARALLEL_NOT_SUPPORTED CKR_SESSION_READ_ONLY = _LowLevel.CKR_SESSION_READ_ONLY CKR_SESSION_EXISTS = _LowLevel.CKR_SESSION_EXISTS CKR_SESSION_READ_ONLY_EXISTS = _LowLevel.CKR_SESSION_READ_ONLY_EXISTS CKR_SESSION_READ_WRITE_SO_EXISTS = _LowLevel.CKR_SESSION_READ_WRITE_SO_EXISTS CKR_SIGNATURE_INVALID = _LowLevel.CKR_SIGNATURE_INVALID CKR_SIGNATURE_LEN_RANGE = _LowLevel.CKR_SIGNATURE_LEN_RANGE CKR_TEMPLATE_INCOMPLETE = _LowLevel.CKR_TEMPLATE_INCOMPLETE CKR_TEMPLATE_INCONSISTENT = _LowLevel.CKR_TEMPLATE_INCONSISTENT CKR_TOKEN_NOT_PRESENT = _LowLevel.CKR_TOKEN_NOT_PRESENT CKR_TOKEN_NOT_RECOGNIZED = _LowLevel.CKR_TOKEN_NOT_RECOGNIZED CKR_TOKEN_WRITE_PROTECTED = _LowLevel.CKR_TOKEN_WRITE_PROTECTED CKR_UNWRAPPING_KEY_HANDLE_INVALID = _LowLevel.CKR_UNWRAPPING_KEY_HANDLE_INVALID CKR_UNWRAPPING_KEY_SIZE_RANGE = _LowLevel.CKR_UNWRAPPING_KEY_SIZE_RANGE CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT = _LowLevel.CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT CKR_USER_ALREADY_LOGGED_IN = _LowLevel.CKR_USER_ALREADY_LOGGED_IN CKR_USER_NOT_LOGGED_IN = _LowLevel.CKR_USER_NOT_LOGGED_IN CKR_USER_PIN_NOT_INITIALIZED = _LowLevel.CKR_USER_PIN_NOT_INITIALIZED CKR_USER_TYPE_INVALID = _LowLevel.CKR_USER_TYPE_INVALID CKR_USER_ANOTHER_ALREADY_LOGGED_IN = _LowLevel.CKR_USER_ANOTHER_ALREADY_LOGGED_IN CKR_USER_TOO_MANY_TYPES = _LowLevel.CKR_USER_TOO_MANY_TYPES CKR_WRAPPED_KEY_INVALID = _LowLevel.CKR_WRAPPED_KEY_INVALID CKR_WRAPPED_KEY_LEN_RANGE = _LowLevel.CKR_WRAPPED_KEY_LEN_RANGE CKR_WRAPPING_KEY_HANDLE_INVALID = _LowLevel.CKR_WRAPPING_KEY_HANDLE_INVALID CKR_WRAPPING_KEY_SIZE_RANGE = _LowLevel.CKR_WRAPPING_KEY_SIZE_RANGE CKR_WRAPPING_KEY_TYPE_INCONSISTENT = _LowLevel.CKR_WRAPPING_KEY_TYPE_INCONSISTENT CKR_RANDOM_SEED_NOT_SUPPORTED = _LowLevel.CKR_RANDOM_SEED_NOT_SUPPORTED CKR_RANDOM_NO_RNG = _LowLevel.CKR_RANDOM_NO_RNG CKR_DOMAIN_PARAMS_INVALID = _LowLevel.CKR_DOMAIN_PARAMS_INVALID CKR_BUFFER_TOO_SMALL = _LowLevel.CKR_BUFFER_TOO_SMALL CKR_SAVED_STATE_INVALID = _LowLevel.CKR_SAVED_STATE_INVALID CKR_INFORMATION_SENSITIVE = _LowLevel.CKR_INFORMATION_SENSITIVE CKR_STATE_UNSAVEABLE = _LowLevel.CKR_STATE_UNSAVEABLE CKR_CRYPTOKI_NOT_INITIALIZED = _LowLevel.CKR_CRYPTOKI_NOT_INITIALIZED CKR_CRYPTOKI_ALREADY_INITIALIZED = _LowLevel.CKR_CRYPTOKI_ALREADY_INITIALIZED CKR_MUTEX_BAD = _LowLevel.CKR_MUTEX_BAD CKR_MUTEX_NOT_LOCKED = _LowLevel.CKR_MUTEX_NOT_LOCKED CKR_NEW_PIN_MODE = _LowLevel.CKR_NEW_PIN_MODE CKR_NEXT_OTP = _LowLevel.CKR_NEXT_OTP CKR_FUNCTION_REJECTED = _LowLevel.CKR_FUNCTION_REJECTED CKR_VENDOR_DEFINED = _LowLevel.CKR_VENDOR_DEFINED CKF_LIBRARY_CANT_CREATE_OS_THREADS = _LowLevel.CKF_LIBRARY_CANT_CREATE_OS_THREADS CKF_OS_LOCKING_OK = _LowLevel.CKF_OS_LOCKING_OK CKF_DONT_BLOCK = _LowLevel.CKF_DONT_BLOCK CKG_MGF1_SHA224 = _LowLevel.CKG_MGF1_SHA224 CKZ_DATA_SPECIFIED = _LowLevel.CKZ_DATA_SPECIFIED CKD_NULL = _LowLevel.CKD_NULL CKD_SHA1_KDF = _LowLevel.CKD_SHA1_KDF CKD_SHA1_KDF_ASN1 = _LowLevel.CKD_SHA1_KDF_ASN1 CKD_SHA1_KDF_CONCATENATE = _LowLevel.CKD_SHA1_KDF_CONCATENATE CKD_SHA224_KDF = _LowLevel.CKD_SHA224_KDF CKD_SHA256_KDF = _LowLevel.CKD_SHA256_KDF CKD_SHA384_KDF = _LowLevel.CKD_SHA384_KDF CKD_SHA512_KDF = _LowLevel.CKD_SHA512_KDF CKD_CPDIVERSIFY_KDF = _LowLevel.CKD_CPDIVERSIFY_KDF CKP_PKCS5_PBKD2_HMAC_SHA1 = _LowLevel.CKP_PKCS5_PBKD2_HMAC_SHA1 CKP_PKCS5_PBKD2_HMAC_GOSTR3411 = _LowLevel.CKP_PKCS5_PBKD2_HMAC_GOSTR3411 CKP_PKCS5_PBKD2_HMAC_SHA224 = _LowLevel.CKP_PKCS5_PBKD2_HMAC_SHA224 CKP_PKCS5_PBKD2_HMAC_SHA256 = _LowLevel.CKP_PKCS5_PBKD2_HMAC_SHA256 CKP_PKCS5_PBKD2_HMAC_SHA384 = _LowLevel.CKP_PKCS5_PBKD2_HMAC_SHA384 CKP_PKCS5_PBKD2_HMAC_SHA512 = _LowLevel.CKP_PKCS5_PBKD2_HMAC_SHA512 CKP_PKCS5_PBKD2_HMAC_SHA512_224 = _LowLevel.CKP_PKCS5_PBKD2_HMAC_SHA512_224 CKP_PKCS5_PBKD2_HMAC_SHA512_256 = _LowLevel.CKP_PKCS5_PBKD2_HMAC_SHA512_256 CKZ_SALT_SPECIFIED = _LowLevel.CKZ_SALT_SPECIFIED class CPKCS11Lib(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self): _LowLevel.CPKCS11Lib_swiginit(self, _LowLevel.new_CPKCS11Lib()) __swig_destroy__ = _LowLevel.delete_CPKCS11Lib def Load(self, szLib): return _LowLevel.CPKCS11Lib_Load(self, szLib) def Unload(self): return _LowLevel.CPKCS11Lib_Unload(self) def C_Initialize(self): return _LowLevel.CPKCS11Lib_C_Initialize(self) def C_Finalize(self): return _LowLevel.CPKCS11Lib_C_Finalize(self) def C_GetInfo(self, pInfo): return _LowLevel.CPKCS11Lib_C_GetInfo(self, pInfo) def C_GetSlotList(self, tokenPresent, slotList): return _LowLevel.CPKCS11Lib_C_GetSlotList(self, tokenPresent, slotList) def C_GetSlotInfo(self, slotID, pInfo): return _LowLevel.CPKCS11Lib_C_GetSlotInfo(self, slotID, pInfo) def C_GetTokenInfo(self, slotID, pInfo): return _LowLevel.CPKCS11Lib_C_GetTokenInfo(self, slotID, pInfo) def C_InitToken(self, slotID, pin, pLabel): return _LowLevel.CPKCS11Lib_C_InitToken(self, slotID, pin, pLabel) def C_InitPIN(self, hSession, pin): return _LowLevel.CPKCS11Lib_C_InitPIN(self, hSession, pin) def C_SetPIN(self, hSession, OldPin, NewPin): return _LowLevel.CPKCS11Lib_C_SetPIN(self, hSession, OldPin, NewPin) def C_OpenSession(self, slotID, flags, outhSession): return _LowLevel.CPKCS11Lib_C_OpenSession(self, slotID, flags, outhSession) def C_CloseSession(self, hSession): return _LowLevel.CPKCS11Lib_C_CloseSession(self, hSession) def C_CloseAllSessions(self, slotID): return _LowLevel.CPKCS11Lib_C_CloseAllSessions(self, slotID) def C_GetSessionInfo(self, hSession, pInfo): return _LowLevel.CPKCS11Lib_C_GetSessionInfo(self, hSession, pInfo) def C_Login(self, hSession, userType, pin): return _LowLevel.CPKCS11Lib_C_Login(self, hSession, userType, pin) def C_Logout(self, hSession): return _LowLevel.CPKCS11Lib_C_Logout(self, hSession) def C_CreateObject(self, hSession, Template, outhObject): return _LowLevel.CPKCS11Lib_C_CreateObject(self, hSession, Template, outhObject) def C_DestroyObject(self, hSession, hObject): return _LowLevel.CPKCS11Lib_C_DestroyObject(self, hSession, hObject) def C_GetObjectSize(self, hSession, hObject, pulSize): return _LowLevel.CPKCS11Lib_C_GetObjectSize(self, hSession, hObject, pulSize) def C_GetAttributeValue(self, hSession, hObject, Template): return _LowLevel.CPKCS11Lib_C_GetAttributeValue(self, hSession, hObject, Template) def C_SetAttributeValue(self, hSession, hObject, Template): return _LowLevel.CPKCS11Lib_C_SetAttributeValue(self, hSession, hObject, Template) def C_FindObjectsInit(self, hSession, Template): return _LowLevel.CPKCS11Lib_C_FindObjectsInit(self, hSession, Template) def C_FindObjects(self, hSession, objectsList): return _LowLevel.CPKCS11Lib_C_FindObjects(self, hSession, objectsList) def C_FindObjectsFinal(self, hSession): return _LowLevel.CPKCS11Lib_C_FindObjectsFinal(self, hSession) def C_EncryptInit(self, hSession, pMechanism, hKey): return _LowLevel.CPKCS11Lib_C_EncryptInit(self, hSession, pMechanism, hKey) def C_Encrypt(self, hSession, inData, outEncryptedData): return _LowLevel.CPKCS11Lib_C_Encrypt(self, hSession, inData, outEncryptedData) def C_EncryptUpdate(self, hSession, inData, outEncryptedData): return _LowLevel.CPKCS11Lib_C_EncryptUpdate(self, hSession, inData, outEncryptedData) def C_EncryptFinal(self, hSession, outEncryptedData): return _LowLevel.CPKCS11Lib_C_EncryptFinal(self, hSession, outEncryptedData) def C_DecryptInit(self, hSession, pMechanism, hKey): return _LowLevel.CPKCS11Lib_C_DecryptInit(self, hSession, pMechanism, hKey) def C_Decrypt(self, hSession, inEncryptedData, outData): return _LowLevel.CPKCS11Lib_C_Decrypt(self, hSession, inEncryptedData, outData) def C_DecryptUpdate(self, hSession, inEncryptedData, outData): return _LowLevel.CPKCS11Lib_C_DecryptUpdate(self, hSession, inEncryptedData, outData) def C_DecryptFinal(self, hSession, outData): return _LowLevel.CPKCS11Lib_C_DecryptFinal(self, hSession, outData) def C_DigestInit(self, hSession, pMechanism): return _LowLevel.CPKCS11Lib_C_DigestInit(self, hSession, pMechanism) def C_Digest(self, hSession, inData, outDigest): return _LowLevel.CPKCS11Lib_C_Digest(self, hSession, inData, outDigest) def C_DigestUpdate(self, hSession, inData): return _LowLevel.CPKCS11Lib_C_DigestUpdate(self, hSession, inData) def C_DigestKey(self, hSession, hKey): return _LowLevel.CPKCS11Lib_C_DigestKey(self, hSession, hKey) def C_DigestFinal(self, hSession, outDigest): return _LowLevel.CPKCS11Lib_C_DigestFinal(self, hSession, outDigest) def C_SignInit(self, hSession, pMechanism, hKey): return _LowLevel.CPKCS11Lib_C_SignInit(self, hSession, pMechanism, hKey) def C_Sign(self, hSession, inData, outSignature): return _LowLevel.CPKCS11Lib_C_Sign(self, hSession, inData, outSignature) def C_SignUpdate(self, hSession, inData): return _LowLevel.CPKCS11Lib_C_SignUpdate(self, hSession, inData) def C_SignFinal(self, hSession, outSignature): return _LowLevel.CPKCS11Lib_C_SignFinal(self, hSession, outSignature) def C_VerifyInit(self, hSession, pMechanism, hKey): return _LowLevel.CPKCS11Lib_C_VerifyInit(self, hSession, pMechanism, hKey) def C_Verify(self, hSession, inData, inSignature): return _LowLevel.CPKCS11Lib_C_Verify(self, hSession, inData, inSignature) def C_VerifyUpdate(self, hSession, inData): return _LowLevel.CPKCS11Lib_C_VerifyUpdate(self, hSession, inData) def C_VerifyFinal(self, hSession, inSignature): return _LowLevel.CPKCS11Lib_C_VerifyFinal(self, hSession, inSignature) def C_GenerateKey(self, hSession, pMechanism, Template, outhKey): return _LowLevel.CPKCS11Lib_C_GenerateKey(self, hSession, pMechanism, Template, outhKey) def C_GenerateKeyPair(self, hSession, pMechanism, PublicKeyTemplate, PrivateKeyTemplate, outhPublicKey, outhPrivateKey): return _LowLevel.CPKCS11Lib_C_GenerateKeyPair(self, hSession, pMechanism, PublicKeyTemplate, PrivateKeyTemplate, outhPublicKey, outhPrivateKey) def C_WrapKey(self, hSession, pMechanism, hWrappingKey, hKey, WrappedKey): return _LowLevel.CPKCS11Lib_C_WrapKey(self, hSession, pMechanism, hWrappingKey, hKey, WrappedKey) def C_UnwrapKey(self, hSession, pMechanism, hUnwrappingKey, WrappedKey, Template, outhKey): return _LowLevel.CPKCS11Lib_C_UnwrapKey(self, hSession, pMechanism, hUnwrappingKey, WrappedKey, Template, outhKey) def C_SeedRandom(self, hSession, Seed): return _LowLevel.CPKCS11Lib_C_SeedRandom(self, hSession, Seed) def C_GenerateRandom(self, hSession, RandomData): return _LowLevel.CPKCS11Lib_C_GenerateRandom(self, hSession, RandomData) def C_WaitForSlotEvent(self, flags, INOUT): return _LowLevel.CPKCS11Lib_C_WaitForSlotEvent(self, flags, INOUT) def C_GetMechanismList(self, slotID, mechanismList): return _LowLevel.CPKCS11Lib_C_GetMechanismList(self, slotID, mechanismList) def C_GetMechanismInfo(self, slotID, type, pInfo): return _LowLevel.CPKCS11Lib_C_GetMechanismInfo(self, slotID, type, pInfo) # Register CPKCS11Lib in _LowLevel: _LowLevel.CPKCS11Lib_swigregister(CPKCS11Lib) class CK_ATTRIBUTE_SMART(object): thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def Reset(self): return _LowLevel.CK_ATTRIBUTE_SMART_Reset(self) def ResetValue(self): return _LowLevel.CK_ATTRIBUTE_SMART_ResetValue(self) def Reserve(self, len): return _LowLevel.CK_ATTRIBUTE_SMART_Reserve(self, len) def GetType(self): return _LowLevel.CK_ATTRIBUTE_SMART_GetType(self) def SetType(self, attrType): return _LowLevel.CK_ATTRIBUTE_SMART_SetType(self, attrType) def GetLen(self): return _LowLevel.CK_ATTRIBUTE_SMART_GetLen(self) def IsString(self): return _LowLevel.CK_ATTRIBUTE_SMART_IsString(self) def IsBool(self): return _LowLevel.CK_ATTRIBUTE_SMART_IsBool(self) def IsNum(self): return _LowLevel.CK_ATTRIBUTE_SMART_IsNum(self) def IsAttributeList(self): return _LowLevel.CK_ATTRIBUTE_SMART_IsAttributeList(self) def IsBin(self): return _LowLevel.CK_ATTRIBUTE_SMART_IsBin(self) def GetString(self): return _LowLevel.CK_ATTRIBUTE_SMART_GetString(self) def SetString(self, attrType, szValue): return _LowLevel.CK_ATTRIBUTE_SMART_SetString(self, attrType, szValue) def GetNum(self): return _LowLevel.CK_ATTRIBUTE_SMART_GetNum(self) def SetNum(self, attrType, ulValue): return _LowLevel.CK_ATTRIBUTE_SMART_SetNum(self, attrType, ulValue) def GetBool(self): return _LowLevel.CK_ATTRIBUTE_SMART_GetBool(self) def SetBool(self, attrType, bValue): return _LowLevel.CK_ATTRIBUTE_SMART_SetBool(self, attrType, bValue) def SetList(self, attrType, val): return _LowLevel.CK_ATTRIBUTE_SMART_SetList(self, attrType, val) def GetBin(self): return _LowLevel.CK_ATTRIBUTE_SMART_GetBin(self) def SetBin(self, attrType, pBuf): return _LowLevel.CK_ATTRIBUTE_SMART_SetBin(self, attrType, pBuf) def __init__(self): _LowLevel.CK_ATTRIBUTE_SMART_swiginit(self, _LowLevel.new_CK_ATTRIBUTE_SMART()) __swig_destroy__ = _LowLevel.delete_CK_ATTRIBUTE_SMART # Register CK_ATTRIBUTE_SMART in _LowLevel: _LowLevel.CK_ATTRIBUTE_SMART_swigregister(CK_ATTRIBUTE_SMART) PyKCS11-1.5.7/src/ck_attribute_smart.cpp0000644000076500000240000001312213455637550021005 0ustar rousseaustaff00000000000000// 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_SENSITIVE: case CKA_DECRYPT: case CKA_DERIVE: case CKA_ENCRYPT: case CKA_HAS_RESET: case CKA_LOCAL: case CKA_MODIFIABLE: 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: 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; } PyKCS11-1.5.7/src/ck_attribute_smart.h0000644000076500000240000000370113455637550020454 0ustar rousseaustaff00000000000000// 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); }; PyKCS11-1.5.7/src/dyn_generic.h0000644000076500000240000000424013421701653017040 0ustar rousseaustaff00000000000000/* * 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 PyKCS11-1.5.7/src/dyn_unix.c0000644000076500000240000000342713421700724016406 0ustar rousseaustaff00000000000000/* * 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__ */ PyKCS11-1.5.7/src/dyn_win32.c0000644000076500000240000000404113421701653016360 0ustar rousseaustaff00000000000000/* * 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 */ PyKCS11-1.5.7/src/opensc/0000755000076500000240000000000013576454261015703 5ustar rousseaustaff00000000000000PyKCS11-1.5.7/src/opensc/pkcs11.h0000644000076500000240000012504113546334027017153 0ustar rousseaustaff00000000000000/* 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_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_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) 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; } ; #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_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 */ PyKCS11-1.5.7/src/pkcs11lib.cpp0000644000076500000240000005766713546444717016740 0ustar rousseaustaff00000000000000// 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" #define CPKCS11LIB_PROLOGUE(FUNCTION_NAME) \ bool bRetryed = false; \ Retry: \ CK_RV rv; \ rv = CKR_OK; \ if (!m_hLib || !m_pFunc) \ return CKR_CRYPTOKI_NOT_INITIALIZED; #define CPKCS11LIB_EPILOGUE if (!bRetryed && m_hLib && m_pFunc && m_bAutoInitialized && \ CKR_CRYPTOKI_NOT_INITIALIZED == rv) { \ m_pFunc->C_Initialize(NULL); \ bRetryed=true; \ goto Retry; \ } CPKCS11Lib::CPKCS11Lib(void): m_bFinalizeOnClose(false), m_bAutoInitialized(false), m_hLib(0), m_pFunc(NULL) { } CPKCS11Lib::~CPKCS11Lib(void) { Unload(); } CK_RV CPKCS11Lib::Load(const char* szLib) { CK_RV rv; Unload(); 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; m_bFinalizeOnClose = true; return CKR_OK; } bool CPKCS11Lib::Unload() { bool bRes = false; if (m_hLib && m_pFunc && m_bFinalizeOnClose) m_pFunc->C_Finalize(NULL); if (m_hLib) { bRes = true; SYS_dyn_CloseLibrary((void**)&m_hLib); } m_hLib = 0; m_pFunc = NULL; m_bFinalizeOnClose = false; return bRes; } CK_RV CPKCS11Lib::C_Initialize() { CPKCS11LIB_PROLOGUE(C_Initialize); rv = m_pFunc->C_Initialize(NULL); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_Finalize() { CPKCS11LIB_PROLOGUE(C_Finalize); rv = m_pFunc->C_Finalize(NULL); if (CKR_OK == rv) m_bFinalizeOnClose = false; CPKCS11LIB_EPILOGUE; 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) { CPKCS11LIB_PROLOGUE(C_GetSlotList); CK_ULONG i; slotList.clear(); CK_SLOT_ID ck_slotList[1024]; CK_ULONG ulSlotCount = sizeof(ck_slotList)/sizeof(ck_slotList[0]); rv = m_pFunc->C_GetSlotList(tokenPresent, ck_slotList, &ulSlotCount); if (CKR_OK == rv) for(i=0; iC_GetSlotInfo(slotID, pInfo); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_GetTokenInfo ( CK_SLOT_ID slotID, CK_TOKEN_INFO* pInfo) { CPKCS11LIB_PROLOGUE(C_GetTokenInfo); rv = m_pFunc->C_GetTokenInfo(slotID, pInfo); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_InitToken( CK_SLOT_ID slotID, vector pin, const char* pLabel) { CPKCS11LIB_PROLOGUE(C_InitToken); CK_ULONG ulPinLen = 0; CK_BYTE* pPin = Vector2Buffer(pin, ulPinLen); rv = m_pFunc->C_InitToken(slotID, (CK_UTF8CHAR_PTR) pPin, ulPinLen, (CK_CHAR*)pLabel); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_InitPIN( CK_SESSION_HANDLE hSession, vector pin) { CPKCS11LIB_PROLOGUE(C_InitPIN); CK_ULONG ulPinLen = 0; CK_BYTE* pPin = Vector2Buffer(pin, ulPinLen); rv = m_pFunc->C_InitPIN(hSession, (CK_UTF8CHAR_PTR) pPin, ulPinLen); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_SetPIN( CK_SESSION_HANDLE hSession, vector OldPin, vector NewPin) { CPKCS11LIB_PROLOGUE(C_SetPIN); 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); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_OpenSession( CK_SLOT_ID slotID, CK_FLAGS flags, CK_SESSION_HANDLE& outhSession) { CPKCS11LIB_PROLOGUE(C_OpenSession); rv = m_pFunc->C_OpenSession(slotID, flags, NULL, NULL, &outhSession); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_CloseSession( CK_SESSION_HANDLE hSession) { CPKCS11LIB_PROLOGUE(C_CloseSession); rv = m_pFunc->C_CloseSession(hSession); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_CloseAllSessions( CK_SLOT_ID slotID) { CPKCS11LIB_PROLOGUE(C_CloseAllSessions); rv = m_pFunc->C_CloseAllSessions(slotID); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_GetSessionInfo( CK_SESSION_HANDLE hSession, CK_SESSION_INFO* pInfo) { CPKCS11LIB_PROLOGUE(C_GetSessionInfo); rv = m_pFunc->C_GetSessionInfo(hSession, pInfo); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_Login( CK_SESSION_HANDLE hSession, CK_USER_TYPE userType, vector pin) { CPKCS11LIB_PROLOGUE(C_Login); CK_ULONG ulPinLen = 0; CK_BYTE* pPin = Vector2Buffer(pin, ulPinLen); rv = m_pFunc->C_Login(hSession, userType, (CK_UTF8CHAR_PTR)pPin, ulPinLen); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_Logout( CK_SESSION_HANDLE hSession) { CPKCS11LIB_PROLOGUE(C_Logout); rv = m_pFunc->C_Logout(hSession); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_CreateObject( CK_SESSION_HANDLE hSession, vector Template, CK_OBJECT_HANDLE& outhObject) { CPKCS11LIB_PROLOGUE(C_CreateObject); 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); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_DestroyObject( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject) { CPKCS11LIB_PROLOGUE(C_DestroyObject); rv = m_pFunc->C_DestroyObject(hSession, (CK_OBJECT_HANDLE)hObject); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_GetObjectSize( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, CK_ULONG* pulSize) { CPKCS11LIB_PROLOGUE(C_GetObjectSize); rv = m_pFunc->C_GetObjectSize(hSession, (CK_OBJECT_HANDLE)hObject, pulSize); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_GetAttributeValue ( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject, vector &Template) { CPKCS11LIB_PROLOGUE(C_GetAttributeValue); 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) { CPKCS11LIB_PROLOGUE(C_SetAttributeValue); 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); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_FindObjectsInit( CK_SESSION_HANDLE hSession, vector &Template) { CPKCS11LIB_PROLOGUE(C_FindObjectsInit); CK_ULONG ulCount = 0; CK_ATTRIBUTE * pTemplate = AttrVector2Template(Template, ulCount); rv = m_pFunc->C_FindObjectsInit(hSession, pTemplate, ulCount); if (pTemplate) DestroyTemplate(pTemplate, ulCount); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_FindObjects( CK_SESSION_HANDLE hSession, vector& objectList) { CPKCS11LIB_PROLOGUE(C_FindObjects); 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; CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_FindObjectsFinal( CK_SESSION_HANDLE hSession) { CPKCS11LIB_PROLOGUE(C_FindObjectsFinal); rv = m_pFunc->C_FindObjectsFinal(hSession); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_EncryptInit( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, CK_OBJECT_HANDLE hKey) { CPKCS11LIB_PROLOGUE(C_EncryptInit); rv = m_pFunc->C_EncryptInit(hSession, pMechanism, (CK_OBJECT_HANDLE)hKey); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_Encrypt( CK_SESSION_HANDLE hSession, vector inData, vector &outEncryptedData) { CPKCS11LIB_PROLOGUE(C_Encrypt); 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; CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_EncryptUpdate( CK_SESSION_HANDLE hSession, vector inData, vector &outEncryptedData) { CPKCS11LIB_PROLOGUE(C_EncryptUpdate); 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; CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_EncryptFinal( CK_SESSION_HANDLE hSession, vector &outEncryptedData) { CPKCS11LIB_PROLOGUE(C_EncryptFinal); 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; CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_DecryptInit( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, CK_OBJECT_HANDLE hKey) { CPKCS11LIB_PROLOGUE(C_DecryptInit); rv = m_pFunc->C_DecryptInit(hSession, pMechanism, (CK_OBJECT_HANDLE)hKey); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_Decrypt( CK_SESSION_HANDLE hSession, vector inEncryptedData, vector &outData) { CPKCS11LIB_PROLOGUE(C_Decrypt); 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; CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_DecryptUpdate( CK_SESSION_HANDLE hSession, vector inEncryptedData, vector &outData) { CPKCS11LIB_PROLOGUE(C_DecryptUpdate); 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; CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_DecryptFinal( CK_SESSION_HANDLE hSession, vector &outData) { CPKCS11LIB_PROLOGUE(C_DecryptFinal); 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; CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_DigestInit( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism) { CPKCS11LIB_PROLOGUE(C_DigestInit); rv = m_pFunc->C_DigestInit(hSession, pMechanism); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_Digest( CK_SESSION_HANDLE hSession, vector inData, vector &outDigest) { CPKCS11LIB_PROLOGUE(C_Digest); 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; CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_DigestUpdate( CK_SESSION_HANDLE hSession, vector inData) { CPKCS11LIB_PROLOGUE(C_DigestUpdate); 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; CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_DigestKey ( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey) { CPKCS11LIB_PROLOGUE(C_DigestKey); rv = m_pFunc->C_DigestKey(hSession, (CK_OBJECT_HANDLE)hKey); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_DigestFinal( CK_SESSION_HANDLE hSession, vector &outDigest) { CPKCS11LIB_PROLOGUE(C_DigestFinal); 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; CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_SignInit( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, CK_OBJECT_HANDLE hKey) { CPKCS11LIB_PROLOGUE(C_SignInit); rv = m_pFunc->C_SignInit(hSession, pMechanism, (CK_OBJECT_HANDLE)hKey); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_Sign( CK_SESSION_HANDLE hSession, vector inData, vector &outSignature) { CPKCS11LIB_PROLOGUE(C_Sign); 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; CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_SignUpdate( CK_SESSION_HANDLE hSession, vector inData) { CPKCS11LIB_PROLOGUE(C_SignUpdate); 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; CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_SignFinal ( CK_SESSION_HANDLE hSession, vector &outSignature) { CPKCS11LIB_PROLOGUE(C_SignFinal); 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; CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_VerifyInit ( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, CK_OBJECT_HANDLE hKey) { CPKCS11LIB_PROLOGUE(C_VerifyInit); rv = m_pFunc->C_VerifyInit(hSession, pMechanism, (CK_OBJECT_HANDLE)hKey); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_Verify( CK_SESSION_HANDLE hSession, vector inData, vector inSignature) { CPKCS11LIB_PROLOGUE(C_Verify); 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; CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_VerifyUpdate( CK_SESSION_HANDLE hSession, vector inData) { CPKCS11LIB_PROLOGUE(C_VerifyUpdate); 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; CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_VerifyFinal( CK_SESSION_HANDLE hSession, vector inSignature) { CPKCS11LIB_PROLOGUE(C_VerifyFinal); 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; CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_GenerateKey( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, vector Template, CK_OBJECT_HANDLE& outhKey) { CPKCS11LIB_PROLOGUE(C_GenerateKey); 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); CPKCS11LIB_EPILOGUE; 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) { CPKCS11LIB_PROLOGUE(C_GenerateKeyPair); 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); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_WrapKey( CK_SESSION_HANDLE hSession, CK_MECHANISM* pMechanism, CK_OBJECT_HANDLE hWrappingKey, CK_OBJECT_HANDLE hKey, vector &WrappedKey) { CPKCS11LIB_PROLOGUE(C_WrapKey); 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; CPKCS11LIB_EPILOGUE; 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) { CPKCS11LIB_PROLOGUE(C_UnwrapKey); 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); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_SeedRandom( CK_SESSION_HANDLE hSession, vector Seed) { CPKCS11LIB_PROLOGUE(C_SeedRandom); CK_ULONG ulInDataLen = 0; CK_BYTE* pInData = Vector2Buffer(Seed, ulInDataLen); rv = m_pFunc->C_SeedRandom(hSession, pInData, ulInDataLen); if (pInData) delete []pInData; CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_GenerateRandom( CK_SESSION_HANDLE hSession, vector &RandomData) { CPKCS11LIB_PROLOGUE(C_GenerateRandom); 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; CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_WaitForSlotEvent( CK_FLAGS flags, unsigned long* pSlot) { CPKCS11LIB_PROLOGUE(C_WaitForSlotEvent); rv = m_pFunc->C_WaitForSlotEvent(flags, pSlot, NULL); CPKCS11LIB_EPILOGUE; return rv; } CK_RV CPKCS11Lib::C_GetMechanismList( unsigned long slotID, vector &mechanismList) { CPKCS11LIB_PROLOGUE(C_GetMechanismList); 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); CPKCS11LIB_EPILOGUE; return rv; } /////////////////////////////////////////////////////////////////////////////// PyKCS11-1.5.7/src/pkcs11lib.h0000644000076500000240000001561513546444717016370 0ustar rousseaustaff00000000000000// 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 { bool m_bFinalizeOnClose; bool m_bAutoInitialized; #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(); 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_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); }; PyKCS11-1.5.7/src/pykcs11.cpp0000644000076500000240000000211113421700724016371 0ustar rousseaustaff00000000000000// 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 PyKCS11-1.5.7/src/pykcs11.h0000644000076500000240000000143313421700724016044 0ustar rousseaustaff00000000000000// 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 PyKCS11-1.5.7/src/pykcs11.i0000644000076500000240000012253113473500675016062 0ustar rousseaustaff00000000000000// 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]; sprintf(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]; sprintf(szVal, "%d.%02d", self->hardwareVersion.major, self->hardwareVersion.minor); return PyKCS11String(szVal); } PyKCS11String GetFirmwareVersion() { char szVal[10]; sprintf(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]; sprintf(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, SWIGTYPE_p_std__vectorT_unsigned_char_std__allocatorT_unsigned_char_t_t, 0))) { // Get the data from the vector // The recommanded code in C++11 should be vect->data() but // Microsoft Visual Studio 9.0 does not suport it and this // compiler is needed for Python 2.7 arg2 = &vect->operator[](0); } else { // If the value being set is of CK_RSA_PKCS_OAEP_PARAMS type: int res2 = SWIG_ConvertPtr($input, &arg2, $descriptor(CK_RSA_PKCS_OAEP_PARAMS*), 0 | 0 ); if (!SWIG_IsOK(res2)) { res2 = SWIG_ConvertPtr($input, &arg2, $descriptor(CK_RSA_PKCS_PSS_PARAMS*), 0); if (!SWIG_IsOK(res2)) { res2 = SWIG_ConvertPtr($input, &arg2, $descriptor(CK_GCM_PARAMS*), 0); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "unsupported CK_MECHANISM Parameter type."); } } } } } 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; } }; 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); %typemap(in) void*; %typemap(in) void* = char*; 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); //%typemap(in) void*; //%typemap(in) void* = char*; 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_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 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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_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_RSA_PKCS_TPM_1_1 0x00004001 #define CKM_RSA_PKCS_OAEP_TPM_1_1 0x00004002 #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_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_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_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_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 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); }; PyKCS11-1.5.7/src/pykcs11string.cpp0000644000076500000240000000261713421700724017633 0ustar rousseaustaff00000000000000// 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]); } PyKCS11-1.5.7/src/pykcs11string.h0000644000076500000240000000212713421700724017274 0ustar rousseaustaff00000000000000// 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; PyKCS11-1.5.7/src/stdafx.cpp0000644000076500000240000000205213421700724016373 0ustar rousseaustaff00000000000000// 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.cpp : source file that includes just the standard includes // PyKCS11.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file PyKCS11-1.5.7/src/stdafx.h0000644000076500000240000000241613421700724016044 0ustar rousseaustaff00000000000000// 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 PyKCS11-1.5.7/src/utility.cpp0000644000076500000240000000457413421700724016620 0ustar rousseaustaff00000000000000// 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_ PyKCS11-1.5.7/test/0000755000076500000240000000000013576454261014604 5ustar rousseaustaff00000000000000PyKCS11-1.5.7/test/test_CK.py0000644000076500000240000000106013455626774016515 0ustar rousseaustaff00000000000000#! /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) if __name__ == "__main__": unittest.main() PyKCS11-1.5.7/test/test_LowLevel.py0000644000076500000240000001126013546445205017741 0ustar rousseaustaff00000000000000import unittest from PyKCS11 import ckbytelist import PyKCS11.LowLevel import os from distutils.util import get_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 get_platform().startswith('linux'): # GNU/Linux lib = "libc.so.6" elif get_platform().startswith('macosx'): # 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() PyKCS11-1.5.7/test/test_asymetric.py0000644000076500000240000001417613455626774020234 0ustar rousseaustaff00000000000000import 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") 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) 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_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, 0 ) 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, 0, ) 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) PyKCS11-1.5.7/test/test_asymetric_ECC.py0000644000076500000240000000637313455626774020706 0ustar rousseaustaff00000000000000import 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) PyKCS11-1.5.7/test/test_asymetric_gost.py0000644000076500000240000000557213455626774021270 0ustar rousseaustaff00000000000000import 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_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) PyKCS11-1.5.7/test/test_ckbytelist.py0000644000076500000240000000461613546444747020406 0ustar rousseaustaff00000000000000import 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) import sys if sys.version_info[0] >= 3: # Python 3 and later type_str = "" else: # Python 2 type_str = "" self.assertEqual(the_exception.text, type_str) self.assertEqual(str(the_exception), "Unknown format (%s)" % type_str) if __name__ == "__main__": unittest.main() PyKCS11-1.5.7/test/test_digest.py0000644000076500000240000000204613455626774017504 0ustar rousseaustaff00000000000000#! /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() PyKCS11-1.5.7/test/test_exception.py0000644000076500000240000000262013455626774020221 0ustar rousseaustaff00000000000000import 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)") PyKCS11-1.5.7/test/test_info.py0000644000076500000240000000321413455626774017156 0ustar rousseaustaff00000000000000import 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) PyKCS11-1.5.7/test/test_init.py0000644000076500000240000000516313455626774017173 0ustar rousseaustaff00000000000000# -*- 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): # for Python version ≥ 3 only import sys if sys.version_info[0] < 3: return 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() PyKCS11-1.5.7/test/test_load.py0000644000076500000240000000241413546444747017142 0ustar rousseaustaff00000000000000# -*- coding: utf-8 -*- import unittest from PyKCS11 import PyKCS11 from distutils.util import get_platform class TestUtil(unittest.TestCase): def setUp(self): self.pkcs11 = PyKCS11.PyKCS11Lib() def tearDown(self): del self.pkcs11 def test_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) # C_GetFunctionList() not found if get_platform().startswith('linux'): # GNU/Linux lib = "libc.so.6" elif get_platform().startswith('macosx'): # 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) PyKCS11-1.5.7/test/test_objects.py0000644000076500000240000000507713455626774017665 0ustar rousseaustaff00000000000000import 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_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,), ], ) self.session.destroyObject(AESKey) PyKCS11-1.5.7/test/test_pin.py0000644000076500000240000000345113546444747017013 0ustar rousseaustaff00000000000000import 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)") PyKCS11-1.5.7/test/test_random.py0000644000076500000240000000132413455626774017503 0ustar rousseaustaff00000000000000import 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) PyKCS11-1.5.7/test/test_symetric.py0000644000076500000240000000767213546726000020056 0ustar rousseaustaff00000000000000from __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) # # 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) PyKCS11-1.5.7/test/test_wrap.py0000644000076500000240000002676613455637550017207 0ustar rousseaustaff00000000000000import 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, [(0,)]) # cleanup self.session.destroyObject(unwrapped) self.session.destroyObject(self.pubKey) self.session.destroyObject(self.privKey) PyKCS11-1.5.7/tox.ini0000644000076500000240000000074313455626774015152 0ustar rousseaustaff00000000000000# 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 = py27,py37 [testenv] whitelist_externals = cp ln deps = asn1crypto changedir = {envdir} commands = cp {toxinidir}/run_test.py . ln -sf {toxinidir}/test {envpython} run_test.py