PK! __init__.pynu[PK!nQ _advapi32.pynu[# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import sys from .. import ffi from ._decode import _try_decode from ..errors import SignatureError from .._ffi import new, unwrap, null from .._types import str_cls if ffi() == 'cffi': from ._advapi32_cffi import advapi32, get_error else: from ._advapi32_ctypes import advapi32, get_error __all__ = [ 'advapi32', 'Advapi32Const', 'handle_error', ] _gwv = sys.getwindowsversion() _win_version_info = (_gwv[0], _gwv[1]) def open_context_handle(provider, verify_only=True): if provider == Advapi32Const.MS_ENH_RSA_AES_PROV: provider_type = Advapi32Const.PROV_RSA_AES elif provider == Advapi32Const.MS_ENH_DSS_DH_PROV: provider_type = Advapi32Const.PROV_DSS_DH else: raise ValueError('Invalid provider specified: %s' % provider) # The DSS provider needs a container to allow importing and exporting # private keys, but all of the RSA stuff works fine with CRYPT_VERIFYCONTEXT if verify_only or provider != Advapi32Const.MS_ENH_DSS_DH_PROV: container_name = null() flags = Advapi32Const.CRYPT_VERIFYCONTEXT else: container_name = Advapi32Const.CONTAINER_NAME flags = Advapi32Const.CRYPT_NEWKEYSET context_handle_pointer = new(advapi32, 'HCRYPTPROV *') res = advapi32.CryptAcquireContextW( context_handle_pointer, container_name, provider, provider_type, flags ) # If using the DSS provider and the container exists, just open it if not res and get_error()[0] == Advapi32Const.NTE_EXISTS: res = advapi32.CryptAcquireContextW( context_handle_pointer, container_name, provider, provider_type, 0 ) handle_error(res) return unwrap(context_handle_pointer) def close_context_handle(handle): res = advapi32.CryptReleaseContext(handle, 0) handle_error(res) def handle_error(result): """ Extracts the last Windows error message into a python unicode string :param result: A function result, 0 or None indicates failure :return: A unicode string error message """ if result: return code, error_string = get_error() if code == Advapi32Const.NTE_BAD_SIGNATURE: raise SignatureError('Signature is invalid') if not isinstance(error_string, str_cls): error_string = _try_decode(error_string) raise OSError(error_string) class Advapi32Const(): # Name we give to a container used to make DSA private key import/export work CONTAINER_NAME = 'oscrypto temporary DSS keyset' PROV_RSA_AES = 24 PROV_DSS_DH = 13 X509_PUBLIC_KEY_INFO = 8 PKCS_PRIVATE_KEY_INFO = 44 X509_DSS_SIGNATURE = 40 CRYPT_NO_SALT = 0x00000010 MS_ENH_DSS_DH_PROV = "Microsoft Enhanced DSS and Diffie-Hellman Cryptographic Provider" # This is the name for Windows Server 2003 and newer and Windows Vista and newer MS_ENH_RSA_AES_PROV = "Microsoft Enhanced RSA and AES Cryptographic Provider" CRYPT_EXPORTABLE = 1 CRYPT_NEWKEYSET = 0x00000008 CRYPT_VERIFYCONTEXT = 0xF0000000 CALG_MD5 = 0x00008003 CALG_SHA1 = 0x00008004 CALG_SHA_256 = 0x0000800c CALG_SHA_384 = 0x0000800d CALG_SHA_512 = 0x0000800e CALG_RC2 = 0x00006602 CALG_RC4 = 0x00006801 CALG_DES = 0x00006601 CALG_3DES_112 = 0x00006609 CALG_3DES = 0x00006603 CALG_AES_128 = 0x0000660e CALG_AES_192 = 0x0000660f CALG_AES_256 = 0x00006610 CALG_DSS_SIGN = 0x00002200 CALG_RSA_SIGN = 0x00002400 CALG_RSA_KEYX = 0x0000a400 CRYPT_MODE_CBC = 1 PKCS5_PADDING = 1 CUR_BLOB_VERSION = 2 PUBLICKEYBLOB = 6 PRIVATEKEYBLOB = 7 PLAINTEXTKEYBLOB = 8 KP_IV = 1 KP_PADDING = 3 KP_MODE = 4 KP_EFFECTIVE_KEYLEN = 19 CRYPT_OAEP = 0x00000040 NTE_BAD_SIGNATURE = -2146893818 # 0x80090006 NTE_EXISTS = -2146893809 # 0x8009000F AT_SIGNATURE = 2 RSA1 = 0x31415352 RSA2 = 0x32415352 DSS1 = 0x31535344 DSS2 = 0x32535344 if _win_version_info == (5, 1): # This is the Windows XP name for the provider Advapi32Const.MS_ENH_RSA_AES_PROV = "Microsoft Enhanced RSA and AES Cryptographic Provider (Prototype)" PK!_advapi32_cffi.pynu[# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function from .._ffi import register_ffi from .._types import str_cls from ..errors import LibraryNotFoundError import cffi __all__ = [ 'advapi32', 'get_error', ] ffi = cffi.FFI() if cffi.__version_info__ >= (0, 9): ffi.set_unicode(True) ffi.cdef(""" typedef HANDLE HCRYPTPROV; typedef HANDLE HCRYPTKEY; typedef HANDLE HCRYPTHASH; typedef unsigned int ALG_ID; typedef struct _CRYPTOAPI_BLOB { DWORD cbData; BYTE *pbData; } CRYPT_INTEGER_BLOB, CRYPT_OBJID_BLOB, CRYPT_DER_BLOB, CRYPT_ATTR_BLOB; typedef struct _CRYPT_ALGORITHM_IDENTIFIER { LPSTR pszObjId; CRYPT_OBJID_BLOB Parameters; } CRYPT_ALGORITHM_IDENTIFIER; typedef struct _CRYPT_BIT_BLOB { DWORD cbData; BYTE *pbData; DWORD cUnusedBits; } CRYPT_BIT_BLOB; typedef struct _CERT_PUBLIC_KEY_INFO { CRYPT_ALGORITHM_IDENTIFIER Algorithm; CRYPT_BIT_BLOB PublicKey; } CERT_PUBLIC_KEY_INFO; typedef struct _CRYPT_ATTRIBUTE { LPSTR pszObjId; DWORD cValue; CRYPT_ATTR_BLOB *rgValue; } CRYPT_ATTRIBUTE; typedef struct _CRYPT_ATTRIBUTES { DWORD cAttr; CRYPT_ATTRIBUTE *rgAttr; } CRYPT_ATTRIBUTES; typedef struct _CRYPT_PRIVATE_KEY_INFO { DWORD Version; CRYPT_ALGORITHM_IDENTIFIER Algorithm; CRYPT_DER_BLOB PrivateKey; CRYPT_ATTRIBUTES *pAttributes; } CRYPT_PRIVATE_KEY_INFO; typedef struct _PUBLICKEYSTRUC { BYTE bType; BYTE bVersion; WORD reserved; ALG_ID aiKeyAlg; } BLOBHEADER, PUBLICKEYSTRUC; typedef struct _DSSPUBKEY { DWORD magic; DWORD bitlen; } DSSPUBKEY; typedef struct _DSSBLOBHEADER { PUBLICKEYSTRUC publickeystruc; DSSPUBKEY dsspubkey; } DSSBLOBHEADER; typedef struct _RSAPUBKEY { DWORD magic; DWORD bitlen; DWORD pubexp; } RSAPUBKEY; typedef struct _RSABLOBHEADER { PUBLICKEYSTRUC publickeystruc; RSAPUBKEY rsapubkey; } RSABLOBHEADER; typedef struct _PLAINTEXTKEYBLOB { BLOBHEADER hdr; DWORD dwKeySize; // rgbKeyData omitted since it is a flexible array member } PLAINTEXTKEYBLOB; typedef struct _DSSSEED { DWORD counter; BYTE seed[20]; } DSSSEED; BOOL CryptAcquireContextW(HCRYPTPROV *phProv, LPCWSTR pszContainer, LPCWSTR pszProvider, DWORD dwProvType, DWORD dwFlags); BOOL CryptReleaseContext(HCRYPTPROV hProv, DWORD dwFlags); BOOL CryptImportKey(HCRYPTPROV hProv, BYTE *pbData, DWORD dwDataLen, HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY *phKey); BOOL CryptGenKey(HCRYPTPROV hProv, ALG_ID Algid, DWORD dwFlags, HCRYPTKEY *phKey); BOOL CryptGetKeyParam(HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData, DWORD *pdwDataLen, DWORD dwFlags); BOOL CryptSetKeyParam(HCRYPTKEY hKey, DWORD dwParam, void *pbData, DWORD dwFlags); BOOL CryptExportKey(HCRYPTKEY hKey, HCRYPTKEY hExpKey, DWORD dwBlobType, DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen); BOOL CryptDestroyKey(HCRYPTKEY hKey); BOOL CryptCreateHash(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTKEY hKey, DWORD dwFlags, HCRYPTHASH *phHash); BOOL CryptHashData(HCRYPTHASH hHash, BYTE *pbData, DWORD dwDataLen, DWORD dwFlags); BOOL CryptSetHashParam(HCRYPTHASH hHash, DWORD dwParam, BYTE *pbData, DWORD dwFlags); BOOL CryptSignHashW(HCRYPTHASH hHash, DWORD dwKeySpec, LPCWSTR sDescription, DWORD dwFlags, BYTE *pbSignature, DWORD *pdwSigLen); BOOL CryptVerifySignatureW(HCRYPTHASH hHash, BYTE *pbSignature, DWORD dwSigLen, HCRYPTKEY hPubKey, LPCWSTR sDescription, DWORD dwFlags); BOOL CryptDestroyHash(HCRYPTHASH hHash); BOOL CryptEncrypt(HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final, DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen, DWORD dwBufLen); BOOL CryptDecrypt(HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final, DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen); """) try: advapi32 = ffi.dlopen('advapi32.dll') register_ffi(advapi32, ffi) except (OSError) as e: if str_cls(e).find('cannot load library') != -1: raise LibraryNotFoundError('advapi32.dll could not be found') raise def get_error(): return ffi.getwinerror() PK!Cz>>_advapi32_ctypes.pynu[# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import ctypes from ctypes import windll, wintypes, POINTER, Structure, c_void_p, c_char_p, c_uint from ctypes.wintypes import BOOL, DWORD from .._ffi import FFIEngineError from .._types import str_cls from ..errors import LibraryNotFoundError __all__ = [ 'advapi32', 'get_error', ] try: advapi32 = windll.advapi32 except (OSError) as e: if str_cls(e).find('The specified module could not be found') != -1: raise LibraryNotFoundError('advapi32.dll could not be found') raise HCRYPTPROV = wintypes.HANDLE HCRYPTKEY = wintypes.HANDLE HCRYPTHASH = wintypes.HANDLE PBYTE = c_char_p ALG_ID = c_uint try: class CRYPTOAPI_BLOB(Structure): # noqa _fields_ = [ ("cbData", DWORD), ("pbData", POINTER(ctypes.c_byte)), ] CRYPT_INTEGER_BLOB = CRYPTOAPI_BLOB CRYPT_OBJID_BLOB = CRYPTOAPI_BLOB CRYPT_DER_BLOB = CRYPTOAPI_BLOB CRYPT_ATTR_BLOB = CRYPTOAPI_BLOB class CRYPT_ALGORITHM_IDENTIFIER(Structure): _fields = [ ('pszObjId', wintypes.LPSTR), ('Parameters', CRYPT_OBJID_BLOB), ] class CRYPT_BIT_BLOB(Structure): _fields_ = [ ('cbData', DWORD), ('pbData', PBYTE), ('cUnusedBits', DWORD), ] class CERT_PUBLIC_KEY_INFO(Structure): _fields_ = [ ('Algorithm', CRYPT_ALGORITHM_IDENTIFIER), ('PublicKey', CRYPT_BIT_BLOB), ] class CRYPT_ATTRIBUTE(Structure): _fields_ = [ ('pszObjId', wintypes.LPSTR), ('cValue', DWORD), ('rgValue', POINTER(CRYPT_ATTR_BLOB)), ] class CRYPT_ATTRIBUTES(Structure): _fields_ = [ ('cAttr', DWORD), ('rgAttr', POINTER(CRYPT_ATTRIBUTE)), ] class CRYPT_PRIVATE_KEY_INFO(Structure): _fields_ = [ ('Version', DWORD), ('Algorithm', CRYPT_ALGORITHM_IDENTIFIER), ('PrivateKey', CRYPT_DER_BLOB), ('pAttributes', POINTER(CRYPT_ATTRIBUTES)), ] class PUBLICKEYSTRUC(Structure): _fields_ = [ ('bType', wintypes.BYTE), ('bVersion', wintypes.BYTE), ('reserved', wintypes.WORD), ('aiKeyAlg', ALG_ID), ] BLOBHEADER = PUBLICKEYSTRUC class DSSPUBKEY(Structure): _fields_ = [ ('magic', DWORD), ('bitlen', DWORD), ] class DSSBLOBHEADER(Structure): _fields_ = [ ('publickeystruc', PUBLICKEYSTRUC), ('dsspubkey', DSSPUBKEY), ] class RSAPUBKEY(Structure): _fields_ = [ ('magic', DWORD), ('bitlen', DWORD), ('pubexp', DWORD), ] class RSABLOBHEADER(Structure): _fields_ = [ ('publickeystruc', PUBLICKEYSTRUC), ('rsapubkey', RSAPUBKEY), ] class PLAINTEXTKEYBLOB(Structure): _fields_ = [ ('hdr', BLOBHEADER), ('dwKeySize', DWORD), # rgbKeyData omitted since it is a flexible array member ] class DSSSEED(Structure): _fields_ = [ ('counter', DWORD), ('seed', wintypes.BYTE * 20), ] advapi32.CryptAcquireContextW.argtypes = [ POINTER(HCRYPTPROV), wintypes.LPCWSTR, wintypes.LPCWSTR, DWORD, DWORD ] advapi32.CryptAcquireContextW.restype = wintypes.BOOL advapi32.CryptReleaseContext.argtypes = [ HCRYPTPROV, DWORD ] advapi32.CryptReleaseContext.restype = wintypes.BOOL advapi32.CryptImportKey.argtypes = [ HCRYPTPROV, PBYTE, DWORD, HCRYPTKEY, DWORD, POINTER(HCRYPTKEY) ] advapi32.CryptImportKey.restype = BOOL advapi32.CryptGenKey.argtypes = [ HCRYPTPROV, ALG_ID, DWORD, POINTER(HCRYPTKEY) ] advapi32.CryptGenKey.restype = wintypes.BOOL advapi32.CryptGetKeyParam.argtypes = [ HCRYPTKEY, DWORD, PBYTE, POINTER(DWORD), DWORD ] advapi32.CryptGetKeyParam.restype = wintypes.BOOL advapi32.CryptSetKeyParam.argtypes = [ HCRYPTKEY, DWORD, c_void_p, DWORD ] advapi32.CryptSetKeyParam.restype = wintypes.BOOL advapi32.CryptExportKey.argtypes = [ HCRYPTKEY, HCRYPTKEY, DWORD, DWORD, PBYTE, POINTER(DWORD) ] advapi32.CryptExportKey.restype = BOOL advapi32.CryptDestroyKey.argtypes = [ HCRYPTKEY ] advapi32.CryptDestroyKey.restype = wintypes.BOOL advapi32.CryptCreateHash.argtypes = [ HCRYPTPROV, ALG_ID, HCRYPTKEY, DWORD, POINTER(HCRYPTHASH) ] advapi32.CryptCreateHash.restype = BOOL advapi32.CryptHashData.argtypes = [ HCRYPTHASH, PBYTE, DWORD, DWORD ] advapi32.CryptHashData.restype = BOOL advapi32.CryptSetHashParam.argtypes = [ HCRYPTHASH, DWORD, PBYTE, DWORD ] advapi32.CryptSetHashParam.restype = BOOL advapi32.CryptSignHashW.argtypes = [ HCRYPTHASH, DWORD, wintypes.LPCWSTR, DWORD, PBYTE, POINTER(DWORD) ] advapi32.CryptSignHashW.restype = BOOL advapi32.CryptVerifySignatureW.argtypes = [ HCRYPTHASH, PBYTE, DWORD, HCRYPTKEY, wintypes.LPCWSTR, DWORD ] advapi32.CryptVerifySignatureW.restype = BOOL advapi32.CryptDestroyHash.argtypes = [ HCRYPTHASH ] advapi32.CryptDestroyHash.restype = wintypes.BOOL advapi32.CryptEncrypt.argtypes = [ HCRYPTKEY, HCRYPTHASH, BOOL, DWORD, PBYTE, POINTER(DWORD), DWORD ] advapi32.CryptEncrypt.restype = BOOL advapi32.CryptDecrypt.argtypes = [ HCRYPTKEY, HCRYPTHASH, BOOL, DWORD, PBYTE, POINTER(DWORD) ] advapi32.CryptDecrypt.restype = BOOL except (AttributeError): raise FFIEngineError('Error initializing ctypes') setattr(advapi32, 'HCRYPTPROV', HCRYPTPROV) setattr(advapi32, 'HCRYPTKEY', HCRYPTKEY) setattr(advapi32, 'HCRYPTHASH', HCRYPTHASH) setattr(advapi32, 'CRYPT_INTEGER_BLOB', CRYPT_INTEGER_BLOB) setattr(advapi32, 'CRYPT_OBJID_BLOB', CRYPT_OBJID_BLOB) setattr(advapi32, 'CRYPT_DER_BLOB', CRYPT_DER_BLOB) setattr(advapi32, 'CRYPT_ATTR_BLOB', CRYPT_ATTR_BLOB) setattr(advapi32, 'CRYPT_ALGORITHM_IDENTIFIER', CRYPT_ALGORITHM_IDENTIFIER) setattr(advapi32, 'CRYPT_BIT_BLOB', CRYPT_BIT_BLOB) setattr(advapi32, 'CERT_PUBLIC_KEY_INFO', CERT_PUBLIC_KEY_INFO) setattr(advapi32, 'CRYPT_PRIVATE_KEY_INFO', CRYPT_PRIVATE_KEY_INFO) setattr(advapi32, 'CRYPT_ATTRIBUTE', CRYPT_ATTRIBUTE) setattr(advapi32, 'CRYPT_ATTRIBUTES', CRYPT_ATTRIBUTES) setattr(advapi32, 'PUBLICKEYSTRUC', PUBLICKEYSTRUC) setattr(advapi32, 'DSSPUBKEY', DSSPUBKEY) setattr(advapi32, 'DSSBLOBHEADER', DSSBLOBHEADER) setattr(advapi32, 'RSAPUBKEY', RSAPUBKEY) setattr(advapi32, 'RSABLOBHEADER', RSABLOBHEADER) setattr(advapi32, 'BLOBHEADER', BLOBHEADER) setattr(advapi32, 'PLAINTEXTKEYBLOB', PLAINTEXTKEYBLOB) setattr(advapi32, 'DSSSEED', DSSSEED) def get_error(): error = ctypes.GetLastError() return (error, ctypes.FormatError(error)) PK!;N_cng.pynu[# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function from .. import ffi from .._ffi import new, null, unwrap if ffi() == 'cffi': from ._cng_cffi import bcrypt else: from ._cng_ctypes import bcrypt __all__ = [ 'bcrypt', 'BcryptConst', 'close_alg_handle', 'handle_error', 'open_alg_handle', ] def open_alg_handle(constant, flags=0): handle_pointer = new(bcrypt, 'BCRYPT_ALG_HANDLE *') res = bcrypt.BCryptOpenAlgorithmProvider(handle_pointer, constant, null(), flags) handle_error(res) return unwrap(handle_pointer) def close_alg_handle(handle): res = bcrypt.BCryptCloseAlgorithmProvider(handle, 0) handle_error(res) def handle_error(error_num): """ Extracts the last Windows error message into a python unicode string :param error_num: The number to get the error string for :return: A unicode string error message """ if error_num == 0: return messages = { BcryptConst.STATUS_NOT_FOUND: 'The object was not found', BcryptConst.STATUS_INVALID_PARAMETER: 'An invalid parameter was passed to a service or function', BcryptConst.STATUS_NO_MEMORY: ( 'Not enough virtual memory or paging file quota is available to complete the specified operation' ), BcryptConst.STATUS_INVALID_HANDLE: 'An invalid HANDLE was specified', BcryptConst.STATUS_INVALID_SIGNATURE: 'The cryptographic signature is invalid', BcryptConst.STATUS_NOT_SUPPORTED: 'The request is not supported', BcryptConst.STATUS_BUFFER_TOO_SMALL: 'The buffer is too small to contain the entry', BcryptConst.STATUS_INVALID_BUFFER_SIZE: 'The size of the buffer is invalid for the specified operation', } output = 'NTSTATUS error 0x%0.2X' % error_num if error_num is not None and error_num in messages: output += ': ' + messages[error_num] raise OSError(output) class BcryptConst(): BCRYPT_RNG_ALGORITHM = 'RNG' BCRYPT_KEY_LENGTH = 'KeyLength' BCRYPT_EFFECTIVE_KEY_LENGTH = 'EffectiveKeyLength' BCRYPT_RSAPRIVATE_BLOB = 'RSAPRIVATEBLOB' BCRYPT_RSAFULLPRIVATE_BLOB = 'RSAFULLPRIVATEBLOB' BCRYPT_RSAPUBLIC_BLOB = 'RSAPUBLICBLOB' BCRYPT_DSA_PRIVATE_BLOB = 'DSAPRIVATEBLOB' BCRYPT_DSA_PUBLIC_BLOB = 'DSAPUBLICBLOB' BCRYPT_ECCPRIVATE_BLOB = 'ECCPRIVATEBLOB' BCRYPT_ECCPUBLIC_BLOB = 'ECCPUBLICBLOB' BCRYPT_RSAPUBLIC_MAGIC = 0x31415352 BCRYPT_RSAPRIVATE_MAGIC = 0x32415352 BCRYPT_RSAFULLPRIVATE_MAGIC = 0x33415352 BCRYPT_DSA_PUBLIC_MAGIC = 0x42505344 BCRYPT_DSA_PRIVATE_MAGIC = 0x56505344 BCRYPT_DSA_PUBLIC_MAGIC_V2 = 0x32425044 BCRYPT_DSA_PRIVATE_MAGIC_V2 = 0x32565044 DSA_HASH_ALGORITHM_SHA1 = 0 DSA_HASH_ALGORITHM_SHA256 = 1 DSA_HASH_ALGORITHM_SHA512 = 2 DSA_FIPS186_2 = 0 DSA_FIPS186_3 = 1 BCRYPT_NO_KEY_VALIDATION = 8 BCRYPT_ECDSA_PUBLIC_P256_MAGIC = 0x31534345 BCRYPT_ECDSA_PRIVATE_P256_MAGIC = 0x32534345 BCRYPT_ECDSA_PUBLIC_P384_MAGIC = 0x33534345 BCRYPT_ECDSA_PRIVATE_P384_MAGIC = 0x34534345 BCRYPT_ECDSA_PUBLIC_P521_MAGIC = 0x35534345 BCRYPT_ECDSA_PRIVATE_P521_MAGIC = 0x36534345 STATUS_SUCCESS = 0x00000000 STATUS_NOT_FOUND = 0xC0000225 STATUS_INVALID_PARAMETER = 0xC000000D STATUS_NO_MEMORY = 0xC0000017 STATUS_INVALID_HANDLE = 0xC0000008 STATUS_INVALID_SIGNATURE = 0xC000A000 STATUS_NOT_SUPPORTED = 0xC00000BB STATUS_BUFFER_TOO_SMALL = 0xC0000023 STATUS_INVALID_BUFFER_SIZE = 0xC0000206 BCRYPT_KEY_DATA_BLOB_MAGIC = 0x4d42444b BCRYPT_KEY_DATA_BLOB_VERSION1 = 0x00000001 BCRYPT_KEY_DATA_BLOB = 'KeyDataBlob' BCRYPT_PAD_PKCS1 = 0x00000002 BCRYPT_PAD_OAEP = 0x00000004 BCRYPT_PAD_PSS = 0x00000008 BCRYPT_3DES_ALGORITHM = '3DES' BCRYPT_3DES_112_ALGORITHM = '3DES_112' BCRYPT_AES_ALGORITHM = 'AES' BCRYPT_DES_ALGORITHM = 'DES' BCRYPT_RC2_ALGORITHM = 'RC2' BCRYPT_RC4_ALGORITHM = 'RC4' BCRYPT_DSA_ALGORITHM = 'DSA' BCRYPT_ECDSA_P256_ALGORITHM = 'ECDSA_P256' BCRYPT_ECDSA_P384_ALGORITHM = 'ECDSA_P384' BCRYPT_ECDSA_P521_ALGORITHM = 'ECDSA_P521' BCRYPT_RSA_ALGORITHM = 'RSA' BCRYPT_MD5_ALGORITHM = 'MD5' BCRYPT_SHA1_ALGORITHM = 'SHA1' BCRYPT_SHA256_ALGORITHM = 'SHA256' BCRYPT_SHA384_ALGORITHM = 'SHA384' BCRYPT_SHA512_ALGORITHM = 'SHA512' BCRYPT_ALG_HANDLE_HMAC_FLAG = 0x00000008 BCRYPT_BLOCK_PADDING = 0x00000001 PK!pv~~ _cng_cffi.pynu[# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function from .._ffi import register_ffi from .._types import str_cls from ..errors import LibraryNotFoundError from cffi import FFI __all__ = [ 'bcrypt', ] ffi = FFI() ffi.cdef(""" typedef HANDLE BCRYPT_ALG_HANDLE; typedef HANDLE BCRYPT_KEY_HANDLE; typedef ULONG NTSTATUS; typedef unsigned char *PUCHAR; typedef unsigned char *PBYTE; typedef struct _BCRYPT_RSAKEY_BLOB { ULONG Magic; ULONG BitLength; ULONG cbPublicExp; ULONG cbModulus; ULONG cbPrime1; ULONG cbPrime2; } BCRYPT_RSAKEY_BLOB; typedef struct _BCRYPT_DSA_KEY_BLOB { ULONG dwMagic; ULONG cbKey; UCHAR Count[4]; UCHAR Seed[20]; UCHAR q[20]; } BCRYPT_DSA_KEY_BLOB; typedef struct _BCRYPT_DSA_KEY_BLOB_V2 { ULONG dwMagic; ULONG cbKey; INT hashAlgorithm; INT standardVersion; ULONG cbSeedLength; ULONG cbGroupSize; UCHAR Count[4]; } BCRYPT_DSA_KEY_BLOB_V2; typedef struct _BCRYPT_ECCKEY_BLOB { ULONG dwMagic; ULONG cbKey; } BCRYPT_ECCKEY_BLOB; typedef struct _BCRYPT_PKCS1_PADDING_INFO { LPCWSTR pszAlgId; } BCRYPT_PKCS1_PADDING_INFO; typedef struct _BCRYPT_PSS_PADDING_INFO { LPCWSTR pszAlgId; ULONG cbSalt; } BCRYPT_PSS_PADDING_INFO; typedef struct _BCRYPT_OAEP_PADDING_INFO { LPCWSTR pszAlgId; PUCHAR pbLabel; ULONG cbLabel; } BCRYPT_OAEP_PADDING_INFO; typedef struct _BCRYPT_KEY_DATA_BLOB_HEADER { ULONG dwMagic; ULONG dwVersion; ULONG cbKeyData; } BCRYPT_KEY_DATA_BLOB_HEADER; NTSTATUS BCryptOpenAlgorithmProvider(BCRYPT_ALG_HANDLE *phAlgorithm, LPCWSTR pszAlgId, LPCWSTR pszImplementation, DWORD dwFlags); NTSTATUS BCryptCloseAlgorithmProvider(BCRYPT_ALG_HANDLE hAlgorithm, DWORD dwFlags); NTSTATUS BCryptSetProperty(HANDLE hObject, LPCWSTR pszProperty, ULONG *pbInput, ULONG cbInput, ULONG dwFlags); NTSTATUS BCryptImportKeyPair(BCRYPT_ALG_HANDLE hAlgorithm, BCRYPT_KEY_HANDLE hImportKey, LPCWSTR pszBlobType, BCRYPT_KEY_HANDLE *phKey, PUCHAR pbInput, ULONG cbInput, ULONG dwFlags); NTSTATUS BCryptImportKey(BCRYPT_ALG_HANDLE hAlgorithm, BCRYPT_KEY_HANDLE hImportKey, LPCWSTR pszBlobType, BCRYPT_KEY_HANDLE *phKey, PUCHAR pbKeyObject, ULONG cbKeyObject, PUCHAR pbInput, ULONG cbInput, ULONG dwFlags); NTSTATUS BCryptDestroyKey(BCRYPT_KEY_HANDLE hKey); NTSTATUS BCryptVerifySignature(BCRYPT_KEY_HANDLE hKey, void *pPaddingInfo, PUCHAR pbHash, ULONG cbHash, PUCHAR pbSignature, ULONG cbSignature, ULONG dwFlags); NTSTATUS BCryptSignHash(BCRYPT_KEY_HANDLE hKey, void * pPaddingInfo, PBYTE pbInput, DWORD cbInput, PBYTE pbOutput, DWORD cbOutput, DWORD *pcbResult, ULONG dwFlags); NTSTATUS BCryptEncrypt(BCRYPT_KEY_HANDLE hKey, PUCHAR pbInput, ULONG cbInput, void *pPaddingInfo, PUCHAR pbIV, ULONG cbIV, PUCHAR pbOutput, ULONG cbOutput, ULONG *pcbResult, ULONG dwFlags); NTSTATUS BCryptDecrypt(BCRYPT_KEY_HANDLE hKey, PUCHAR pbInput, ULONG cbInput, void *pPaddingInfo, PUCHAR pbIV, ULONG cbIV, PUCHAR pbOutput, ULONG cbOutput, ULONG *pcbResult, ULONG dwFlags); NTSTATUS BCryptDeriveKeyPBKDF2(BCRYPT_ALG_HANDLE hPrf, PUCHAR pbPassword, ULONG cbPassword, PUCHAR pbSalt, ULONG cbSalt, ULONGLONG cIterations, PUCHAR pbDerivedKey, ULONG cbDerivedKey, ULONG dwFlags); NTSTATUS BCryptGenRandom(BCRYPT_ALG_HANDLE hAlgorithm, PUCHAR pbBuffer, ULONG cbBuffer, ULONG dwFlags); NTSTATUS BCryptGenerateKeyPair(BCRYPT_ALG_HANDLE hAlgorithm, BCRYPT_KEY_HANDLE *phKey, ULONG dwLength, ULONG dwFlags); NTSTATUS BCryptFinalizeKeyPair(BCRYPT_KEY_HANDLE hKey, ULONG dwFlags); NTSTATUS BCryptExportKey(BCRYPT_KEY_HANDLE hKey, BCRYPT_KEY_HANDLE hExportKey, LPCWSTR pszBlobType, PUCHAR pbOutput, ULONG cbOutput, ULONG *pcbResult, ULONG dwFlags); """) try: bcrypt = ffi.dlopen('bcrypt.dll') register_ffi(bcrypt, ffi) except (OSError) as e: if str_cls(e).find('cannot load library') != -1: raise LibraryNotFoundError('bcrypt.dll could not be found - Windows XP and Server 2003 are not supported') raise PK!  _cng_ctypes.pynu[# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function from ctypes import windll, wintypes, POINTER, Structure, c_void_p, c_ulonglong, c_char_p, c_byte from ctypes.wintypes import ULONG, DWORD, LPCWSTR from .._ffi import FFIEngineError from .._types import str_cls from ..errors import LibraryNotFoundError __all__ = [ 'bcrypt', ] try: bcrypt = windll.bcrypt except (OSError) as e: if str_cls(e).find('The specified module could not be found') != -1: raise LibraryNotFoundError('bcrypt.dll could not be found - Windows XP and Server 2003 are not supported') raise BCRYPT_ALG_HANDLE = wintypes.HANDLE BCRYPT_KEY_HANDLE = wintypes.HANDLE NTSTATUS = wintypes.ULONG PUCHAR = c_char_p PBYTE = c_char_p try: bcrypt.BCryptOpenAlgorithmProvider.argtypes = [ POINTER(BCRYPT_ALG_HANDLE), LPCWSTR, LPCWSTR, DWORD ] bcrypt.BCryptOpenAlgorithmProvider.restype = NTSTATUS bcrypt.BCryptCloseAlgorithmProvider.argtypes = [ BCRYPT_ALG_HANDLE, ULONG ] bcrypt.BCryptCloseAlgorithmProvider.restype = NTSTATUS bcrypt.BCryptImportKeyPair.argtypes = [ BCRYPT_ALG_HANDLE, BCRYPT_KEY_HANDLE, LPCWSTR, POINTER(BCRYPT_KEY_HANDLE), PUCHAR, ULONG, ULONG ] bcrypt.BCryptImportKeyPair.restype = NTSTATUS bcrypt.BCryptImportKey.argtypes = [ BCRYPT_ALG_HANDLE, BCRYPT_KEY_HANDLE, LPCWSTR, POINTER(BCRYPT_KEY_HANDLE), PUCHAR, ULONG, PUCHAR, ULONG, ULONG ] bcrypt.BCryptImportKey.restype = NTSTATUS bcrypt.BCryptDestroyKey.argtypes = [ BCRYPT_KEY_HANDLE ] bcrypt.BCryptDestroyKey.restype = NTSTATUS bcrypt.BCryptVerifySignature.argtypes = [ BCRYPT_KEY_HANDLE, c_void_p, PUCHAR, ULONG, PUCHAR, ULONG, ULONG ] bcrypt.BCryptVerifySignature.restype = NTSTATUS bcrypt.BCryptSignHash.argtypes = [ BCRYPT_KEY_HANDLE, c_void_p, PBYTE, DWORD, PBYTE, DWORD, POINTER(DWORD), ULONG ] bcrypt.BCryptSignHash.restype = NTSTATUS bcrypt.BCryptSetProperty.argtypes = [ BCRYPT_KEY_HANDLE, LPCWSTR, c_void_p, ULONG, ULONG ] bcrypt.BCryptSetProperty.restype = NTSTATUS bcrypt.BCryptEncrypt.argtypes = [ BCRYPT_KEY_HANDLE, PUCHAR, ULONG, c_void_p, PUCHAR, ULONG, PUCHAR, ULONG, POINTER(ULONG), ULONG ] bcrypt.BCryptEncrypt.restype = NTSTATUS bcrypt.BCryptDecrypt.argtypes = [ BCRYPT_KEY_HANDLE, PUCHAR, ULONG, c_void_p, PUCHAR, ULONG, PUCHAR, ULONG, POINTER(ULONG), ULONG ] bcrypt.BCryptDecrypt.restype = NTSTATUS bcrypt.BCryptDeriveKeyPBKDF2.argtypes = [ BCRYPT_ALG_HANDLE, PUCHAR, ULONG, PUCHAR, ULONG, c_ulonglong, PUCHAR, ULONG, ULONG ] bcrypt.BCryptDeriveKeyPBKDF2.restype = NTSTATUS bcrypt.BCryptGenRandom.argtypes = [ BCRYPT_ALG_HANDLE, PUCHAR, ULONG, ULONG ] bcrypt.BCryptGenRandom.restype = NTSTATUS bcrypt.BCryptGenerateKeyPair.argtypes = [ BCRYPT_ALG_HANDLE, POINTER(BCRYPT_KEY_HANDLE), ULONG, ULONG ] bcrypt.BCryptGenerateKeyPair.restype = NTSTATUS bcrypt.BCryptFinalizeKeyPair.argtypes = [ BCRYPT_KEY_HANDLE, ULONG ] bcrypt.BCryptFinalizeKeyPair.restype = NTSTATUS bcrypt.BCryptExportKey.argtypes = [ BCRYPT_KEY_HANDLE, BCRYPT_KEY_HANDLE, LPCWSTR, PUCHAR, ULONG, POINTER(ULONG), ULONG ] bcrypt.BCryptExportKey.restype = NTSTATUS except (AttributeError): raise FFIEngineError('Error initializing ctypes') class BCRYPT_RSAKEY_BLOB(Structure): # noqa _fields_ = [ ('Magic', ULONG), ('BitLength', ULONG), ('cbPublicExp', ULONG), ('cbModulus', ULONG), ('cbPrime1', ULONG), ('cbPrime2', ULONG), ] class BCRYPT_DSA_KEY_BLOB(Structure): # noqa _fields_ = [ ('dwMagic', ULONG), ('cbKey', ULONG), ('Count', c_byte * 4), ('Seed', c_byte * 20), ('q', c_byte * 20), ] class BCRYPT_DSA_KEY_BLOB_V2(Structure): # noqa _fields_ = [ ('dwMagic', ULONG), ('cbKey', ULONG), ('hashAlgorithm', wintypes.INT), ('standardVersion', wintypes.INT), ('cbSeedLength', ULONG), ('cbGroupSize', ULONG), ('Count', c_byte * 4), ] class BCRYPT_ECCKEY_BLOB(Structure): # noqa _fields_ = [ ('dwMagic', ULONG), ('cbKey', ULONG), ] class BCRYPT_PKCS1_PADDING_INFO(Structure): # noqa _fields_ = [ ('pszAlgId', LPCWSTR), ] class BCRYPT_PSS_PADDING_INFO(Structure): # noqa _fields_ = [ ('pszAlgId', LPCWSTR), ('cbSalt', ULONG), ] class BCRYPT_OAEP_PADDING_INFO(Structure): # noqa _fields_ = [ ('pszAlgId', LPCWSTR), ('pbLabel', PUCHAR), ('cbLabel', ULONG), ] class BCRYPT_KEY_DATA_BLOB_HEADER(Structure): # noqa _fields_ = [ ('dwMagic', ULONG), ('dwVersion', ULONG), ('cbKeyData', ULONG), ] setattr(bcrypt, 'BCRYPT_ALG_HANDLE', BCRYPT_ALG_HANDLE) setattr(bcrypt, 'BCRYPT_KEY_HANDLE', BCRYPT_KEY_HANDLE) setattr(bcrypt, 'BCRYPT_RSAKEY_BLOB', BCRYPT_RSAKEY_BLOB) setattr(bcrypt, 'BCRYPT_DSA_KEY_BLOB', BCRYPT_DSA_KEY_BLOB) setattr(bcrypt, 'BCRYPT_DSA_KEY_BLOB_V2', BCRYPT_DSA_KEY_BLOB_V2) setattr(bcrypt, 'BCRYPT_ECCKEY_BLOB', BCRYPT_ECCKEY_BLOB) setattr(bcrypt, 'BCRYPT_PKCS1_PADDING_INFO', BCRYPT_PKCS1_PADDING_INFO) setattr(bcrypt, 'BCRYPT_PSS_PADDING_INFO', BCRYPT_PSS_PADDING_INFO) setattr(bcrypt, 'BCRYPT_OAEP_PADDING_INFO', BCRYPT_OAEP_PADDING_INFO) setattr(bcrypt, 'BCRYPT_KEY_DATA_BLOB_HEADER', BCRYPT_KEY_DATA_BLOB_HEADER) PK!*ii _crypt32.pynu[# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function from .. import ffi from ._decode import _try_decode from .._ffi import buffer_from_bytes from .._types import str_cls if ffi() == 'cffi': from ._crypt32_cffi import crypt32, get_error else: from ._crypt32_ctypes import crypt32, get_error __all__ = [ 'crypt32', 'Crypt32Const', 'handle_error', ] def handle_error(result): """ Extracts the last Windows error message into a python unicode string :param result: A function result, 0 or None indicates failure :return: A unicode string error message """ if result: return _, error_string = get_error() if not isinstance(error_string, str_cls): error_string = _try_decode(error_string) raise OSError(error_string) class Crypt32Const(): X509_ASN_ENCODING = 1 ERROR_INSUFFICIENT_BUFFER = 122 CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG = 0x4 CRYPT_E_NOT_FOUND = -2146885628 CERT_STORE_PROV_MEMORY = b'Memory' CERT_STORE_CREATE_NEW_FLAG = 0x00002000 CERT_STORE_ADD_USE_EXISTING = 2 USAGE_MATCH_TYPE_OR = 1 CERT_CHAIN_POLICY_SSL = 4 AUTHTYPE_SERVER = 2 CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG = 0x00000010 CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS = 0x00000F00 CERT_CHAIN_CACHE_END_CERT = 1 CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY = 0x80000000 TRUST_E_CERT_SIGNATURE = 0x80096004 CERT_E_EXPIRED = 0x800B0101 CERT_E_ROLE = 0x800B0103 CERT_E_PURPOSE = 0x800B0106 CERT_E_UNTRUSTEDROOT = 0x800B0109 CERT_E_CN_NO_MATCH = 0x800B010F CRYPT_E_REVOKED = 0x80092010 PKIX_KP_SERVER_AUTH = buffer_from_bytes(b"1.3.6.1.5.5.7.3.1\x00") SERVER_GATED_CRYPTO = buffer_from_bytes(b"1.3.6.1.4.1.311.10.3.3\x00") SGC_NETSCAPE = buffer_from_bytes(b"2.16.840.1.113730.4.1\x00") PK!Ί  _crypt32_cffi.pynu[# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import sys from .._ffi import register_ffi from .._types import str_cls from ..errors import LibraryNotFoundError import cffi __all__ = [ 'crypt32', 'get_error', ] ffi = cffi.FFI() if cffi.__version_info__ >= (0, 9): ffi.set_unicode(True) if sys.maxsize > 2 ** 32: ffi.cdef("typedef uint64_t ULONG_PTR;") else: ffi.cdef("typedef unsigned long ULONG_PTR;") ffi.cdef(""" typedef HANDLE HCERTSTORE; typedef unsigned char *PBYTE; typedef struct _CRYPTOAPI_BLOB { DWORD cbData; PBYTE pbData; } CRYPTOAPI_BLOB; typedef CRYPTOAPI_BLOB CRYPT_INTEGER_BLOB; typedef CRYPTOAPI_BLOB CERT_NAME_BLOB; typedef CRYPTOAPI_BLOB CRYPT_BIT_BLOB; typedef CRYPTOAPI_BLOB CRYPT_OBJID_BLOB; typedef struct _CRYPT_ALGORITHM_IDENTIFIER { LPSTR pszObjId; CRYPT_OBJID_BLOB Parameters; } CRYPT_ALGORITHM_IDENTIFIER; typedef struct _FILETIME { DWORD dwLowDateTime; DWORD dwHighDateTime; } FILETIME; typedef struct _CERT_PUBLIC_KEY_INFO { CRYPT_ALGORITHM_IDENTIFIER Algorithm; CRYPT_BIT_BLOB PublicKey; } CERT_PUBLIC_KEY_INFO; typedef struct _CERT_EXTENSION { LPSTR pszObjId; BOOL fCritical; CRYPT_OBJID_BLOB Value; } CERT_EXTENSION, *PCERT_EXTENSION; typedef struct _CERT_INFO { DWORD dwVersion; CRYPT_INTEGER_BLOB SerialNumber; CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm; CERT_NAME_BLOB Issuer; FILETIME NotBefore; FILETIME NotAfter; CERT_NAME_BLOB Subject; CERT_PUBLIC_KEY_INFO SubjectPublicKeyInfo; CRYPT_BIT_BLOB IssuerUniqueId; CRYPT_BIT_BLOB SubjectUniqueId; DWORD cExtension; PCERT_EXTENSION *rgExtension; } CERT_INFO, *PCERT_INFO; typedef struct _CERT_CONTEXT { DWORD dwCertEncodingType; PBYTE pbCertEncoded; DWORD cbCertEncoded; PCERT_INFO pCertInfo; HCERTSTORE hCertStore; } CERT_CONTEXT, *PCERT_CONTEXT; typedef struct _CERT_TRUST_STATUS { DWORD dwErrorStatus; DWORD dwInfoStatus; } CERT_TRUST_STATUS, *PCERT_TRUST_STATUS; typedef struct _CERT_ENHKEY_USAGE { DWORD cUsageIdentifier; LPSTR *rgpszUsageIdentifier; } CERT_ENHKEY_USAGE, *PCERT_ENHKEY_USAGE; typedef struct _CERT_CHAIN_ELEMENT { DWORD cbSize; PCERT_CONTEXT pCertContext; CERT_TRUST_STATUS TrustStatus; void *pRevocationInfo; PCERT_ENHKEY_USAGE pIssuanceUsage; PCERT_ENHKEY_USAGE pApplicationUsage; LPCWSTR pwszExtendedErrorInfo; } CERT_CHAIN_ELEMENT, *PCERT_CHAIN_ELEMENT; typedef struct _CERT_SIMPLE_CHAIN { DWORD cbSize; CERT_TRUST_STATUS TrustStatus; DWORD cElement; PCERT_CHAIN_ELEMENT *rgpElement; void *pTrustListInfo; BOOL fHasRevocationFreshnessTime; DWORD dwRevocationFreshnessTime; } CERT_SIMPLE_CHAIN, *PCERT_SIMPLE_CHAIN; typedef struct _CERT_CHAIN_CONTEXT { DWORD cbSize; CERT_TRUST_STATUS TrustStatus; DWORD cChain; PCERT_SIMPLE_CHAIN *rgpChain; DWORD cLowerQualityChainContext; void *rgpLowerQualityChainContext; BOOL fHasRevocationFreshnessTime; DWORD dwRevocationFreshnessTime; } CERT_CHAIN_CONTEXT, *PCERT_CHAIN_CONTEXT; typedef struct _CERT_USAGE_MATCH { DWORD dwType; CERT_ENHKEY_USAGE Usage; } CERT_USAGE_MATCH; typedef struct _CERT_CHAIN_PARA { DWORD cbSize; CERT_USAGE_MATCH RequestedUsage; } CERT_CHAIN_PARA; typedef struct _CERT_CHAIN_POLICY_PARA { DWORD cbSize; DWORD dwFlags; void *pvExtraPolicyPara; } CERT_CHAIN_POLICY_PARA; typedef struct _HTTPSPolicyCallbackData { DWORD cbSize; DWORD dwAuthType; DWORD fdwChecks; WCHAR *pwszServerName; } SSL_EXTRA_CERT_CHAIN_POLICY_PARA; typedef struct _CERT_CHAIN_POLICY_STATUS { DWORD cbSize; DWORD dwError; LONG lChainIndex; LONG lElementIndex; void *pvExtraPolicyStatus; } CERT_CHAIN_POLICY_STATUS; typedef HANDLE HCERTCHAINENGINE; typedef HANDLE HCRYPTPROV; HCERTSTORE CertOpenStore(LPCSTR lpszStoreProvider, DWORD dwMsgAndCertEncodingType, HCRYPTPROV hCryptProv, DWORD dwFlags, void *pvPara); BOOL CertAddEncodedCertificateToStore(HCERTSTORE hCertStore, DWORD dwCertEncodingType, BYTE *pbCertEncoded, DWORD cbCertEncoded, DWORD dwAddDisposition, PCERT_CONTEXT *ppCertContext); BOOL CertGetCertificateChain(HCERTCHAINENGINE hChainEngine, CERT_CONTEXT *pCertContext, FILETIME *pTime, HCERTSTORE hAdditionalStore, CERT_CHAIN_PARA *pChainPara, DWORD dwFlags, void *pvReserved, PCERT_CHAIN_CONTEXT *ppChainContext); BOOL CertVerifyCertificateChainPolicy(ULONG_PTR pszPolicyOID, PCERT_CHAIN_CONTEXT pChainContext, CERT_CHAIN_POLICY_PARA *pPolicyPara, CERT_CHAIN_POLICY_STATUS *pPolicyStatus); void CertFreeCertificateChain(PCERT_CHAIN_CONTEXT pChainContext); HCERTSTORE CertOpenSystemStoreW(HANDLE hprov, LPCWSTR szSubsystemProtocol); PCERT_CONTEXT CertEnumCertificatesInStore(HCERTSTORE hCertStore, CERT_CONTEXT *pPrevCertContext); BOOL CertCloseStore(HCERTSTORE hCertStore, DWORD dwFlags); BOOL CertGetEnhancedKeyUsage(CERT_CONTEXT *pCertContext, DWORD dwFlags, CERT_ENHKEY_USAGE *pUsage, DWORD *pcbUsage); """) try: crypt32 = ffi.dlopen('crypt32.dll') register_ffi(crypt32, ffi) except (OSError) as e: if str_cls(e).find('cannot load library') != -1: raise LibraryNotFoundError('crypt32.dll could not be found') raise def get_error(): return ffi.getwinerror() PK!3H&  _crypt32_ctypes.pynu[# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import sys import ctypes from ctypes import windll, wintypes, POINTER, Structure, c_void_p, c_char_p from ctypes.wintypes import DWORD from .._ffi import FFIEngineError from .._types import str_cls from ..errors import LibraryNotFoundError from ._kernel32 import kernel32 __all__ = [ 'crypt32', 'get_error', ] try: crypt32 = windll.crypt32 except (OSError) as e: if str_cls(e).find('The specified module could not be found') != -1: raise LibraryNotFoundError('crypt32.dll could not be found') raise HCERTSTORE = wintypes.HANDLE HCERTCHAINENGINE = wintypes.HANDLE HCRYPTPROV = wintypes.HANDLE HCRYPTKEY = wintypes.HANDLE PBYTE = c_char_p if sys.maxsize > 2 ** 32: ULONG_PTR = ctypes.c_uint64 else: ULONG_PTR = ctypes.c_ulong try: class CRYPTOAPI_BLOB(Structure): # noqa _fields_ = [ ("cbData", DWORD), ("pbData", c_void_p), ] CRYPT_INTEGER_BLOB = CRYPTOAPI_BLOB CERT_NAME_BLOB = CRYPTOAPI_BLOB CRYPT_BIT_BLOB = CRYPTOAPI_BLOB CRYPT_OBJID_BLOB = CRYPTOAPI_BLOB class CRYPT_ALGORITHM_IDENTIFIER(Structure): # noqa _fields_ = [ ("pszObjId", wintypes.LPSTR), ("Parameters", CRYPT_OBJID_BLOB), ] class CERT_PUBLIC_KEY_INFO(Structure): # noqa _fields_ = [ ("Algorithm", CRYPT_ALGORITHM_IDENTIFIER), ("PublicKey", CRYPT_BIT_BLOB), ] class CERT_EXTENSION(Structure): # noqa _fields_ = [ ("pszObjId", wintypes.LPSTR), ("fCritical", wintypes.BOOL), ("Value", CRYPT_OBJID_BLOB), ] PCERT_EXTENSION = POINTER(CERT_EXTENSION) class CERT_INFO(Structure): # noqa _fields_ = [ ("dwVersion", DWORD), ("SerialNumber", CRYPT_INTEGER_BLOB), ("SignatureAlgorithm", CRYPT_ALGORITHM_IDENTIFIER), ("Issuer", CERT_NAME_BLOB), ("NotBefore", kernel32.FILETIME), ("NotAfter", kernel32.FILETIME), ("Subject", CERT_NAME_BLOB), ("SubjectPublicKeyInfo", CERT_PUBLIC_KEY_INFO), ("IssuerUniqueId", CRYPT_BIT_BLOB), ("SubjectUniqueId", CRYPT_BIT_BLOB), ("cExtension", DWORD), ("rgExtension", POINTER(PCERT_EXTENSION)), ] PCERT_INFO = POINTER(CERT_INFO) class CERT_CONTEXT(Structure): # noqa _fields_ = [ ("dwCertEncodingType", DWORD), ("pbCertEncoded", c_void_p), ("cbCertEncoded", DWORD), ("pCertInfo", PCERT_INFO), ("hCertStore", HCERTSTORE) ] PCERT_CONTEXT = POINTER(CERT_CONTEXT) class CERT_ENHKEY_USAGE(Structure): # noqa _fields_ = [ ('cUsageIdentifier', DWORD), ('rgpszUsageIdentifier', POINTER(POINTER(wintypes.BYTE))), ] PCERT_ENHKEY_USAGE = POINTER(CERT_ENHKEY_USAGE) class CERT_TRUST_STATUS(Structure): # noqa _fields_ = [ ('dwErrorStatus', DWORD), ('dwInfoStatus', DWORD), ] class CERT_CHAIN_ELEMENT(Structure): # noqa _fields_ = [ ('cbSize', DWORD), ('pCertContext', PCERT_CONTEXT), ('TrustStatus', CERT_TRUST_STATUS), ('pRevocationInfo', c_void_p), ('pIssuanceUsage', PCERT_ENHKEY_USAGE), ('pApplicationUsage', PCERT_ENHKEY_USAGE), ('pwszExtendedErrorInfo', wintypes.LPCWSTR), ] PCERT_CHAIN_ELEMENT = POINTER(CERT_CHAIN_ELEMENT) class CERT_SIMPLE_CHAIN(Structure): # noqa _fields_ = [ ('cbSize', DWORD), ('TrustStatus', CERT_TRUST_STATUS), ('cElement', DWORD), ('rgpElement', POINTER(PCERT_CHAIN_ELEMENT)), ('pTrustListInfo', c_void_p), ('fHasRevocationFreshnessTime', wintypes.BOOL), ('dwRevocationFreshnessTime', DWORD), ] PCERT_SIMPLE_CHAIN = POINTER(CERT_SIMPLE_CHAIN) class CERT_CHAIN_CONTEXT(Structure): # noqa _fields_ = [ ('cbSize', DWORD), ('TrustStatus', CERT_TRUST_STATUS), ('cChain', DWORD), ('rgpChain', POINTER(PCERT_SIMPLE_CHAIN)), ('cLowerQualityChainContext', DWORD), ('rgpLowerQualityChainContext', c_void_p), ('fHasRevocationFreshnessTime', wintypes.BOOL), ('dwRevocationFreshnessTime', DWORD), ] PCERT_CHAIN_CONTEXT = POINTER(CERT_CHAIN_CONTEXT) class CERT_USAGE_MATCH(Structure): # noqa _fields_ = [ ('dwType', DWORD), ('Usage', CERT_ENHKEY_USAGE), ] class CERT_CHAIN_PARA(Structure): # noqa _fields_ = [ ('cbSize', DWORD), ('RequestedUsage', CERT_USAGE_MATCH), ] class CERT_CHAIN_POLICY_PARA(Structure): # noqa _fields_ = [ ('cbSize', DWORD), ('dwFlags', DWORD), ('pvExtraPolicyPara', c_void_p), ] class SSL_EXTRA_CERT_CHAIN_POLICY_PARA(Structure): # noqa _fields_ = [ ('cbSize', DWORD), ('dwAuthType', DWORD), ('fdwChecks', DWORD), ('pwszServerName', wintypes.LPCWSTR), ] class CERT_CHAIN_POLICY_STATUS(Structure): # noqa _fields_ = [ ('cbSize', DWORD), ('dwError', DWORD), ('lChainIndex', wintypes.LONG), ('lElementIndex', wintypes.LONG), ('pvExtraPolicyStatus', c_void_p), ] crypt32.CertOpenStore.argtypes = [ wintypes.LPCSTR, DWORD, HCRYPTPROV, DWORD, c_void_p ] crypt32.CertOpenStore.restype = HCERTSTORE crypt32.CertAddEncodedCertificateToStore.argtypes = [ HCERTSTORE, DWORD, PBYTE, DWORD, DWORD, POINTER(PCERT_CONTEXT) ] crypt32.CertAddEncodedCertificateToStore.restype = wintypes.BOOL crypt32.CertGetCertificateChain.argtypes = [ HCERTCHAINENGINE, PCERT_CONTEXT, POINTER(kernel32.FILETIME), HCERTSTORE, POINTER(CERT_CHAIN_PARA), DWORD, c_void_p, POINTER(PCERT_CHAIN_CONTEXT) ] crypt32.CertGetCertificateChain.restype = wintypes.BOOL crypt32.CertVerifyCertificateChainPolicy.argtypes = [ ULONG_PTR, PCERT_CHAIN_CONTEXT, POINTER(CERT_CHAIN_POLICY_PARA), POINTER(CERT_CHAIN_POLICY_STATUS) ] crypt32.CertVerifyCertificateChainPolicy.restype = wintypes.BOOL crypt32.CertFreeCertificateChain.argtypes = [ PCERT_CHAIN_CONTEXT ] crypt32.CertFreeCertificateChain.restype = None crypt32.CertOpenSystemStoreW.argtypes = [ wintypes.HANDLE, wintypes.LPCWSTR ] crypt32.CertOpenSystemStoreW.restype = HCERTSTORE crypt32.CertEnumCertificatesInStore.argtypes = [ HCERTSTORE, PCERT_CONTEXT ] crypt32.CertEnumCertificatesInStore.restype = PCERT_CONTEXT crypt32.CertCloseStore.argtypes = [ HCERTSTORE, DWORD ] crypt32.CertCloseStore.restype = wintypes.BOOL crypt32.CertGetEnhancedKeyUsage.argtypes = [ PCERT_CONTEXT, DWORD, c_void_p, POINTER(DWORD) ] crypt32.CertGetEnhancedKeyUsage.restype = wintypes.BOOL except (AttributeError): raise FFIEngineError('Error initializing ctypes') setattr(crypt32, 'FILETIME', kernel32.FILETIME) setattr(crypt32, 'CERT_ENHKEY_USAGE', CERT_ENHKEY_USAGE) setattr(crypt32, 'CERT_CONTEXT', CERT_CONTEXT) setattr(crypt32, 'PCERT_CONTEXT', PCERT_CONTEXT) setattr(crypt32, 'CERT_USAGE_MATCH', CERT_USAGE_MATCH) setattr(crypt32, 'CERT_CHAIN_PARA', CERT_CHAIN_PARA) setattr(crypt32, 'CERT_CHAIN_POLICY_PARA', CERT_CHAIN_POLICY_PARA) setattr(crypt32, 'SSL_EXTRA_CERT_CHAIN_POLICY_PARA', SSL_EXTRA_CERT_CHAIN_POLICY_PARA) setattr(crypt32, 'CERT_CHAIN_POLICY_STATUS', CERT_CHAIN_POLICY_STATUS) setattr(crypt32, 'PCERT_CHAIN_CONTEXT', PCERT_CHAIN_CONTEXT) def get_error(): error = ctypes.GetLastError() return (error, ctypes.FormatError(error)) PK!m? _decode.pynu[# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import locale from .._types import str_cls _encoding = locale.getpreferredencoding() _fallback_encodings = ['utf-8', 'cp1252'] def _try_decode(byte_string): """ Tries decoding a byte string from the OS into a unicode string :param byte_string: A byte string :return: A unicode string """ try: return str_cls(byte_string, _encoding) # If the "correct" encoding did not work, try some defaults, and then just # obliterate characters that we can't seen to decode properly except (UnicodeDecodeError): for encoding in _fallback_encodings: try: return str_cls(byte_string, encoding, errors='strict') except (UnicodeDecodeError): pass return str_cls(byte_string, errors='replace') PK!F8&& _kernel32.pynu[# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function from .. import ffi from ._decode import _try_decode from .._types import str_cls if ffi() == 'cffi': from ._kernel32_cffi import kernel32, get_error else: from ._kernel32_ctypes import kernel32, get_error __all__ = [ 'handle_error', 'kernel32', ] def handle_error(result): """ Extracts the last Windows error message into a python unicode string :param result: A function result, 0 or None indicates failure :return: A unicode string error message """ if result: return _, error_string = get_error() if not isinstance(error_string, str_cls): error_string = _try_decode(error_string) raise OSError(error_string) PK!Ԇ_kernel32_cffi.pynu[# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function from .._ffi import register_ffi from .._types import str_cls from ..errors import LibraryNotFoundError import cffi __all__ = [ 'get_error', 'kernel32', ] ffi = cffi.FFI() if cffi.__version_info__ >= (0, 9): ffi.set_unicode(True) ffi.cdef(""" typedef long long LARGE_INTEGER; BOOL QueryPerformanceCounter(LARGE_INTEGER *lpPerformanceCount); typedef struct _FILETIME { DWORD dwLowDateTime; DWORD dwHighDateTime; } FILETIME; void GetSystemTimeAsFileTime(FILETIME *lpSystemTimeAsFileTime); """) try: kernel32 = ffi.dlopen('kernel32.dll') register_ffi(kernel32, ffi) except (OSError) as e: if str_cls(e).find('cannot load library') != -1: raise LibraryNotFoundError('kernel32.dll could not be found') raise def get_error(): return ffi.getwinerror() PK!_kernel32_ctypes.pynu[# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import ctypes from ctypes import windll, wintypes, POINTER, c_longlong, Structure from .._ffi import FFIEngineError from .._types import str_cls from ..errors import LibraryNotFoundError __all__ = [ 'get_error', 'kernel32', ] try: kernel32 = windll.kernel32 except (OSError) as e: if str_cls(e).find('The specified module could not be found') != -1: raise LibraryNotFoundError('kernel32.dll could not be found') raise LARGE_INTEGER = c_longlong try: kernel32.QueryPerformanceCounter.argtypes = [POINTER(LARGE_INTEGER)] kernel32.QueryPerformanceCounter.restype = wintypes.BOOL class FILETIME(Structure): _fields_ = [ ("dwLowDateTime", wintypes.DWORD), ("dwHighDateTime", wintypes.DWORD), ] kernel32.GetSystemTimeAsFileTime.argtypes = [POINTER(FILETIME)] kernel32.GetSystemTimeAsFileTime.restype = None except (AttributeError): raise FFIEngineError('Error initializing ctypes') setattr(kernel32, 'LARGE_INTEGER', LARGE_INTEGER) setattr(kernel32, 'FILETIME', FILETIME) def get_error(): error = ctypes.GetLastError() return (error, ctypes.FormatError(error)) PK!H _secur32.pynu[# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function from .. import ffi from ._decode import _try_decode from ..errors import TLSError from .._types import str_cls if ffi() == 'cffi': from ._secur32_cffi import secur32, get_error else: from ._secur32_ctypes import secur32, get_error __all__ = [ 'handle_error', 'secur32', 'Secur32Const', ] def handle_error(result, exception_class=None): """ Extracts the last Windows error message into a python unicode string :param result: A function result, 0 or None indicates failure :param exception_class: The exception class to use for the exception if an error occurred :return: A unicode string error message """ if result == 0: return if result == Secur32Const.SEC_E_OUT_OF_SEQUENCE: raise TLSError('A packet was received out of order') if result == Secur32Const.SEC_E_MESSAGE_ALTERED: raise TLSError('A packet was received altered') if result == Secur32Const.SEC_E_CONTEXT_EXPIRED: raise TLSError('The TLS session expired') _, error_string = get_error() if not isinstance(error_string, str_cls): error_string = _try_decode(error_string) if exception_class is None: exception_class = OSError raise exception_class(('SECURITY_STATUS error 0x%0.2X: ' % result) + error_string) class Secur32Const(): SCHANNEL_CRED_VERSION = 4 SECPKG_CRED_OUTBOUND = 0x00000002 UNISP_NAME = "Microsoft Unified Security Protocol Provider" SCH_CRED_MANUAL_CRED_VALIDATION = 0x00000008 SCH_CRED_AUTO_CRED_VALIDATION = 0x00000020 SCH_USE_STRONG_CRYPTO = 0x00400000 SCH_CRED_NO_DEFAULT_CREDS = 0x00000010 SECBUFFER_VERSION = 0 SEC_E_OK = 0x00000000 SEC_I_CONTINUE_NEEDED = 0x00090312 SEC_I_CONTEXT_EXPIRED = 0x00090317 SEC_I_RENEGOTIATE = 0x00090321 SEC_E_INCOMPLETE_MESSAGE = 0x80090318 SEC_E_INVALID_TOKEN = 0x80090308 SEC_E_OUT_OF_SEQUENCE = 0x8009031 SEC_E_MESSAGE_ALTERED = 0x8009030F SEC_E_CONTEXT_EXPIRED = 0x80090317 SEC_E_INVALID_PARAMETER = 0x8009035D SEC_E_WRONG_PRINCIPAL = 0x80090322 # Domain name mismatch SEC_E_UNTRUSTED_ROOT = 0x80090325 SEC_E_CERT_EXPIRED = 0x80090328 SEC_E_ILLEGAL_MESSAGE = 0x80090326 # Handshake error SEC_E_INTERNAL_ERROR = 0x80090304 # Occurs when DH params are too small SEC_E_BUFFER_TOO_SMALL = 0x80090321 SEC_I_INCOMPLETE_CREDENTIALS = 0x00090320 ISC_REQ_REPLAY_DETECT = 4 ISC_REQ_SEQUENCE_DETECT = 8 ISC_REQ_CONFIDENTIALITY = 16 ISC_REQ_ALLOCATE_MEMORY = 256 ISC_REQ_INTEGRITY = 65536 ISC_REQ_STREAM = 0x00008000 ISC_REQ_USE_SUPPLIED_CREDS = 0x00000080 ISC_RET_REPLAY_DETECT = 4 ISC_RET_SEQUENCE_DETECT = 8 ISC_RET_CONFIDENTIALITY = 16 ISC_RET_ALLOCATED_MEMORY = 256 ISC_RET_INTEGRITY = 65536 ISC_RET_STREAM = 0x00008000 SECBUFFER_ALERT = 17 SECBUFFER_STREAM_HEADER = 7 SECBUFFER_STREAM_TRAILER = 6 SECBUFFER_EXTRA = 5 SECBUFFER_TOKEN = 2 SECBUFFER_DATA = 1 SECBUFFER_EMPTY = 0 SECPKG_ATTR_STREAM_SIZES = 0x04 SECPKG_ATTR_CONNECTION_INFO = 0x5A SECPKG_ATTR_REMOTE_CERT_CONTEXT = 0x53 SP_PROT_TLS1_2_CLIENT = 0x800 SP_PROT_TLS1_1_CLIENT = 0x200 SP_PROT_TLS1_CLIENT = 0x80 SP_PROT_SSL3_CLIENT = 0x20 SP_PROT_SSL2_CLIENT = 0x8 CALG_AES_256 = 0x00006610 CALG_AES_128 = 0x0000660E CALG_3DES = 0x00006603 CALG_RC4 = 0x00006801 CALG_RC2 = 0x00006602 CALG_DES = 0x00006601 CALG_MD5 = 0x00008003 CALG_SHA1 = 0x00008004 CALG_SHA256 = 0x0000800C CALG_SHA384 = 0x0000800D CALG_SHA512 = 0x0000800E CALG_DH_SF = 0x0000AA01 CALG_DH_EPHEM = 0x0000AA02 CALG_ECDH = 0x0000AA05 CALG_ECDHE = 0x0000AE06 CALG_RSA_KEYX = 0x0000A400 CALG_RSA_SIGN = 0x00002400 CALG_ECDSA = 0x00002203 CALG_DSS_SIGN = 0x00002200 PK!˗_secur32_cffi.pynu[# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import sys from .._ffi import register_ffi from .._types import str_cls from ..errors import LibraryNotFoundError import cffi __all__ = [ 'get_error', 'secur32', ] ffi = cffi.FFI() if cffi.__version_info__ >= (0, 9): ffi.set_unicode(True) if sys.maxsize > 2 ** 32: ffi.cdef("typedef uint64_t ULONG_PTR;") else: ffi.cdef("typedef unsigned long ULONG_PTR;") ffi.cdef(""" typedef HANDLE HCERTSTORE; typedef unsigned int ALG_ID; typedef WCHAR SEC_WCHAR; typedef unsigned long SECURITY_STATUS; typedef void *LUID; typedef void *SEC_GET_KEY_FN; typedef struct _SecHandle { ULONG_PTR dwLower; ULONG_PTR dwUpper; } SecHandle; typedef SecHandle CredHandle; typedef SecHandle CtxtHandle; typedef struct _SCHANNEL_CRED { DWORD dwVersion; DWORD cCreds; void *paCred; HCERTSTORE hRootStore; DWORD cMappers; void **aphMappers; DWORD cSupportedAlgs; ALG_ID *palgSupportedAlgs; DWORD grbitEnabledProtocols; DWORD dwMinimumCipherStrength; DWORD dwMaximumCipherStrength; DWORD dwSessionLifespan; DWORD dwFlags; DWORD dwCredFormat; } SCHANNEL_CRED; typedef struct _TimeStamp { DWORD dwLowDateTime; DWORD dwHighDateTime; } TimeStamp; typedef struct _SecBuffer { ULONG cbBuffer; ULONG BufferType; BYTE *pvBuffer; } SecBuffer; typedef struct _SecBufferDesc { ULONG ulVersion; ULONG cBuffers; SecBuffer *pBuffers; } SecBufferDesc; typedef struct _SecPkgContext_StreamSizes { ULONG cbHeader; ULONG cbTrailer; ULONG cbMaximumMessage; ULONG cBuffers; ULONG cbBlockSize; } SecPkgContext_StreamSizes; typedef struct _CERT_CONTEXT { DWORD dwCertEncodingType; BYTE *pbCertEncoded; DWORD cbCertEncoded; void *pCertInfo; HCERTSTORE hCertStore; } CERT_CONTEXT; typedef struct _SecPkgContext_ConnectionInfo { DWORD dwProtocol; ALG_ID aiCipher; DWORD dwCipherStrength; ALG_ID aiHash; DWORD dwHashStrength; ALG_ID aiExch; DWORD dwExchStrength; } SecPkgContext_ConnectionInfo; SECURITY_STATUS AcquireCredentialsHandleW(SEC_WCHAR *pszPrincipal, SEC_WCHAR *pszPackage, ULONG fCredentialUse, LUID *pvLogonID, void *pAuthData, SEC_GET_KEY_FN pGetKeyFn, void *pvGetKeyArgument, CredHandle *phCredential, TimeStamp *ptsExpiry); SECURITY_STATUS FreeCredentialsHandle(CredHandle *phCredential); SECURITY_STATUS InitializeSecurityContextW(CredHandle *phCredential, CtxtHandle *phContext, SEC_WCHAR *pszTargetName, ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep, SecBufferDesc *pInput, ULONG Reserved2, CtxtHandle *phNewContext, SecBufferDesc *pOutput, ULONG *pfContextAttr, TimeStamp *ptsExpiry); SECURITY_STATUS FreeContextBuffer(void *pvContextBuffer); SECURITY_STATUS ApplyControlToken(CtxtHandle *phContext, SecBufferDesc *pInput); SECURITY_STATUS DeleteSecurityContext(CtxtHandle *phContext); SECURITY_STATUS QueryContextAttributesW(CtxtHandle *phContext, ULONG ulAttribute, void *pBuffer); SECURITY_STATUS EncryptMessage(CtxtHandle *phContext, ULONG fQOP, SecBufferDesc *pMessage, ULONG MessageSeqNo); SECURITY_STATUS DecryptMessage(CtxtHandle *phContext, SecBufferDesc *pMessage, ULONG MessageSeqNo, ULONG *pfQOP); """) try: secur32 = ffi.dlopen('secur32.dll') register_ffi(secur32, ffi) except (OSError) as e: if str_cls(e).find('cannot load library') != -1: raise LibraryNotFoundError('secur32.dll could not be found') raise def get_error(): return ffi.getwinerror() PK!U]_secur32_ctypes.pynu[# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import sys import ctypes from ctypes import windll, wintypes, POINTER, c_void_p, c_uint, Structure from ctypes.wintypes import DWORD, ULONG from .._ffi import FFIEngineError from .._types import str_cls from ..errors import LibraryNotFoundError __all__ = [ 'get_error', 'secur32', ] try: secur32 = windll.secur32 except (OSError) as e: if str_cls(e).find('The specified module could not be found') != -1: raise LibraryNotFoundError('secur32.dll could not be found') raise HCERTSTORE = wintypes.HANDLE ALG_ID = c_uint if sys.maxsize > 2 ** 32: ULONG_PTR = ctypes.c_uint64 else: ULONG_PTR = ctypes.c_ulong SEC_GET_KEY_FN = c_void_p LUID = c_void_p SECURITY_STATUS = ctypes.c_ulong SEC_WCHAR = wintypes.WCHAR try: class SecHandle(Structure): _fields_ = [ ('dwLower', ULONG_PTR), ('dwUpper', ULONG_PTR), ] CredHandle = SecHandle CtxtHandle = SecHandle class SCHANNEL_CRED(Structure): # noqa _fields_ = [ ('dwVersion', DWORD), ('cCreds', DWORD), ('paCred', c_void_p), ('hRootStore', HCERTSTORE), ('cMappers', DWORD), ('aphMappers', POINTER(c_void_p)), ('cSupportedAlgs', DWORD), ('palgSupportedAlgs', POINTER(ALG_ID)), ('grbitEnabledProtocols', DWORD), ('dwMinimumCipherStrength', DWORD), ('dwMaximumCipherStrength', DWORD), ('dwSessionLifespan', DWORD), ('dwFlags', DWORD), ('dwCredFormat', DWORD), ] class TimeStamp(Structure): _fields_ = [ ('dwLowDateTime', DWORD), ('dwHighDateTime', DWORD), ] class SecBuffer(Structure): _fields_ = [ ('cbBuffer', ULONG), ('BufferType', ULONG), ('pvBuffer', POINTER(ctypes.c_byte)), ] PSecBuffer = POINTER(SecBuffer) class SecBufferDesc(Structure): _fields_ = [ ('ulVersion', ULONG), ('cBuffers', ULONG), ('pBuffers', PSecBuffer), ] class SecPkgContext_StreamSizes(Structure): # noqa _fields_ = [ ('cbHeader', ULONG), ('cbTrailer', ULONG), ('cbMaximumMessage', ULONG), ('cBuffers', ULONG), ('cbBlockSize', ULONG), ] class SecPkgContext_ConnectionInfo(Structure): # noqa _fields_ = [ ('dwProtocol', DWORD), ('aiCipher', ALG_ID), ('dwCipherStrength', DWORD), ('aiHash', ALG_ID), ('dwHashStrength', DWORD), ('aiExch', ALG_ID), ('dwExchStrength', DWORD), ] secur32.AcquireCredentialsHandleW.argtypes = [ POINTER(SEC_WCHAR), POINTER(SEC_WCHAR), ULONG, POINTER(LUID), c_void_p, SEC_GET_KEY_FN, c_void_p, POINTER(CredHandle), POINTER(TimeStamp) ] secur32.AcquireCredentialsHandleW.restype = SECURITY_STATUS secur32.FreeCredentialsHandle.argtypes = [ POINTER(CredHandle) ] secur32.FreeCredentialsHandle.restype = SECURITY_STATUS secur32.InitializeSecurityContextW.argtypes = [ POINTER(CredHandle), POINTER(CtxtHandle), POINTER(SEC_WCHAR), ULONG, ULONG, ULONG, POINTER(SecBufferDesc), ULONG, POINTER(CtxtHandle), POINTER(SecBufferDesc), POINTER(ULONG), POINTER(TimeStamp) ] secur32.InitializeSecurityContextW.restype = SECURITY_STATUS secur32.FreeContextBuffer.argtypes = [ c_void_p ] secur32.FreeContextBuffer.restype = SECURITY_STATUS secur32.ApplyControlToken.argtypes = [ POINTER(CtxtHandle), POINTER(SecBufferDesc) ] secur32.ApplyControlToken.restype = SECURITY_STATUS secur32.DeleteSecurityContext.argtypes = [ POINTER(CtxtHandle) ] secur32.DeleteSecurityContext.restype = SECURITY_STATUS secur32.QueryContextAttributesW.argtypes = [ POINTER(CtxtHandle), ULONG, c_void_p ] secur32.QueryContextAttributesW.restype = SECURITY_STATUS secur32.EncryptMessage.argtypes = [ POINTER(CtxtHandle), ULONG, POINTER(SecBufferDesc), ULONG ] secur32.EncryptMessage.restype = SECURITY_STATUS secur32.DecryptMessage.argtypes = [ POINTER(CtxtHandle), POINTER(SecBufferDesc), ULONG, POINTER(ULONG) ] secur32.DecryptMessage.restype = SECURITY_STATUS except (AttributeError): raise FFIEngineError('Error initializing ctypes') setattr(secur32, 'ALG_ID', ALG_ID) setattr(secur32, 'CredHandle', CredHandle) setattr(secur32, 'CtxtHandle', CtxtHandle) setattr(secur32, 'SecBuffer', SecBuffer) setattr(secur32, 'SecBufferDesc', SecBufferDesc) setattr(secur32, 'SecPkgContext_StreamSizes', SecPkgContext_StreamSizes) setattr(secur32, 'SecPkgContext_ConnectionInfo', SecPkgContext_ConnectionInfo) setattr(secur32, 'SCHANNEL_CRED', SCHANNEL_CRED) def get_error(): error = ctypes.GetLastError() return (error, ctypes.FormatError(error)) PK!tƸ asymmetric.pynu[# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import os import sys import hashlib import random from .._asn1 import ( Certificate as Asn1Certificate, DHParameters, DSAParams, DSASignature, ECDomainParameters, ECPrivateKey, Integer, int_from_bytes, int_to_bytes, PrivateKeyAlgorithm, PrivateKeyInfo, PublicKeyAlgorithm, PublicKeyInfo, RSAPrivateKey, RSAPublicKey, ) from .._asymmetric import ( _CertificateBase, _fingerprint, _parse_pkcs12, _PrivateKeyBase, _PublicKeyBase, _unwrap_private_key_info, parse_certificate, parse_private, parse_public, ) from .._errors import pretty_message from .._ffi import ( buffer_from_bytes, buffer_from_unicode, byte_array, bytes_from_buffer, cast, deref, native, new, null, pointer_set, sizeof, struct, struct_bytes, struct_from_buffer, unwrap, write_to_buffer, ) from .. import backend from .._int import fill_width from ..errors import AsymmetricKeyError, IncompleteAsymmetricKeyError, SignatureError from .._types import type_name, str_cls, byte_cls, int_types from .._pkcs1 import ( add_pkcs1v15_signature_padding, add_pss_padding, raw_rsa_private_crypt, raw_rsa_public_crypt, remove_pkcs1v15_signature_padding, verify_pss_padding, ) from ..util import constant_compare _gwv = sys.getwindowsversion() _win_version_info = (_gwv[0], _gwv[1]) _backend = backend() if _backend == 'winlegacy': from ._advapi32 import advapi32, Advapi32Const, handle_error, open_context_handle, close_context_handle from .._ecdsa import ( ec_generate_pair as _pure_python_ec_generate_pair, ec_compute_public_key_point as _pure_python_ec_compute_public_key_point, ec_public_key_info, ecdsa_sign as _pure_python_ecdsa_sign, ecdsa_verify as _pure_python_ecdsa_verify, ) else: from ._cng import bcrypt, BcryptConst, handle_error, open_alg_handle, close_alg_handle __all__ = [ 'Certificate', 'dsa_sign', 'dsa_verify', 'ecdsa_sign', 'ecdsa_verify', 'generate_pair', 'load_certificate', 'load_pkcs12', 'load_private_key', 'load_public_key', 'parse_pkcs12', 'PrivateKey', 'PublicKey', 'rsa_oaep_decrypt', 'rsa_oaep_encrypt', 'rsa_pkcs1v15_decrypt', 'rsa_pkcs1v15_encrypt', 'rsa_pkcs1v15_sign', 'rsa_pkcs1v15_verify', 'rsa_pss_sign', 'rsa_pss_verify', ] # A list of primes from OpenSSL's bn_prime.h to use when testing primality of a # large integer _SMALL_PRIMES = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003, 5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087, 5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179, 5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279, 5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387, 5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443, 5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521, 5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639, 5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693, 5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791, 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857, 5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939, 5953, 5981, 5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053, 6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133, 6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221, 6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287, 6299, 6301, 6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367, 6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473, 6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571, 6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661, 6673, 6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761, 6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833, 6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917, 6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997, 7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103, 7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207, 7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297, 7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369, 7393, 7411, 7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499, 7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561, 7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643, 7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717, 7723, 7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829, 7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919, 7927, 7933, 7937, 7949, 7951, 7963, 7993, 8009, 8011, 8017, 8039, 8053, 8059, 8069, 8081, 8087, 8089, 8093, 8101, 8111, 8117, 8123, 8147, 8161, 8167, 8171, 8179, 8191, 8209, 8219, 8221, 8231, 8233, 8237, 8243, 8263, 8269, 8273, 8287, 8291, 8293, 8297, 8311, 8317, 8329, 8353, 8363, 8369, 8377, 8387, 8389, 8419, 8423, 8429, 8431, 8443, 8447, 8461, 8467, 8501, 8513, 8521, 8527, 8537, 8539, 8543, 8563, 8573, 8581, 8597, 8599, 8609, 8623, 8627, 8629, 8641, 8647, 8663, 8669, 8677, 8681, 8689, 8693, 8699, 8707, 8713, 8719, 8731, 8737, 8741, 8747, 8753, 8761, 8779, 8783, 8803, 8807, 8819, 8821, 8831, 8837, 8839, 8849, 8861, 8863, 8867, 8887, 8893, 8923, 8929, 8933, 8941, 8951, 8963, 8969, 8971, 8999, 9001, 9007, 9011, 9013, 9029, 9041, 9043, 9049, 9059, 9067, 9091, 9103, 9109, 9127, 9133, 9137, 9151, 9157, 9161, 9173, 9181, 9187, 9199, 9203, 9209, 9221, 9227, 9239, 9241, 9257, 9277, 9281, 9283, 9293, 9311, 9319, 9323, 9337, 9341, 9343, 9349, 9371, 9377, 9391, 9397, 9403, 9413, 9419, 9421, 9431, 9433, 9437, 9439, 9461, 9463, 9467, 9473, 9479, 9491, 9497, 9511, 9521, 9533, 9539, 9547, 9551, 9587, 9601, 9613, 9619, 9623, 9629, 9631, 9643, 9649, 9661, 9677, 9679, 9689, 9697, 9719, 9721, 9733, 9739, 9743, 9749, 9767, 9769, 9781, 9787, 9791, 9803, 9811, 9817, 9829, 9833, 9839, 9851, 9857, 9859, 9871, 9883, 9887, 9901, 9907, 9923, 9929, 9931, 9941, 9949, 9967, 9973, 10007, 10009, 10037, 10039, 10061, 10067, 10069, 10079, 10091, 10093, 10099, 10103, 10111, 10133, 10139, 10141, 10151, 10159, 10163, 10169, 10177, 10181, 10193, 10211, 10223, 10243, 10247, 10253, 10259, 10267, 10271, 10273, 10289, 10301, 10303, 10313, 10321, 10331, 10333, 10337, 10343, 10357, 10369, 10391, 10399, 10427, 10429, 10433, 10453, 10457, 10459, 10463, 10477, 10487, 10499, 10501, 10513, 10529, 10531, 10559, 10567, 10589, 10597, 10601, 10607, 10613, 10627, 10631, 10639, 10651, 10657, 10663, 10667, 10687, 10691, 10709, 10711, 10723, 10729, 10733, 10739, 10753, 10771, 10781, 10789, 10799, 10831, 10837, 10847, 10853, 10859, 10861, 10867, 10883, 10889, 10891, 10903, 10909, 10937, 10939, 10949, 10957, 10973, 10979, 10987, 10993, 11003, 11027, 11047, 11057, 11059, 11069, 11071, 11083, 11087, 11093, 11113, 11117, 11119, 11131, 11149, 11159, 11161, 11171, 11173, 11177, 11197, 11213, 11239, 11243, 11251, 11257, 11261, 11273, 11279, 11287, 11299, 11311, 11317, 11321, 11329, 11351, 11353, 11369, 11383, 11393, 11399, 11411, 11423, 11437, 11443, 11447, 11467, 11471, 11483, 11489, 11491, 11497, 11503, 11519, 11527, 11549, 11551, 11579, 11587, 11593, 11597, 11617, 11621, 11633, 11657, 11677, 11681, 11689, 11699, 11701, 11717, 11719, 11731, 11743, 11777, 11779, 11783, 11789, 11801, 11807, 11813, 11821, 11827, 11831, 11833, 11839, 11863, 11867, 11887, 11897, 11903, 11909, 11923, 11927, 11933, 11939, 11941, 11953, 11959, 11969, 11971, 11981, 11987, 12007, 12011, 12037, 12041, 12043, 12049, 12071, 12073, 12097, 12101, 12107, 12109, 12113, 12119, 12143, 12149, 12157, 12161, 12163, 12197, 12203, 12211, 12227, 12239, 12241, 12251, 12253, 12263, 12269, 12277, 12281, 12289, 12301, 12323, 12329, 12343, 12347, 12373, 12377, 12379, 12391, 12401, 12409, 12413, 12421, 12433, 12437, 12451, 12457, 12473, 12479, 12487, 12491, 12497, 12503, 12511, 12517, 12527, 12539, 12541, 12547, 12553, 12569, 12577, 12583, 12589, 12601, 12611, 12613, 12619, 12637, 12641, 12647, 12653, 12659, 12671, 12689, 12697, 12703, 12713, 12721, 12739, 12743, 12757, 12763, 12781, 12791, 12799, 12809, 12821, 12823, 12829, 12841, 12853, 12889, 12893, 12899, 12907, 12911, 12917, 12919, 12923, 12941, 12953, 12959, 12967, 12973, 12979, 12983, 13001, 13003, 13007, 13009, 13033, 13037, 13043, 13049, 13063, 13093, 13099, 13103, 13109, 13121, 13127, 13147, 13151, 13159, 13163, 13171, 13177, 13183, 13187, 13217, 13219, 13229, 13241, 13249, 13259, 13267, 13291, 13297, 13309, 13313, 13327, 13331, 13337, 13339, 13367, 13381, 13397, 13399, 13411, 13417, 13421, 13441, 13451, 13457, 13463, 13469, 13477, 13487, 13499, 13513, 13523, 13537, 13553, 13567, 13577, 13591, 13597, 13613, 13619, 13627, 13633, 13649, 13669, 13679, 13681, 13687, 13691, 13693, 13697, 13709, 13711, 13721, 13723, 13729, 13751, 13757, 13759, 13763, 13781, 13789, 13799, 13807, 13829, 13831, 13841, 13859, 13873, 13877, 13879, 13883, 13901, 13903, 13907, 13913, 13921, 13931, 13933, 13963, 13967, 13997, 13999, 14009, 14011, 14029, 14033, 14051, 14057, 14071, 14081, 14083, 14087, 14107, 14143, 14149, 14153, 14159, 14173, 14177, 14197, 14207, 14221, 14243, 14249, 14251, 14281, 14293, 14303, 14321, 14323, 14327, 14341, 14347, 14369, 14387, 14389, 14401, 14407, 14411, 14419, 14423, 14431, 14437, 14447, 14449, 14461, 14479, 14489, 14503, 14519, 14533, 14537, 14543, 14549, 14551, 14557, 14561, 14563, 14591, 14593, 14621, 14627, 14629, 14633, 14639, 14653, 14657, 14669, 14683, 14699, 14713, 14717, 14723, 14731, 14737, 14741, 14747, 14753, 14759, 14767, 14771, 14779, 14783, 14797, 14813, 14821, 14827, 14831, 14843, 14851, 14867, 14869, 14879, 14887, 14891, 14897, 14923, 14929, 14939, 14947, 14951, 14957, 14969, 14983, 15013, 15017, 15031, 15053, 15061, 15073, 15077, 15083, 15091, 15101, 15107, 15121, 15131, 15137, 15139, 15149, 15161, 15173, 15187, 15193, 15199, 15217, 15227, 15233, 15241, 15259, 15263, 15269, 15271, 15277, 15287, 15289, 15299, 15307, 15313, 15319, 15329, 15331, 15349, 15359, 15361, 15373, 15377, 15383, 15391, 15401, 15413, 15427, 15439, 15443, 15451, 15461, 15467, 15473, 15493, 15497, 15511, 15527, 15541, 15551, 15559, 15569, 15581, 15583, 15601, 15607, 15619, 15629, 15641, 15643, 15647, 15649, 15661, 15667, 15671, 15679, 15683, 15727, 15731, 15733, 15737, 15739, 15749, 15761, 15767, 15773, 15787, 15791, 15797, 15803, 15809, 15817, 15823, 15859, 15877, 15881, 15887, 15889, 15901, 15907, 15913, 15919, 15923, 15937, 15959, 15971, 15973, 15991, 16001, 16007, 16033, 16057, 16061, 16063, 16067, 16069, 16073, 16087, 16091, 16097, 16103, 16111, 16127, 16139, 16141, 16183, 16187, 16189, 16193, 16217, 16223, 16229, 16231, 16249, 16253, 16267, 16273, 16301, 16319, 16333, 16339, 16349, 16361, 16363, 16369, 16381, 16411, 16417, 16421, 16427, 16433, 16447, 16451, 16453, 16477, 16481, 16487, 16493, 16519, 16529, 16547, 16553, 16561, 16567, 16573, 16603, 16607, 16619, 16631, 16633, 16649, 16651, 16657, 16661, 16673, 16691, 16693, 16699, 16703, 16729, 16741, 16747, 16759, 16763, 16787, 16811, 16823, 16829, 16831, 16843, 16871, 16879, 16883, 16889, 16901, 16903, 16921, 16927, 16931, 16937, 16943, 16963, 16979, 16981, 16987, 16993, 17011, 17021, 17027, 17029, 17033, 17041, 17047, 17053, 17077, 17093, 17099, 17107, 17117, 17123, 17137, 17159, 17167, 17183, 17189, 17191, 17203, 17207, 17209, 17231, 17239, 17257, 17291, 17293, 17299, 17317, 17321, 17327, 17333, 17341, 17351, 17359, 17377, 17383, 17387, 17389, 17393, 17401, 17417, 17419, 17431, 17443, 17449, 17467, 17471, 17477, 17483, 17489, 17491, 17497, 17509, 17519, 17539, 17551, 17569, 17573, 17579, 17581, 17597, 17599, 17609, 17623, 17627, 17657, 17659, 17669, 17681, 17683, 17707, 17713, 17729, 17737, 17747, 17749, 17761, 17783, 17789, 17791, 17807, 17827, 17837, 17839, 17851, 17863, ] class _WinKey(): # A CNG BCRYPT_KEY_HANDLE on Vista and newer, an HCRYPTKEY on XP and 2003 key_handle = None # On XP and 2003, we have to carry around more info context_handle = None ex_key_handle = None # A reference to the library used in the destructor to make sure it hasn't # been garbage collected by the time this object is garbage collected _lib = None def __init__(self, key_handle, asn1): """ :param key_handle: A CNG BCRYPT_KEY_HANDLE value (Vista and newer) or an HCRYPTKEY (XP and 2003) from loading/importing the key :param asn1: An asn1crypto object for the concrete type """ self.key_handle = key_handle self.asn1 = asn1 if _backend == 'winlegacy': self._lib = advapi32 else: self._lib = bcrypt def __del__(self): if self.key_handle: if _backend == 'winlegacy': res = self._lib.CryptDestroyKey(self.key_handle) else: res = self._lib.BCryptDestroyKey(self.key_handle) handle_error(res) self.key_handle = None if self.context_handle and _backend == 'winlegacy': close_context_handle(self.context_handle) self.context_handle = None self._lib = None class PrivateKey(_WinKey, _PrivateKeyBase): """ Container for the OS crypto library representation of a private key """ _public_key = None def __init__(self, key_handle, asn1): """ :param key_handle: A CNG BCRYPT_KEY_HANDLE value (Vista and newer) or an HCRYPTKEY (XP and 2003) from loading/importing the key :param asn1: An asn1crypto.keys.PrivateKeyInfo object """ _WinKey.__init__(self, key_handle, asn1) @property def public_key(self): """ :return: A PublicKey object corresponding to this private key. """ if _backend == 'winlegacy': if self.algorithm == 'ec': pub_point = _pure_python_ec_compute_public_key_point(self.asn1) self._public_key = PublicKey(None, ec_public_key_info(pub_point, self.curve)) elif self.algorithm == 'dsa': # The DSA provider won't allow exporting the private key with # CryptoImportKey flags set to 0 and won't allow flags to be set # to CRYPT_EXPORTABLE, so we manually recreated the public key # ASN.1 params = self.asn1['private_key_algorithm']['parameters'] pub_asn1 = PublicKeyInfo({ 'algorithm': PublicKeyAlgorithm({ 'algorithm': 'dsa', 'parameters': params }), 'public_key': Integer(pow( params['g'].native, self.asn1['private_key'].parsed.native, params['p'].native )) }) self._public_key = load_public_key(pub_asn1) else: # This suffers from similar problems as above, although not # as insurmountable. This is just a simpler/faster solution # since the private key has all of the data we need anyway parsed = self.asn1['private_key'].parsed pub_asn1 = PublicKeyInfo({ 'algorithm': PublicKeyAlgorithm({ 'algorithm': 'rsa' }), 'public_key': RSAPublicKey({ 'modulus': parsed['modulus'], 'public_exponent': parsed['public_exponent'] }) }) self._public_key = load_public_key(pub_asn1) else: pub_asn1, _ = _bcrypt_key_handle_to_asn1(self.algorithm, self.bit_size, self.key_handle) self._public_key = load_public_key(pub_asn1) return self._public_key @property def fingerprint(self): """ Creates a fingerprint that can be compared with a public key to see if the two form a pair. This fingerprint is not compatible with fingerprints generated by any other software. :return: A byte string that is a sha256 hash of selected components (based on the key type) """ if self._fingerprint is None: self._fingerprint = _fingerprint(self.asn1, load_private_key) return self._fingerprint class PublicKey(_WinKey, _PublicKeyBase): """ Container for the OS crypto library representation of a public key """ def __init__(self, key_handle, asn1): """ :param key_handle: A CNG BCRYPT_KEY_HANDLE value (Vista and newer) or an HCRYPTKEY (XP and 2003) from loading/importing the key :param asn1: An asn1crypto.keys.PublicKeyInfo object """ _WinKey.__init__(self, key_handle, asn1) class Certificate(_WinKey, _CertificateBase): """ Container for the OS crypto library representation of a certificate """ _public_key = None _self_signed = None def __init__(self, key_handle, asn1): """ :param key_handle: A CNG BCRYPT_KEY_HANDLE value (Vista and newer) or an HCRYPTKEY (XP and 2003) from loading/importing the certificate :param asn1: An asn1crypto.x509.Certificate object """ _WinKey.__init__(self, key_handle, asn1) @property def public_key(self): """ :return: The PublicKey object for the public key this certificate contains """ if self._public_key is None: self._public_key = load_public_key(self.asn1['tbs_certificate']['subject_public_key_info']) return self._public_key @property def self_signed(self): """ :return: A boolean - if the certificate is self-signed """ if self._self_signed is None: self._self_signed = False if self.asn1.self_signed in set(['yes', 'maybe']): signature_algo = self.asn1['signature_algorithm'].signature_algo hash_algo = self.asn1['signature_algorithm'].hash_algo if signature_algo == 'rsassa_pkcs1v15': verify_func = rsa_pkcs1v15_verify elif signature_algo == 'rsassa_pss': verify_func = rsa_pss_verify elif signature_algo == 'dsa': verify_func = dsa_verify elif signature_algo == 'ecdsa': verify_func = ecdsa_verify else: raise OSError(pretty_message( ''' Unable to verify the signature of the certificate since it uses the unsupported algorithm %s ''', signature_algo )) try: verify_func( self, self.asn1['signature_value'].native, self.asn1['tbs_certificate'].dump(), hash_algo ) self._self_signed = True except (SignatureError): pass return self._self_signed def generate_pair(algorithm, bit_size=None, curve=None): """ Generates a public/private key pair :param algorithm: The key algorithm - "rsa", "dsa" or "ec" :param bit_size: An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024, 2048, 3072 or 4096. For "dsa" the value may be 1024, plus 2048 or 3072 if on Windows 8 or newer. :param curve: A unicode string - used for "ec" keys. Valid values include "secp256r1", "secp384r1" and "secp521r1". :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A 2-element tuple of (PublicKey, PrivateKey). The contents of each key may be saved by calling .asn1.dump(). """ if algorithm not in set(['rsa', 'dsa', 'ec']): raise ValueError(pretty_message( ''' algorithm must be one of "rsa", "dsa", "ec", not %s ''', repr(algorithm) )) if algorithm == 'rsa': if bit_size not in set([1024, 2048, 3072, 4096]): raise ValueError(pretty_message( ''' bit_size must be one of 1024, 2048, 3072, 4096, not %s ''', repr(bit_size) )) elif algorithm == 'dsa': # Windows Vista and 7 only support SHA1-based DSA keys if _win_version_info < (6, 2) or _backend == 'winlegacy': if bit_size != 1024: raise ValueError(pretty_message( ''' bit_size must be 1024, not %s ''', repr(bit_size) )) else: if bit_size not in set([1024, 2048, 3072]): raise ValueError(pretty_message( ''' bit_size must be one of 1024, 2048, 3072, not %s ''', repr(bit_size) )) elif algorithm == 'ec': if curve not in set(['secp256r1', 'secp384r1', 'secp521r1']): raise ValueError(pretty_message( ''' curve must be one of "secp256r1", "secp384r1", "secp521r1", not %s ''', repr(curve) )) if _backend == 'winlegacy': if algorithm == 'ec': pub_info, priv_info = _pure_python_ec_generate_pair(curve) return (PublicKey(None, pub_info), PrivateKey(None, priv_info)) return _advapi32_generate_pair(algorithm, bit_size) else: return _bcrypt_generate_pair(algorithm, bit_size, curve) def _advapi32_key_handle_to_asn1(algorithm, bit_size, key_handle): """ Accepts an key handle and exports it to ASN.1 :param algorithm: The key algorithm - "rsa" or "dsa" :param bit_size: An integer - only used when algorithm is "rsa" :param key_handle: The handle to export :return: A 2-element tuple of asn1crypto.keys.PrivateKeyInfo and asn1crypto.keys.PublicKeyInfo """ if algorithm == 'rsa': struct_type = 'RSABLOBHEADER' else: struct_type = 'DSSBLOBHEADER' out_len = new(advapi32, 'DWORD *') res = advapi32.CryptExportKey( key_handle, null(), Advapi32Const.PRIVATEKEYBLOB, 0, null(), out_len ) handle_error(res) buffer_length = deref(out_len) buffer_ = buffer_from_bytes(buffer_length) res = advapi32.CryptExportKey( key_handle, null(), Advapi32Const.PRIVATEKEYBLOB, 0, buffer_, out_len ) handle_error(res) blob_struct_pointer = struct_from_buffer(advapi32, struct_type, buffer_) blob_struct = unwrap(blob_struct_pointer) struct_size = sizeof(advapi32, blob_struct) private_blob = bytes_from_buffer(buffer_, buffer_length)[struct_size:] if algorithm == 'rsa': public_info, private_info = _advapi32_interpret_rsa_key_blob(bit_size, blob_struct, private_blob) else: # The public key for a DSA key is not available in from the private # key blob, so we have to separately export the public key public_out_len = new(advapi32, 'DWORD *') res = advapi32.CryptExportKey( key_handle, null(), Advapi32Const.PUBLICKEYBLOB, 0, null(), public_out_len ) handle_error(res) public_buffer_length = deref(public_out_len) public_buffer = buffer_from_bytes(public_buffer_length) res = advapi32.CryptExportKey( key_handle, null(), Advapi32Const.PUBLICKEYBLOB, 0, public_buffer, public_out_len ) handle_error(res) public_blob = bytes_from_buffer(public_buffer, public_buffer_length)[struct_size:] public_info, private_info = _advapi32_interpret_dsa_key_blob(bit_size, public_blob, private_blob) return (public_info, private_info) def _advapi32_generate_pair(algorithm, bit_size=None): """ Generates a public/private key pair using CryptoAPI :param algorithm: The key algorithm - "rsa" or "dsa" :param bit_size: An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024, 2048, 3072 or 4096. For "dsa" the value may be 1024. :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A 2-element tuple of (PublicKey, PrivateKey). The contents of each key may be saved by calling .asn1.dump(). """ if algorithm == 'rsa': provider = Advapi32Const.MS_ENH_RSA_AES_PROV algorithm_id = Advapi32Const.CALG_RSA_SIGN else: provider = Advapi32Const.MS_ENH_DSS_DH_PROV algorithm_id = Advapi32Const.CALG_DSS_SIGN context_handle = None key_handle = None try: context_handle = open_context_handle(provider, verify_only=False) key_handle_pointer = new(advapi32, 'HCRYPTKEY *') flags = (bit_size << 16) | Advapi32Const.CRYPT_EXPORTABLE res = advapi32.CryptGenKey(context_handle, algorithm_id, flags, key_handle_pointer) handle_error(res) key_handle = unwrap(key_handle_pointer) public_info, private_info = _advapi32_key_handle_to_asn1(algorithm, bit_size, key_handle) return (load_public_key(public_info), load_private_key(private_info)) finally: if context_handle: close_context_handle(context_handle) if key_handle: advapi32.CryptDestroyKey(key_handle) def _bcrypt_key_handle_to_asn1(algorithm, bit_size, key_handle): """ Accepts an key handle and exports it to ASN.1 :param algorithm: The key algorithm - "rsa", "dsa" or "ec" :param bit_size: An integer - only used when algorithm is "dsa" :param key_handle: The handle to export :return: A 2-element tuple of asn1crypto.keys.PrivateKeyInfo and asn1crypto.keys.PublicKeyInfo """ if algorithm == 'rsa': struct_type = 'BCRYPT_RSAKEY_BLOB' private_blob_type = BcryptConst.BCRYPT_RSAFULLPRIVATE_BLOB public_blob_type = BcryptConst.BCRYPT_RSAPUBLIC_BLOB elif algorithm == 'dsa': if bit_size > 1024: struct_type = 'BCRYPT_DSA_KEY_BLOB_V2' else: struct_type = 'BCRYPT_DSA_KEY_BLOB' private_blob_type = BcryptConst.BCRYPT_DSA_PRIVATE_BLOB public_blob_type = BcryptConst.BCRYPT_DSA_PUBLIC_BLOB else: struct_type = 'BCRYPT_ECCKEY_BLOB' private_blob_type = BcryptConst.BCRYPT_ECCPRIVATE_BLOB public_blob_type = BcryptConst.BCRYPT_ECCPUBLIC_BLOB private_out_len = new(bcrypt, 'ULONG *') res = bcrypt.BCryptExportKey(key_handle, null(), private_blob_type, null(), 0, private_out_len, 0) handle_error(res) private_buffer_length = deref(private_out_len) private_buffer = buffer_from_bytes(private_buffer_length) res = bcrypt.BCryptExportKey( key_handle, null(), private_blob_type, private_buffer, private_buffer_length, private_out_len, 0 ) handle_error(res) private_blob_struct_pointer = struct_from_buffer(bcrypt, struct_type, private_buffer) private_blob_struct = unwrap(private_blob_struct_pointer) struct_size = sizeof(bcrypt, private_blob_struct) private_blob = bytes_from_buffer(private_buffer, private_buffer_length)[struct_size:] if algorithm == 'rsa': private_key = _bcrypt_interpret_rsa_key_blob('private', private_blob_struct, private_blob) elif algorithm == 'dsa': if bit_size > 1024: private_key = _bcrypt_interpret_dsa_key_blob('private', 2, private_blob_struct, private_blob) else: private_key = _bcrypt_interpret_dsa_key_blob('private', 1, private_blob_struct, private_blob) else: private_key = _bcrypt_interpret_ec_key_blob('private', private_blob_struct, private_blob) public_out_len = new(bcrypt, 'ULONG *') res = bcrypt.BCryptExportKey(key_handle, null(), public_blob_type, null(), 0, public_out_len, 0) handle_error(res) public_buffer_length = deref(public_out_len) public_buffer = buffer_from_bytes(public_buffer_length) res = bcrypt.BCryptExportKey( key_handle, null(), public_blob_type, public_buffer, public_buffer_length, public_out_len, 0 ) handle_error(res) public_blob_struct_pointer = struct_from_buffer(bcrypt, struct_type, public_buffer) public_blob_struct = unwrap(public_blob_struct_pointer) struct_size = sizeof(bcrypt, public_blob_struct) public_blob = bytes_from_buffer(public_buffer, public_buffer_length)[struct_size:] if algorithm == 'rsa': public_key = _bcrypt_interpret_rsa_key_blob('public', public_blob_struct, public_blob) elif algorithm == 'dsa': if bit_size > 1024: public_key = _bcrypt_interpret_dsa_key_blob('public', 2, public_blob_struct, public_blob) else: public_key = _bcrypt_interpret_dsa_key_blob('public', 1, public_blob_struct, public_blob) else: public_key = _bcrypt_interpret_ec_key_blob('public', public_blob_struct, public_blob) return (public_key, private_key) def _bcrypt_generate_pair(algorithm, bit_size=None, curve=None): """ Generates a public/private key pair using CNG :param algorithm: The key algorithm - "rsa", "dsa" or "ec" :param bit_size: An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024, 2048, 3072 or 4096. For "dsa" the value may be 1024, plus 2048 or 3072 if on Windows 8 or newer. :param curve: A unicode string - used for "ec" keys. Valid values include "secp256r1", "secp384r1" and "secp521r1". :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A 2-element tuple of (PublicKey, PrivateKey). The contents of each key may be saved by calling .asn1.dump(). """ if algorithm == 'rsa': alg_constant = BcryptConst.BCRYPT_RSA_ALGORITHM elif algorithm == 'dsa': alg_constant = BcryptConst.BCRYPT_DSA_ALGORITHM else: alg_constant = { 'secp256r1': BcryptConst.BCRYPT_ECDSA_P256_ALGORITHM, 'secp384r1': BcryptConst.BCRYPT_ECDSA_P384_ALGORITHM, 'secp521r1': BcryptConst.BCRYPT_ECDSA_P521_ALGORITHM, }[curve] bit_size = { 'secp256r1': 256, 'secp384r1': 384, 'secp521r1': 521, }[curve] key_handle = None try: alg_handle = open_alg_handle(alg_constant) key_handle_pointer = new(bcrypt, 'BCRYPT_KEY_HANDLE *') res = bcrypt.BCryptGenerateKeyPair(alg_handle, key_handle_pointer, bit_size, 0) handle_error(res) key_handle = unwrap(key_handle_pointer) res = bcrypt.BCryptFinalizeKeyPair(key_handle, 0) handle_error(res) public_key, private_key = _bcrypt_key_handle_to_asn1(algorithm, bit_size, key_handle) finally: if key_handle: bcrypt.BCryptDestroyKey(key_handle) return (load_public_key(public_key), load_private_key(private_key)) def generate_dh_parameters(bit_size): """ Generates DH parameters for use with Diffie-Hellman key exchange. Returns a structure in the format of DHParameter defined in PKCS#3, which is also used by the OpenSSL dhparam tool. THIS CAN BE VERY TIME CONSUMING! :param bit_size: The integer bit size of the parameters to generate. Must be between 512 and 4096, and divisible by 64. Recommended secure value as of early 2016 is 2048, with an absolute minimum of 1024. :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: An asn1crypto.algos.DHParameters object. Use oscrypto.asymmetric.dump_dh_parameters() to save to disk for usage with web servers. """ if not isinstance(bit_size, int_types): raise TypeError(pretty_message( ''' bit_size must be an integer, not %s ''', type_name(bit_size) )) if bit_size < 512: raise ValueError('bit_size must be greater than or equal to 512') if bit_size > 4096: raise ValueError('bit_size must be less than or equal to 4096') if bit_size % 64 != 0: raise ValueError('bit_size must be a multiple of 64') alg_handle = None # The following algorithm has elements taken from OpenSSL. In short, it # generates random numbers and then ensures that they are valid for the # hardcoded generator of 2, and then ensures the number is a "safe" prime # by ensuring p//2 is prime also. # OpenSSL allows use of generator 2 or 5, but we hardcode 2 since it is # the default, and what is used by Security.framework on OS X also. g = 2 try: byte_size = bit_size // 8 if _backend == 'win': alg_handle = open_alg_handle(BcryptConst.BCRYPT_RNG_ALGORITHM) buffer = buffer_from_bytes(byte_size) while True: if _backend == 'winlegacy': rb = os.urandom(byte_size) else: res = bcrypt.BCryptGenRandom(alg_handle, buffer, byte_size, 0) handle_error(res) rb = bytes_from_buffer(buffer) p = int_from_bytes(rb) # If a number is even, it can't be prime if p % 2 == 0: continue # Perform the generator checks outlined in OpenSSL's # dh_builtin_genparams() located in dh_gen.c if g == 2: if p % 24 != 11: continue elif g == 5: rem = p % 10 if rem != 3 and rem != 7: continue divisible = False for prime in _SMALL_PRIMES: if p % prime == 0: divisible = True break # If the number is not divisible by any of the small primes, then # move on to the full Miller-Rabin test. if not divisible and _is_prime(bit_size, p): q = p // 2 if _is_prime(bit_size, q): return DHParameters({'p': p, 'g': g}) finally: if alg_handle: close_alg_handle(alg_handle) def _is_prime(bit_size, n): """ An implementation of Miller–Rabin for checking if a number is prime. :param bit_size: An integer of the number of bits in the prime number :param n: An integer, the prime number :return: A boolean """ r = 0 s = n - 1 while s % 2 == 0: r += 1 s //= 2 if bit_size >= 1300: k = 2 elif bit_size >= 850: k = 3 elif bit_size >= 650: k = 4 elif bit_size >= 550: k = 5 elif bit_size >= 450: k = 6 for _ in range(k): a = random.randrange(2, n - 1) x = pow(a, s, n) if x == 1 or x == n - 1: continue for _ in range(r - 1): x = pow(x, 2, n) if x == n - 1: break else: return False return True def _advapi32_interpret_rsa_key_blob(bit_size, blob_struct, blob): """ Takes a CryptoAPI RSA private key blob and converts it into the ASN.1 structures for the public and private keys :param bit_size: The integer bit size of the key :param blob_struct: An instance of the advapi32.RSAPUBKEY struct :param blob: A byte string of the binary data after the header :return: A 2-element tuple of (asn1crypto.keys.PublicKeyInfo, asn1crypto.keys.PrivateKeyInfo) """ len1 = bit_size // 8 len2 = bit_size // 16 prime1_offset = len1 prime2_offset = prime1_offset + len2 exponent1_offset = prime2_offset + len2 exponent2_offset = exponent1_offset + len2 coefficient_offset = exponent2_offset + len2 private_exponent_offset = coefficient_offset + len2 public_exponent = blob_struct.rsapubkey.pubexp modulus = int_from_bytes(blob[0:prime1_offset][::-1]) prime1 = int_from_bytes(blob[prime1_offset:prime2_offset][::-1]) prime2 = int_from_bytes(blob[prime2_offset:exponent1_offset][::-1]) exponent1 = int_from_bytes(blob[exponent1_offset:exponent2_offset][::-1]) exponent2 = int_from_bytes(blob[exponent2_offset:coefficient_offset][::-1]) coefficient = int_from_bytes(blob[coefficient_offset:private_exponent_offset][::-1]) private_exponent = int_from_bytes(blob[private_exponent_offset:private_exponent_offset + len1][::-1]) public_key_info = PublicKeyInfo({ 'algorithm': PublicKeyAlgorithm({ 'algorithm': 'rsa', }), 'public_key': RSAPublicKey({ 'modulus': modulus, 'public_exponent': public_exponent, }), }) rsa_private_key = RSAPrivateKey({ 'version': 'two-prime', 'modulus': modulus, 'public_exponent': public_exponent, 'private_exponent': private_exponent, 'prime1': prime1, 'prime2': prime2, 'exponent1': exponent1, 'exponent2': exponent2, 'coefficient': coefficient, }) private_key_info = PrivateKeyInfo({ 'version': 0, 'private_key_algorithm': PrivateKeyAlgorithm({ 'algorithm': 'rsa', }), 'private_key': rsa_private_key, }) return (public_key_info, private_key_info) def _advapi32_interpret_dsa_key_blob(bit_size, public_blob, private_blob): """ Takes a CryptoAPI DSS private key blob and converts it into the ASN.1 structures for the public and private keys :param bit_size: The integer bit size of the key :param public_blob: A byte string of the binary data after the public key header :param private_blob: A byte string of the binary data after the private key header :return: A 2-element tuple of (asn1crypto.keys.PublicKeyInfo, asn1crypto.keys.PrivateKeyInfo) """ len1 = 20 len2 = bit_size // 8 q_offset = len2 g_offset = q_offset + len1 x_offset = g_offset + len2 y_offset = x_offset p = int_from_bytes(private_blob[0:q_offset][::-1]) q = int_from_bytes(private_blob[q_offset:g_offset][::-1]) g = int_from_bytes(private_blob[g_offset:x_offset][::-1]) x = int_from_bytes(private_blob[x_offset:x_offset + len1][::-1]) y = int_from_bytes(public_blob[y_offset:y_offset + len2][::-1]) public_key_info = PublicKeyInfo({ 'algorithm': PublicKeyAlgorithm({ 'algorithm': 'dsa', 'parameters': DSAParams({ 'p': p, 'q': q, 'g': g, }) }), 'public_key': Integer(y), }) private_key_info = PrivateKeyInfo({ 'version': 0, 'private_key_algorithm': PrivateKeyAlgorithm({ 'algorithm': 'dsa', 'parameters': DSAParams({ 'p': p, 'q': q, 'g': g, }) }), 'private_key': Integer(x), }) return (public_key_info, private_key_info) def _bcrypt_interpret_rsa_key_blob(key_type, blob_struct, blob): """ Take a CNG BCRYPT_RSAFULLPRIVATE_BLOB and converts it into an ASN.1 structure :param key_type: A unicode string of "private" or "public" :param blob_struct: An instance of BCRYPT_RSAKEY_BLOB :param blob: A byte string of the binary data contained after the struct :return: An asn1crypto.keys.PrivateKeyInfo or asn1crypto.keys.PublicKeyInfo object, based on the key_type param """ public_exponent_byte_length = native(int, blob_struct.cbPublicExp) modulus_byte_length = native(int, blob_struct.cbModulus) modulus_offset = public_exponent_byte_length public_exponent = int_from_bytes(blob[0:modulus_offset]) modulus = int_from_bytes(blob[modulus_offset:modulus_offset + modulus_byte_length]) if key_type == 'public': return PublicKeyInfo({ 'algorithm': PublicKeyAlgorithm({ 'algorithm': 'rsa', }), 'public_key': RSAPublicKey({ 'modulus': modulus, 'public_exponent': public_exponent, }), }) elif key_type == 'private': prime1_byte_length = native(int, blob_struct.cbPrime1) prime2_byte_length = native(int, blob_struct.cbPrime2) prime1_offset = modulus_offset + modulus_byte_length prime2_offset = prime1_offset + prime1_byte_length exponent1_offset = prime2_offset + prime2_byte_length exponent2_offset = exponent1_offset + prime2_byte_length coefficient_offset = exponent2_offset + prime2_byte_length private_exponent_offset = coefficient_offset + prime1_byte_length prime1 = int_from_bytes(blob[prime1_offset:prime2_offset]) prime2 = int_from_bytes(blob[prime2_offset:exponent1_offset]) exponent1 = int_from_bytes(blob[exponent1_offset:exponent2_offset]) exponent2 = int_from_bytes(blob[exponent2_offset:coefficient_offset]) coefficient = int_from_bytes(blob[coefficient_offset:private_exponent_offset]) private_exponent = int_from_bytes(blob[private_exponent_offset:private_exponent_offset + modulus_byte_length]) rsa_private_key = RSAPrivateKey({ 'version': 'two-prime', 'modulus': modulus, 'public_exponent': public_exponent, 'private_exponent': private_exponent, 'prime1': prime1, 'prime2': prime2, 'exponent1': exponent1, 'exponent2': exponent2, 'coefficient': coefficient, }) return PrivateKeyInfo({ 'version': 0, 'private_key_algorithm': PrivateKeyAlgorithm({ 'algorithm': 'rsa', }), 'private_key': rsa_private_key, }) else: raise ValueError(pretty_message( ''' key_type must be one of "public", "private", not %s ''', repr(key_type) )) def _bcrypt_interpret_dsa_key_blob(key_type, version, blob_struct, blob): """ Take a CNG BCRYPT_DSA_KEY_BLOB or BCRYPT_DSA_KEY_BLOB_V2 and converts it into an ASN.1 structure :param key_type: A unicode string of "private" or "public" :param version: An integer - 1 or 2, indicating the blob is BCRYPT_DSA_KEY_BLOB or BCRYPT_DSA_KEY_BLOB_V2 :param blob_struct: An instance of BCRYPT_DSA_KEY_BLOB or BCRYPT_DSA_KEY_BLOB_V2 :param blob: A byte string of the binary data contained after the struct :return: An asn1crypto.keys.PrivateKeyInfo or asn1crypto.keys.PublicKeyInfo object, based on the key_type param """ key_byte_length = native(int, blob_struct.cbKey) if version == 1: q = int_from_bytes(native(byte_cls, blob_struct.q)) g_offset = key_byte_length public_offset = g_offset + key_byte_length private_offset = public_offset + key_byte_length p = int_from_bytes(blob[0:g_offset]) g = int_from_bytes(blob[g_offset:public_offset]) elif version == 2: seed_byte_length = native(int, blob_struct.cbSeedLength) group_byte_length = native(int, blob_struct.cbGroupSize) q_offset = seed_byte_length p_offset = q_offset + group_byte_length g_offset = p_offset + key_byte_length public_offset = g_offset + key_byte_length private_offset = public_offset + key_byte_length # The seed is skipped since it is not part of the ASN.1 structure q = int_from_bytes(blob[q_offset:p_offset]) p = int_from_bytes(blob[p_offset:g_offset]) g = int_from_bytes(blob[g_offset:public_offset]) else: raise ValueError('version must be 1 or 2, not %s' % repr(version)) if key_type == 'public': public = int_from_bytes(blob[public_offset:private_offset]) return PublicKeyInfo({ 'algorithm': PublicKeyAlgorithm({ 'algorithm': 'dsa', 'parameters': DSAParams({ 'p': p, 'q': q, 'g': g, }) }), 'public_key': Integer(public), }) elif key_type == 'private': private = int_from_bytes(blob[private_offset:private_offset + key_byte_length]) return PrivateKeyInfo({ 'version': 0, 'private_key_algorithm': PrivateKeyAlgorithm({ 'algorithm': 'dsa', 'parameters': DSAParams({ 'p': p, 'q': q, 'g': g, }) }), 'private_key': Integer(private), }) else: raise ValueError(pretty_message( ''' key_type must be one of "public", "private", not %s ''', repr(key_type) )) def _bcrypt_interpret_ec_key_blob(key_type, blob_struct, blob): """ Take a CNG BCRYPT_ECCKEY_BLOB and converts it into an ASN.1 structure :param key_type: A unicode string of "private" or "public" :param blob_struct: An instance of BCRYPT_ECCKEY_BLOB :param blob: A byte string of the binary data contained after the struct :return: An asn1crypto.keys.PrivateKeyInfo or asn1crypto.keys.PublicKeyInfo object, based on the key_type param """ magic = native(int, blob_struct.dwMagic) key_byte_length = native(int, blob_struct.cbKey) curve = { BcryptConst.BCRYPT_ECDSA_PRIVATE_P256_MAGIC: 'secp256r1', BcryptConst.BCRYPT_ECDSA_PRIVATE_P384_MAGIC: 'secp384r1', BcryptConst.BCRYPT_ECDSA_PRIVATE_P521_MAGIC: 'secp521r1', BcryptConst.BCRYPT_ECDSA_PUBLIC_P256_MAGIC: 'secp256r1', BcryptConst.BCRYPT_ECDSA_PUBLIC_P384_MAGIC: 'secp384r1', BcryptConst.BCRYPT_ECDSA_PUBLIC_P521_MAGIC: 'secp521r1', }[magic] public = b'\x04' + blob[0:key_byte_length * 2] if key_type == 'public': return PublicKeyInfo({ 'algorithm': PublicKeyAlgorithm({ 'algorithm': 'ec', 'parameters': ECDomainParameters( name='named', value=curve ) }), 'public_key': public, }) elif key_type == 'private': private = int_from_bytes(blob[key_byte_length * 2:key_byte_length * 3]) return PrivateKeyInfo({ 'version': 0, 'private_key_algorithm': PrivateKeyAlgorithm({ 'algorithm': 'ec', 'parameters': ECDomainParameters( name='named', value=curve ) }), 'private_key': ECPrivateKey({ 'version': 'ecPrivkeyVer1', 'private_key': private, 'public_key': public, }), }) else: raise ValueError(pretty_message( ''' key_type must be one of "public", "private", not %s ''', repr(key_type) )) def load_certificate(source): """ Loads an x509 certificate into a Certificate object :param source: A byte string of file contents or a unicode string filename :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A Certificate object """ if isinstance(source, Asn1Certificate): certificate = source elif isinstance(source, byte_cls): certificate = parse_certificate(source) elif isinstance(source, str_cls): with open(source, 'rb') as f: certificate = parse_certificate(f.read()) else: raise TypeError(pretty_message( ''' source must be a byte string, unicode string or asn1crypto.x509.Certificate object, not %s ''', type_name(source) )) return _load_key(certificate, Certificate) def _load_key(key_object, container): """ Loads a certificate, public key or private key into a Certificate, PublicKey or PrivateKey object :param key_object: An asn1crypto.x509.Certificate, asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo object :param container: The class of the object to hold the key_handle :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type oscrypto.errors.AsymmetricKeyError - when the key is incompatible with the OS crypto library OSError - when an error is returned by the OS crypto library :return: A PrivateKey, PublicKey or Certificate object, based on container """ key_info = key_object if isinstance(key_object, Asn1Certificate): key_info = key_object['tbs_certificate']['subject_public_key_info'] algo = key_info.algorithm curve_name = None if algo == 'ec': curve_type, curve_name = key_info.curve if curve_type != 'named': raise AsymmetricKeyError(pretty_message( ''' Windows only supports EC keys using named curves ''' )) if curve_name not in set(['secp256r1', 'secp384r1', 'secp521r1']): raise AsymmetricKeyError(pretty_message( ''' Windows only supports EC keys using the named curves secp256r1, secp384r1 and secp521r1 ''' )) elif algo == 'dsa': if key_info.hash_algo is None: raise IncompleteAsymmetricKeyError(pretty_message( ''' The DSA key does not contain the necessary p, q and g parameters and can not be used ''' )) elif key_info.bit_size > 1024 and (_win_version_info < (6, 2) or _backend == 'winlegacy'): raise AsymmetricKeyError(pretty_message( ''' Windows XP, 2003, Vista, 7 and Server 2008 only support DSA keys based on SHA1 (1024 bits or less) - this key is based on %s and is %s bits ''', key_info.hash_algo.upper(), key_info.bit_size )) elif key_info.bit_size == 2048 and key_info.hash_algo == 'sha1': raise AsymmetricKeyError(pretty_message( ''' Windows only supports 2048 bit DSA keys based on SHA2 - this key is 2048 bits and based on SHA1, a non-standard combination that is usually generated by old versions of OpenSSL ''' )) if _backend == 'winlegacy': if algo == 'ec': return container(None, key_object) return _advapi32_load_key(key_object, key_info, container) return _bcrypt_load_key(key_object, key_info, container, curve_name) def _advapi32_load_key(key_object, key_info, container): """ Loads a certificate, public key or private key into a Certificate, PublicKey or PrivateKey object via CryptoAPI :param key_object: An asn1crypto.x509.Certificate, asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo object :param key_info: An asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo object :param container: The class of the object to hold the key_handle :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type oscrypto.errors.AsymmetricKeyError - when the key is incompatible with the OS crypto library OSError - when an error is returned by the OS crypto library :return: A PrivateKey, PublicKey or Certificate object, based on container """ key_type = 'public' if isinstance(key_info, PublicKeyInfo) else 'private' algo = key_info.algorithm if algo == 'rsassa_pss': algo = 'rsa' if algo == 'rsa' or algo == 'rsassa_pss': provider = Advapi32Const.MS_ENH_RSA_AES_PROV else: provider = Advapi32Const.MS_ENH_DSS_DH_PROV context_handle = None key_handle = None try: context_handle = open_context_handle(provider, verify_only=key_type == 'public') blob = _advapi32_create_blob(key_info, key_type, algo) buffer_ = buffer_from_bytes(blob) key_handle_pointer = new(advapi32, 'HCRYPTKEY *') res = advapi32.CryptImportKey( context_handle, buffer_, len(blob), null(), 0, key_handle_pointer ) handle_error(res) key_handle = unwrap(key_handle_pointer) output = container(key_handle, key_object) output.context_handle = context_handle if algo == 'rsa': ex_blob = _advapi32_create_blob(key_info, key_type, algo, signing=False) ex_buffer = buffer_from_bytes(ex_blob) ex_key_handle_pointer = new(advapi32, 'HCRYPTKEY *') res = advapi32.CryptImportKey( context_handle, ex_buffer, len(ex_blob), null(), 0, ex_key_handle_pointer ) handle_error(res) output.ex_key_handle = unwrap(ex_key_handle_pointer) return output except (Exception): if key_handle: advapi32.CryptDestroyKey(key_handle) if context_handle: close_context_handle(context_handle) raise def _advapi32_create_blob(key_info, key_type, algo, signing=True): """ Generates a blob for importing a key to CryptoAPI :param key_info: An asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo object :param key_type: A unicode string of "public" or "private" :param algo: A unicode string of "rsa" or "dsa" :param signing: If the key handle is for signing - may only be False for rsa keys :return: A byte string of a blob to pass to advapi32.CryptImportKey() """ if key_type == 'public': blob_type = Advapi32Const.PUBLICKEYBLOB else: blob_type = Advapi32Const.PRIVATEKEYBLOB if algo == 'rsa': struct_type = 'RSABLOBHEADER' if signing: algorithm_id = Advapi32Const.CALG_RSA_SIGN else: algorithm_id = Advapi32Const.CALG_RSA_KEYX else: struct_type = 'DSSBLOBHEADER' algorithm_id = Advapi32Const.CALG_DSS_SIGN blob_header_pointer = struct(advapi32, 'BLOBHEADER') blob_header = unwrap(blob_header_pointer) blob_header.bType = blob_type blob_header.bVersion = Advapi32Const.CUR_BLOB_VERSION blob_header.reserved = 0 blob_header.aiKeyAlg = algorithm_id blob_struct_pointer = struct(advapi32, struct_type) blob_struct = unwrap(blob_struct_pointer) blob_struct.publickeystruc = blob_header bit_size = key_info.bit_size len1 = bit_size // 8 len2 = bit_size // 16 if algo == 'rsa': pubkey_pointer = struct(advapi32, 'RSAPUBKEY') pubkey = unwrap(pubkey_pointer) pubkey.bitlen = bit_size if key_type == 'public': parsed_key_info = key_info['public_key'].parsed pubkey.magic = Advapi32Const.RSA1 pubkey.pubexp = parsed_key_info['public_exponent'].native blob_data = int_to_bytes(parsed_key_info['modulus'].native, signed=False, width=len1)[::-1] else: parsed_key_info = key_info['private_key'].parsed pubkey.magic = Advapi32Const.RSA2 pubkey.pubexp = parsed_key_info['public_exponent'].native blob_data = int_to_bytes(parsed_key_info['modulus'].native, signed=False, width=len1)[::-1] blob_data += int_to_bytes(parsed_key_info['prime1'].native, signed=False, width=len2)[::-1] blob_data += int_to_bytes(parsed_key_info['prime2'].native, signed=False, width=len2)[::-1] blob_data += int_to_bytes(parsed_key_info['exponent1'].native, signed=False, width=len2)[::-1] blob_data += int_to_bytes(parsed_key_info['exponent2'].native, signed=False, width=len2)[::-1] blob_data += int_to_bytes(parsed_key_info['coefficient'].native, signed=False, width=len2)[::-1] blob_data += int_to_bytes(parsed_key_info['private_exponent'].native, signed=False, width=len1)[::-1] blob_struct.rsapubkey = pubkey else: pubkey_pointer = struct(advapi32, 'DSSPUBKEY') pubkey = unwrap(pubkey_pointer) pubkey.bitlen = bit_size if key_type == 'public': pubkey.magic = Advapi32Const.DSS1 params = key_info['algorithm']['parameters'].native key_data = int_to_bytes(key_info['public_key'].parsed.native, signed=False, width=len1)[::-1] else: pubkey.magic = Advapi32Const.DSS2 params = key_info['private_key_algorithm']['parameters'].native key_data = int_to_bytes(key_info['private_key'].parsed.native, signed=False, width=20)[::-1] blob_struct.dsspubkey = pubkey blob_data = int_to_bytes(params['p'], signed=False, width=len1)[::-1] blob_data += int_to_bytes(params['q'], signed=False, width=20)[::-1] blob_data += int_to_bytes(params['g'], signed=False, width=len1)[::-1] blob_data += key_data dssseed_pointer = struct(advapi32, 'DSSSEED') dssseed = unwrap(dssseed_pointer) # This indicates no counter or seed info is available dssseed.counter = 0xffffffff blob_data += struct_bytes(dssseed_pointer) return struct_bytes(blob_struct_pointer) + blob_data def _bcrypt_load_key(key_object, key_info, container, curve_name): """ Loads a certificate, public key or private key into a Certificate, PublicKey or PrivateKey object via CNG :param key_object: An asn1crypto.x509.Certificate, asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo object :param key_info: An asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo object :param container: The class of the object to hold the key_handle :param curve_name: None or a unicode string of the curve name for an EC key :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type oscrypto.errors.AsymmetricKeyError - when the key is incompatible with the OS crypto library OSError - when an error is returned by the OS crypto library :return: A PrivateKey, PublicKey or Certificate object, based on container """ alg_handle = None key_handle = None key_type = 'public' if isinstance(key_info, PublicKeyInfo) else 'private' algo = key_info.algorithm if algo == 'rsassa_pss': algo = 'rsa' try: alg_selector = key_info.curve[1] if algo == 'ec' else algo alg_constant = { 'rsa': BcryptConst.BCRYPT_RSA_ALGORITHM, 'dsa': BcryptConst.BCRYPT_DSA_ALGORITHM, 'secp256r1': BcryptConst.BCRYPT_ECDSA_P256_ALGORITHM, 'secp384r1': BcryptConst.BCRYPT_ECDSA_P384_ALGORITHM, 'secp521r1': BcryptConst.BCRYPT_ECDSA_P521_ALGORITHM, }[alg_selector] alg_handle = open_alg_handle(alg_constant) if algo == 'rsa': if key_type == 'public': blob_type = BcryptConst.BCRYPT_RSAPUBLIC_BLOB magic = BcryptConst.BCRYPT_RSAPUBLIC_MAGIC parsed_key = key_info['public_key'].parsed prime1_size = 0 prime2_size = 0 else: blob_type = BcryptConst.BCRYPT_RSAFULLPRIVATE_BLOB magic = BcryptConst.BCRYPT_RSAFULLPRIVATE_MAGIC parsed_key = key_info['private_key'].parsed prime1 = int_to_bytes(parsed_key['prime1'].native) prime2 = int_to_bytes(parsed_key['prime2'].native) exponent1 = int_to_bytes(parsed_key['exponent1'].native) exponent2 = int_to_bytes(parsed_key['exponent2'].native) coefficient = int_to_bytes(parsed_key['coefficient'].native) private_exponent = int_to_bytes(parsed_key['private_exponent'].native) prime1_size = len(prime1) prime2_size = len(prime2) public_exponent = int_to_bytes(parsed_key['public_exponent'].native) modulus = int_to_bytes(parsed_key['modulus'].native) blob_struct_pointer = struct(bcrypt, 'BCRYPT_RSAKEY_BLOB') blob_struct = unwrap(blob_struct_pointer) blob_struct.Magic = magic blob_struct.BitLength = key_info.bit_size blob_struct.cbPublicExp = len(public_exponent) blob_struct.cbModulus = len(modulus) blob_struct.cbPrime1 = prime1_size blob_struct.cbPrime2 = prime2_size blob = struct_bytes(blob_struct_pointer) + public_exponent + modulus if key_type == 'private': blob += prime1 + prime2 blob += fill_width(exponent1, prime1_size) blob += fill_width(exponent2, prime2_size) blob += fill_width(coefficient, prime1_size) blob += fill_width(private_exponent, len(modulus)) elif algo == 'dsa': if key_type == 'public': blob_type = BcryptConst.BCRYPT_DSA_PUBLIC_BLOB public_key = key_info['public_key'].parsed.native params = key_info['algorithm']['parameters'] else: blob_type = BcryptConst.BCRYPT_DSA_PRIVATE_BLOB public_key = _unwrap_private_key_info(key_info)['public_key'].native private_bytes = int_to_bytes(key_info['private_key'].parsed.native) params = key_info['private_key_algorithm']['parameters'] public_bytes = int_to_bytes(public_key) p = int_to_bytes(params['p'].native) g = int_to_bytes(params['g'].native) q = int_to_bytes(params['q'].native) if key_info.bit_size > 1024: q_len = len(q) else: q_len = 20 key_width = max(len(public_bytes), len(g), len(p)) public_bytes = fill_width(public_bytes, key_width) p = fill_width(p, key_width) g = fill_width(g, key_width) q = fill_width(q, q_len) # We don't know the count or seed, so we set them to the max value # since setting them to 0 results in a parameter error count = b'\xff' * 4 seed = b'\xff' * q_len if key_info.bit_size > 1024: if key_type == 'public': magic = BcryptConst.BCRYPT_DSA_PUBLIC_MAGIC_V2 else: magic = BcryptConst.BCRYPT_DSA_PRIVATE_MAGIC_V2 blob_struct_pointer = struct(bcrypt, 'BCRYPT_DSA_KEY_BLOB_V2') blob_struct = unwrap(blob_struct_pointer) blob_struct.dwMagic = magic blob_struct.cbKey = key_width # We don't know if SHA256 was used here, but the output is long # enough for the generation of q for the supported 2048/224, # 2048/256 and 3072/256 FIPS approved pairs blob_struct.hashAlgorithm = BcryptConst.DSA_HASH_ALGORITHM_SHA256 blob_struct.standardVersion = BcryptConst.DSA_FIPS186_3 blob_struct.cbSeedLength = q_len blob_struct.cbGroupSize = q_len blob_struct.Count = byte_array(count) blob = struct_bytes(blob_struct_pointer) blob += seed + q + p + g + public_bytes if key_type == 'private': blob += fill_width(private_bytes, q_len) else: if key_type == 'public': magic = BcryptConst.BCRYPT_DSA_PUBLIC_MAGIC else: magic = BcryptConst.BCRYPT_DSA_PRIVATE_MAGIC blob_struct_pointer = struct(bcrypt, 'BCRYPT_DSA_KEY_BLOB') blob_struct = unwrap(blob_struct_pointer) blob_struct.dwMagic = magic blob_struct.cbKey = key_width blob_struct.Count = byte_array(count) blob_struct.Seed = byte_array(seed) blob_struct.q = byte_array(q) blob = struct_bytes(blob_struct_pointer) + p + g + public_bytes if key_type == 'private': blob += fill_width(private_bytes, q_len) elif algo == 'ec': if key_type == 'public': blob_type = BcryptConst.BCRYPT_ECCPUBLIC_BLOB x, y = key_info['public_key'].to_coords() else: blob_type = BcryptConst.BCRYPT_ECCPRIVATE_BLOB public_key = key_info['private_key'].parsed['public_key'] # We aren't guaranteed to get the public key coords with the # key info structure, but BCrypt doesn't seem to have an issue # importing the private key with 0 values, which can only be # presumed that it is generating the x and y points from the # private key value and base point if public_key: x, y = public_key.to_coords() else: x = 0 y = 0 private_bytes = int_to_bytes(key_info['private_key'].parsed['private_key'].native) blob_struct_pointer = struct(bcrypt, 'BCRYPT_ECCKEY_BLOB') blob_struct = unwrap(blob_struct_pointer) magic = { ('public', 'secp256r1'): BcryptConst.BCRYPT_ECDSA_PUBLIC_P256_MAGIC, ('public', 'secp384r1'): BcryptConst.BCRYPT_ECDSA_PUBLIC_P384_MAGIC, ('public', 'secp521r1'): BcryptConst.BCRYPT_ECDSA_PUBLIC_P521_MAGIC, ('private', 'secp256r1'): BcryptConst.BCRYPT_ECDSA_PRIVATE_P256_MAGIC, ('private', 'secp384r1'): BcryptConst.BCRYPT_ECDSA_PRIVATE_P384_MAGIC, ('private', 'secp521r1'): BcryptConst.BCRYPT_ECDSA_PRIVATE_P521_MAGIC, }[(key_type, curve_name)] key_width = { 'secp256r1': 32, 'secp384r1': 48, 'secp521r1': 66 }[curve_name] x_bytes = int_to_bytes(x) y_bytes = int_to_bytes(y) x_bytes = fill_width(x_bytes, key_width) y_bytes = fill_width(y_bytes, key_width) blob_struct.dwMagic = magic blob_struct.cbKey = key_width blob = struct_bytes(blob_struct_pointer) + x_bytes + y_bytes if key_type == 'private': blob += fill_width(private_bytes, key_width) key_handle_pointer = new(bcrypt, 'BCRYPT_KEY_HANDLE *') res = bcrypt.BCryptImportKeyPair( alg_handle, null(), blob_type, key_handle_pointer, blob, len(blob), BcryptConst.BCRYPT_NO_KEY_VALIDATION ) handle_error(res) key_handle = unwrap(key_handle_pointer) return container(key_handle, key_object) finally: if alg_handle: close_alg_handle(alg_handle) def load_private_key(source, password=None): """ Loads a private key into a PrivateKey object :param source: A byte string of file contents, a unicode string filename or an asn1crypto.keys.PrivateKeyInfo object :param password: A byte or unicode string to decrypt the private key file. Unicode strings will be encoded using UTF-8. Not used is the source is a PrivateKeyInfo object. :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type oscrypto.errors.AsymmetricKeyError - when the private key is incompatible with the OS crypto library OSError - when an error is returned by the OS crypto library :return: A PrivateKey object """ if isinstance(source, PrivateKeyInfo): private_object = source else: if password is not None: if isinstance(password, str_cls): password = password.encode('utf-8') if not isinstance(password, byte_cls): raise TypeError(pretty_message( ''' password must be a byte string, not %s ''', type_name(password) )) if isinstance(source, str_cls): with open(source, 'rb') as f: source = f.read() elif not isinstance(source, byte_cls): raise TypeError(pretty_message( ''' source must be a byte string, unicode string or asn1crypto.keys.PrivateKeyInfo object, not %s ''', type_name(source) )) private_object = parse_private(source, password) return _load_key(private_object, PrivateKey) def load_public_key(source): """ Loads a public key into a PublicKey object :param source: A byte string of file contents, a unicode string filename or an asn1crypto.keys.PublicKeyInfo object :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type oscrypto.errors.AsymmetricKeyError - when the public key is incompatible with the OS crypto library OSError - when an error is returned by the OS crypto library :return: A PublicKey object """ if isinstance(source, PublicKeyInfo): public_key = source elif isinstance(source, byte_cls): public_key = parse_public(source) elif isinstance(source, str_cls): with open(source, 'rb') as f: public_key = parse_public(f.read()) else: raise TypeError(pretty_message( ''' source must be a byte string, unicode string or asn1crypto.keys.PublicKeyInfo object, not %s ''', type_name(public_key) )) return _load_key(public_key, PublicKey) def parse_pkcs12(data, password=None): """ Parses a PKCS#12 ANS.1 DER-encoded structure and extracts certs and keys :param data: A byte string of a DER-encoded PKCS#12 file :param password: A byte string of the password to any encrypted data :raises: ValueError - when any of the parameters are of the wrong type or value OSError - when an error is returned by one of the OS decryption functions :return: A three-element tuple of: 1. An asn1crypto.keys.PrivateKeyInfo object 2. An asn1crypto.x509.Certificate object 3. A list of zero or more asn1crypto.x509.Certificate objects that are "extra" certificates, possibly intermediates from the cert chain """ return _parse_pkcs12(data, password, load_private_key) def load_pkcs12(source, password=None): """ Loads a .p12 or .pfx file into a PrivateKey object and one or more Certificates objects :param source: A byte string of file contents or a unicode string filename :param password: A byte or unicode string to decrypt the PKCS12 file. Unicode strings will be encoded using UTF-8. :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type oscrypto.errors.AsymmetricKeyError - when a contained key is incompatible with the OS crypto library OSError - when an error is returned by the OS crypto library :return: A three-element tuple containing (PrivateKey, Certificate, [Certificate, ...]) """ if password is not None: if isinstance(password, str_cls): password = password.encode('utf-8') if not isinstance(password, byte_cls): raise TypeError(pretty_message( ''' password must be a byte string, not %s ''', type_name(password) )) if isinstance(source, str_cls): with open(source, 'rb') as f: source = f.read() elif not isinstance(source, byte_cls): raise TypeError(pretty_message( ''' source must be a byte string or a unicode string, not %s ''', type_name(source) )) key_info, cert_info, extra_certs_info = parse_pkcs12(source, password) key = None cert = None if key_info: key = _load_key(key_info, PrivateKey) if cert_info: cert = _load_key(cert_info.public_key, Certificate) extra_certs = [_load_key(info.public_key, Certificate) for info in extra_certs_info] return (key, cert, extra_certs) def rsa_pkcs1v15_verify(certificate_or_public_key, signature, data, hash_algorithm): """ Verifies an RSASSA-PKCS-v1.5 signature. When the hash_algorithm is "raw", the operation is identical to RSA public key decryption. That is: the data is not hashed and no ASN.1 structure with an algorithm identifier of the hash algorithm is placed in the encrypted byte string. :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte string of the signature to verify :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384", "sha512" or "raw" :raises: oscrypto.errors.SignatureError - when the signature is determined to be invalid ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library """ if certificate_or_public_key.algorithm != 'rsa': raise ValueError('The key specified is not an RSA public key') return _verify(certificate_or_public_key, signature, data, hash_algorithm) def rsa_pss_verify(certificate_or_public_key, signature, data, hash_algorithm): """ Verifies an RSASSA-PSS signature. For the PSS padding the mask gen algorithm will be mgf1 using the same hash algorithm as the signature. The salt length with be the length of the hash algorithm, and the trailer field with be the standard 0xBC byte. :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte string of the signature to verify :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384" or "sha512" :raises: oscrypto.errors.SignatureError - when the signature is determined to be invalid ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library """ cp_alg = certificate_or_public_key.algorithm if cp_alg != 'rsa' and cp_alg != 'rsassa_pss': raise ValueError('The key specified is not an RSA public key') return _verify(certificate_or_public_key, signature, data, hash_algorithm, rsa_pss_padding=True) def dsa_verify(certificate_or_public_key, signature, data, hash_algorithm): """ Verifies a DSA signature :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte string of the signature to verify :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384" or "sha512" :raises: oscrypto.errors.SignatureError - when the signature is determined to be invalid ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library """ if certificate_or_public_key.algorithm != 'dsa': raise ValueError('The key specified is not a DSA public key') return _verify(certificate_or_public_key, signature, data, hash_algorithm) def ecdsa_verify(certificate_or_public_key, signature, data, hash_algorithm): """ Verifies an ECDSA signature :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte string of the signature to verify :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384" or "sha512" :raises: oscrypto.errors.SignatureError - when the signature is determined to be invalid ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library """ if certificate_or_public_key.algorithm != 'ec': raise ValueError('The key specified is not an EC public key') return _verify(certificate_or_public_key, signature, data, hash_algorithm) def _verify(certificate_or_public_key, signature, data, hash_algorithm, rsa_pss_padding=False): """ Verifies an RSA, DSA or ECDSA signature :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte string of the signature to verify :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384", "sha512" or "raw" :param rsa_pss_padding: If PSS padding should be used for RSA keys :raises: oscrypto.errors.SignatureError - when the signature is determined to be invalid ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library """ if not isinstance(certificate_or_public_key, (Certificate, PublicKey)): raise TypeError(pretty_message( ''' certificate_or_public_key must be an instance of the Certificate or PublicKey class, not %s ''', type_name(certificate_or_public_key) )) if not isinstance(signature, byte_cls): raise TypeError(pretty_message( ''' signature must be a byte string, not %s ''', type_name(signature) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) cp_alg = certificate_or_public_key.algorithm cp_is_rsa = cp_alg == 'rsa' or cp_alg == 'rsassa_pss' valid_hash_algorithms = set(['md5', 'sha1', 'sha256', 'sha384', 'sha512']) if cp_is_rsa and not rsa_pss_padding: valid_hash_algorithms |= set(['raw']) if hash_algorithm not in valid_hash_algorithms: valid_hash_algorithms_error = '"md5", "sha1", "sha256", "sha384", "sha512"' if cp_is_rsa and not rsa_pss_padding: valid_hash_algorithms_error += ', "raw"' raise ValueError(pretty_message( ''' hash_algorithm must be one of %s, not %s ''', valid_hash_algorithms_error, repr(hash_algorithm) )) if not cp_is_rsa and rsa_pss_padding is not False: raise ValueError(pretty_message( ''' PSS padding may only be used with RSA keys - signing via a %s key was requested ''', cp_alg.upper() )) if hash_algorithm == 'raw': if len(data) > certificate_or_public_key.byte_size - 11: raise ValueError(pretty_message( ''' data must be 11 bytes shorter than the key size when hash_algorithm is "raw" - key size is %s bytes, but data is %s bytes long ''', certificate_or_public_key.byte_size, len(data) )) if _backend == 'winlegacy': if certificate_or_public_key.algorithm == 'ec': return _pure_python_ecdsa_verify(certificate_or_public_key, signature, data, hash_algorithm) return _advapi32_verify(certificate_or_public_key, signature, data, hash_algorithm, rsa_pss_padding) return _bcrypt_verify(certificate_or_public_key, signature, data, hash_algorithm, rsa_pss_padding) def _advapi32_verify(certificate_or_public_key, signature, data, hash_algorithm, rsa_pss_padding=False): """ Verifies an RSA, DSA or ECDSA signature via CryptoAPI :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte string of the signature to verify :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384", "sha512" or "raw" :param rsa_pss_padding: If PSS padding should be used for RSA keys :raises: oscrypto.errors.SignatureError - when the signature is determined to be invalid ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library """ algo = certificate_or_public_key.algorithm algo_is_rsa = algo == 'rsa' or algo == 'rsassa_pss' if algo_is_rsa and rsa_pss_padding: hash_length = { 'sha1': 20, 'sha224': 28, 'sha256': 32, 'sha384': 48, 'sha512': 64 }.get(hash_algorithm, 0) decrypted_signature = raw_rsa_public_crypt(certificate_or_public_key, signature) key_size = certificate_or_public_key.bit_size if not verify_pss_padding(hash_algorithm, hash_length, key_size, data, decrypted_signature): raise SignatureError('Signature is invalid') return if algo_is_rsa and hash_algorithm == 'raw': padded_plaintext = raw_rsa_public_crypt(certificate_or_public_key, signature) try: plaintext = remove_pkcs1v15_signature_padding(certificate_or_public_key.byte_size, padded_plaintext) if not constant_compare(plaintext, data): raise ValueError() except (ValueError): raise SignatureError('Signature is invalid') return hash_handle = None try: alg_id = { 'md5': Advapi32Const.CALG_MD5, 'sha1': Advapi32Const.CALG_SHA1, 'sha256': Advapi32Const.CALG_SHA_256, 'sha384': Advapi32Const.CALG_SHA_384, 'sha512': Advapi32Const.CALG_SHA_512, }[hash_algorithm] hash_handle_pointer = new(advapi32, 'HCRYPTHASH *') res = advapi32.CryptCreateHash( certificate_or_public_key.context_handle, alg_id, null(), 0, hash_handle_pointer ) handle_error(res) hash_handle = unwrap(hash_handle_pointer) res = advapi32.CryptHashData(hash_handle, data, len(data), 0) handle_error(res) if algo == 'dsa': # Windows doesn't use the ASN.1 Sequence for DSA signatures, # so we have to convert it here for the verification to work try: signature = DSASignature.load(signature).to_p1363() # Switch the two integers so that the reversal later will # result in the correct order half_len = len(signature) // 2 signature = signature[half_len:] + signature[:half_len] except (ValueError, OverflowError, TypeError): raise SignatureError('Signature is invalid') # The CryptoAPI expects signatures to be in little endian byte order, # which is the opposite of other systems, so we must reverse it reversed_signature = signature[::-1] res = advapi32.CryptVerifySignatureW( hash_handle, reversed_signature, len(signature), certificate_or_public_key.key_handle, null(), 0 ) handle_error(res) finally: if hash_handle: advapi32.CryptDestroyHash(hash_handle) def _bcrypt_verify(certificate_or_public_key, signature, data, hash_algorithm, rsa_pss_padding=False): """ Verifies an RSA, DSA or ECDSA signature via CNG :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte string of the signature to verify :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384", "sha512" or "raw" :param rsa_pss_padding: If PSS padding should be used for RSA keys :raises: oscrypto.errors.SignatureError - when the signature is determined to be invalid ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library """ if hash_algorithm == 'raw': digest = data else: hash_constant = { 'md5': BcryptConst.BCRYPT_MD5_ALGORITHM, 'sha1': BcryptConst.BCRYPT_SHA1_ALGORITHM, 'sha256': BcryptConst.BCRYPT_SHA256_ALGORITHM, 'sha384': BcryptConst.BCRYPT_SHA384_ALGORITHM, 'sha512': BcryptConst.BCRYPT_SHA512_ALGORITHM }[hash_algorithm] digest = getattr(hashlib, hash_algorithm)(data).digest() padding_info = null() flags = 0 cp_alg = certificate_or_public_key.algorithm cp_is_rsa = cp_alg == 'rsa' or cp_alg == 'rsassa_pss' if cp_is_rsa: if rsa_pss_padding: flags = BcryptConst.BCRYPT_PAD_PSS padding_info_struct_pointer = struct(bcrypt, 'BCRYPT_PSS_PADDING_INFO') padding_info_struct = unwrap(padding_info_struct_pointer) # This has to be assigned to a variable to prevent cffi from gc'ing it hash_buffer = buffer_from_unicode(hash_constant) padding_info_struct.pszAlgId = cast(bcrypt, 'wchar_t *', hash_buffer) padding_info_struct.cbSalt = len(digest) else: flags = BcryptConst.BCRYPT_PAD_PKCS1 padding_info_struct_pointer = struct(bcrypt, 'BCRYPT_PKCS1_PADDING_INFO') padding_info_struct = unwrap(padding_info_struct_pointer) # This has to be assigned to a variable to prevent cffi from gc'ing it if hash_algorithm == 'raw': padding_info_struct.pszAlgId = null() else: hash_buffer = buffer_from_unicode(hash_constant) padding_info_struct.pszAlgId = cast(bcrypt, 'wchar_t *', hash_buffer) padding_info = cast(bcrypt, 'void *', padding_info_struct_pointer) else: # Windows doesn't use the ASN.1 Sequence for DSA/ECDSA signatures, # so we have to convert it here for the verification to work try: signature = DSASignature.load(signature).to_p1363() except (ValueError, OverflowError, TypeError): raise SignatureError('Signature is invalid') res = bcrypt.BCryptVerifySignature( certificate_or_public_key.key_handle, padding_info, digest, len(digest), signature, len(signature), flags ) failure = res == BcryptConst.STATUS_INVALID_SIGNATURE failure = failure or res == BcryptConst.STATUS_INVALID_PARAMETER if failure: raise SignatureError('Signature is invalid') handle_error(res) def rsa_pkcs1v15_sign(private_key, data, hash_algorithm): """ Generates an RSASSA-PKCS-v1.5 signature. When the hash_algorithm is "raw", the operation is identical to RSA private key encryption. That is: the data is not hashed and no ASN.1 structure with an algorithm identifier of the hash algorithm is placed in the encrypted byte string. :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384", "sha512" or "raw" :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature """ if private_key.algorithm != 'rsa': raise ValueError('The key specified is not an RSA private key') return _sign(private_key, data, hash_algorithm) def rsa_pss_sign(private_key, data, hash_algorithm): """ Generates an RSASSA-PSS signature. For the PSS padding the mask gen algorithm will be mgf1 using the same hash algorithm as the signature. The salt length with be the length of the hash algorithm, and the trailer field with be the standard 0xBC byte. :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384" or "sha512" :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature """ pkey_alg = private_key.algorithm if pkey_alg != 'rsa' and pkey_alg != 'rsassa_pss': raise ValueError('The key specified is not an RSA private key') return _sign(private_key, data, hash_algorithm, rsa_pss_padding=True) def dsa_sign(private_key, data, hash_algorithm): """ Generates a DSA signature :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384" or "sha512" :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature """ if private_key.algorithm != 'dsa': raise ValueError('The key specified is not a DSA private key') return _sign(private_key, data, hash_algorithm) def ecdsa_sign(private_key, data, hash_algorithm): """ Generates an ECDSA signature :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384" or "sha512" :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature """ if private_key.algorithm != 'ec': raise ValueError('The key specified is not an EC private key') return _sign(private_key, data, hash_algorithm) def _sign(private_key, data, hash_algorithm, rsa_pss_padding=False): """ Generates an RSA, DSA or ECDSA signature :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384", "sha512" or "raw" :param rsa_pss_padding: If PSS padding should be used for RSA keys :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature """ if not isinstance(private_key, PrivateKey): raise TypeError(pretty_message( ''' private_key must be an instance of PrivateKey, not %s ''', type_name(private_key) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) pkey_alg = private_key.algorithm pkey_is_rsa = pkey_alg == 'rsa' or pkey_alg == 'rsassa_pss' valid_hash_algorithms = set(['md5', 'sha1', 'sha256', 'sha384', 'sha512']) if private_key.algorithm == 'rsa' and not rsa_pss_padding: valid_hash_algorithms |= set(['raw']) if hash_algorithm not in valid_hash_algorithms: valid_hash_algorithms_error = '"md5", "sha1", "sha256", "sha384", "sha512"' if pkey_is_rsa and not rsa_pss_padding: valid_hash_algorithms_error += ', "raw"' raise ValueError(pretty_message( ''' hash_algorithm must be one of %s, not %s ''', valid_hash_algorithms_error, repr(hash_algorithm) )) if not pkey_is_rsa and rsa_pss_padding is not False: raise ValueError(pretty_message( ''' PSS padding may only be used with RSA keys - signing via a %s key was requested ''', pkey_alg.upper() )) if hash_algorithm == 'raw': if len(data) > private_key.byte_size - 11: raise ValueError(pretty_message( ''' data must be 11 bytes shorter than the key size when hash_algorithm is "raw" - key size is %s bytes, but data is %s bytes long ''', private_key.byte_size, len(data) )) if _backend == 'winlegacy': if private_key.algorithm == 'ec': return _pure_python_ecdsa_sign(private_key, data, hash_algorithm) return _advapi32_sign(private_key, data, hash_algorithm, rsa_pss_padding) return _bcrypt_sign(private_key, data, hash_algorithm, rsa_pss_padding) def _advapi32_sign(private_key, data, hash_algorithm, rsa_pss_padding=False): """ Generates an RSA, DSA or ECDSA signature via CryptoAPI :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384", "sha512" or "raw" :param rsa_pss_padding: If PSS padding should be used for RSA keys :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature """ algo = private_key.algorithm algo_is_rsa = algo == 'rsa' or algo == 'rsassa_pss' if algo_is_rsa and hash_algorithm == 'raw': padded_data = add_pkcs1v15_signature_padding(private_key.byte_size, data) return raw_rsa_private_crypt(private_key, padded_data) if algo_is_rsa and rsa_pss_padding: hash_length = { 'sha1': 20, 'sha224': 28, 'sha256': 32, 'sha384': 48, 'sha512': 64 }.get(hash_algorithm, 0) padded_data = add_pss_padding(hash_algorithm, hash_length, private_key.bit_size, data) return raw_rsa_private_crypt(private_key, padded_data) if private_key.algorithm == 'dsa' and hash_algorithm == 'md5': raise ValueError(pretty_message( ''' Windows does not support md5 signatures with DSA keys ''' )) hash_handle = None try: alg_id = { 'md5': Advapi32Const.CALG_MD5, 'sha1': Advapi32Const.CALG_SHA1, 'sha256': Advapi32Const.CALG_SHA_256, 'sha384': Advapi32Const.CALG_SHA_384, 'sha512': Advapi32Const.CALG_SHA_512, }[hash_algorithm] hash_handle_pointer = new(advapi32, 'HCRYPTHASH *') res = advapi32.CryptCreateHash( private_key.context_handle, alg_id, null(), 0, hash_handle_pointer ) handle_error(res) hash_handle = unwrap(hash_handle_pointer) res = advapi32.CryptHashData(hash_handle, data, len(data), 0) handle_error(res) out_len = new(advapi32, 'DWORD *') res = advapi32.CryptSignHashW( hash_handle, Advapi32Const.AT_SIGNATURE, null(), 0, null(), out_len ) handle_error(res) buffer_length = deref(out_len) buffer_ = buffer_from_bytes(buffer_length) res = advapi32.CryptSignHashW( hash_handle, Advapi32Const.AT_SIGNATURE, null(), 0, buffer_, out_len ) handle_error(res) output = bytes_from_buffer(buffer_, deref(out_len)) # CryptoAPI outputs the signature in little endian byte order, so we # must swap it for compatibility with other systems output = output[::-1] if algo == 'dsa': # Switch the two integers because the reversal just before switched # then half_len = len(output) // 2 output = output[half_len:] + output[:half_len] # Windows doesn't use the ASN.1 Sequence for DSA signatures, # so we have to convert it here for the verification to work output = DSASignature.from_p1363(output).dump() return output finally: if hash_handle: advapi32.CryptDestroyHash(hash_handle) def _bcrypt_sign(private_key, data, hash_algorithm, rsa_pss_padding=False): """ Generates an RSA, DSA or ECDSA signature via CNG :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384", "sha512" or "raw" :param rsa_pss_padding: If PSS padding should be used for RSA keys :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature """ if hash_algorithm == 'raw': digest = data else: hash_constant = { 'md5': BcryptConst.BCRYPT_MD5_ALGORITHM, 'sha1': BcryptConst.BCRYPT_SHA1_ALGORITHM, 'sha256': BcryptConst.BCRYPT_SHA256_ALGORITHM, 'sha384': BcryptConst.BCRYPT_SHA384_ALGORITHM, 'sha512': BcryptConst.BCRYPT_SHA512_ALGORITHM }[hash_algorithm] digest = getattr(hashlib, hash_algorithm)(data).digest() padding_info = null() flags = 0 pkey_alg = private_key.algorithm pkey_is_rsa = pkey_alg == 'rsa' or pkey_alg == 'rsassa_pss' if pkey_is_rsa: if rsa_pss_padding: hash_length = { 'md5': 16, 'sha1': 20, 'sha256': 32, 'sha384': 48, 'sha512': 64 }[hash_algorithm] flags = BcryptConst.BCRYPT_PAD_PSS padding_info_struct_pointer = struct(bcrypt, 'BCRYPT_PSS_PADDING_INFO') padding_info_struct = unwrap(padding_info_struct_pointer) # This has to be assigned to a variable to prevent cffi from gc'ing it hash_buffer = buffer_from_unicode(hash_constant) padding_info_struct.pszAlgId = cast(bcrypt, 'wchar_t *', hash_buffer) padding_info_struct.cbSalt = hash_length else: flags = BcryptConst.BCRYPT_PAD_PKCS1 padding_info_struct_pointer = struct(bcrypt, 'BCRYPT_PKCS1_PADDING_INFO') padding_info_struct = unwrap(padding_info_struct_pointer) # This has to be assigned to a variable to prevent cffi from gc'ing it if hash_algorithm == 'raw': padding_info_struct.pszAlgId = null() else: hash_buffer = buffer_from_unicode(hash_constant) padding_info_struct.pszAlgId = cast(bcrypt, 'wchar_t *', hash_buffer) padding_info = cast(bcrypt, 'void *', padding_info_struct_pointer) if pkey_alg == 'dsa' and private_key.bit_size > 1024 and hash_algorithm in set(['md5', 'sha1']): raise ValueError(pretty_message( ''' Windows does not support sha1 signatures with DSA keys based on sha224, sha256 or sha512 ''' )) out_len = new(bcrypt, 'DWORD *') res = bcrypt.BCryptSignHash( private_key.key_handle, padding_info, digest, len(digest), null(), 0, out_len, flags ) handle_error(res) buffer_len = deref(out_len) buffer = buffer_from_bytes(buffer_len) if pkey_is_rsa: padding_info = cast(bcrypt, 'void *', padding_info_struct_pointer) res = bcrypt.BCryptSignHash( private_key.key_handle, padding_info, digest, len(digest), buffer, buffer_len, out_len, flags ) handle_error(res) signature = bytes_from_buffer(buffer, deref(out_len)) if not pkey_is_rsa: # Windows doesn't use the ASN.1 Sequence for DSA/ECDSA signatures, # so we have to convert it here for the verification to work signature = DSASignature.from_p1363(signature).dump() return signature def _encrypt(certificate_or_public_key, data, rsa_oaep_padding=False): """ Encrypts a value using an RSA public key :param certificate_or_public_key: A Certificate or PublicKey instance to encrypt with :param data: A byte string of the data to encrypt :param rsa_oaep_padding: If OAEP padding should be used instead of PKCS#1 v1.5 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext """ if not isinstance(certificate_or_public_key, (Certificate, PublicKey)): raise TypeError(pretty_message( ''' certificate_or_public_key must be an instance of the Certificate or PublicKey class, not %s ''', type_name(certificate_or_public_key) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) if not isinstance(rsa_oaep_padding, bool): raise TypeError(pretty_message( ''' rsa_oaep_padding must be a bool, not %s ''', type_name(rsa_oaep_padding) )) if _backend == 'winlegacy': return _advapi32_encrypt(certificate_or_public_key, data, rsa_oaep_padding) return _bcrypt_encrypt(certificate_or_public_key, data, rsa_oaep_padding) def _advapi32_encrypt(certificate_or_public_key, data, rsa_oaep_padding=False): """ Encrypts a value using an RSA public key via CryptoAPI :param certificate_or_public_key: A Certificate or PublicKey instance to encrypt with :param data: A byte string of the data to encrypt :param rsa_oaep_padding: If OAEP padding should be used instead of PKCS#1 v1.5 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext """ flags = 0 if rsa_oaep_padding: flags = Advapi32Const.CRYPT_OAEP out_len = new(advapi32, 'DWORD *', len(data)) res = advapi32.CryptEncrypt( certificate_or_public_key.ex_key_handle, null(), True, flags, null(), out_len, 0 ) handle_error(res) buffer_len = deref(out_len) buffer = buffer_from_bytes(buffer_len) write_to_buffer(buffer, data) pointer_set(out_len, len(data)) res = advapi32.CryptEncrypt( certificate_or_public_key.ex_key_handle, null(), True, flags, buffer, out_len, buffer_len ) handle_error(res) return bytes_from_buffer(buffer, deref(out_len))[::-1] def _bcrypt_encrypt(certificate_or_public_key, data, rsa_oaep_padding=False): """ Encrypts a value using an RSA public key via CNG :param certificate_or_public_key: A Certificate or PublicKey instance to encrypt with :param data: A byte string of the data to encrypt :param rsa_oaep_padding: If OAEP padding should be used instead of PKCS#1 v1.5 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext """ flags = BcryptConst.BCRYPT_PAD_PKCS1 if rsa_oaep_padding is True: flags = BcryptConst.BCRYPT_PAD_OAEP padding_info_struct_pointer = struct(bcrypt, 'BCRYPT_OAEP_PADDING_INFO') padding_info_struct = unwrap(padding_info_struct_pointer) # This has to be assigned to a variable to prevent cffi from gc'ing it hash_buffer = buffer_from_unicode(BcryptConst.BCRYPT_SHA1_ALGORITHM) padding_info_struct.pszAlgId = cast(bcrypt, 'wchar_t *', hash_buffer) padding_info_struct.pbLabel = null() padding_info_struct.cbLabel = 0 padding_info = cast(bcrypt, 'void *', padding_info_struct_pointer) else: padding_info = null() out_len = new(bcrypt, 'ULONG *') res = bcrypt.BCryptEncrypt( certificate_or_public_key.key_handle, data, len(data), padding_info, null(), 0, null(), 0, out_len, flags ) handle_error(res) buffer_len = deref(out_len) buffer = buffer_from_bytes(buffer_len) res = bcrypt.BCryptEncrypt( certificate_or_public_key.key_handle, data, len(data), padding_info, null(), 0, buffer, buffer_len, out_len, flags ) handle_error(res) return bytes_from_buffer(buffer, deref(out_len)) def _decrypt(private_key, ciphertext, rsa_oaep_padding=False): """ Encrypts a value using an RSA private key :param private_key: A PrivateKey instance to decrypt with :param ciphertext: A byte string of the data to decrypt :param rsa_oaep_padding: If OAEP padding should be used instead of PKCS#1 v1.5 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if not isinstance(private_key, PrivateKey): raise TypeError(pretty_message( ''' private_key must be an instance of the PrivateKey class, not %s ''', type_name(private_key) )) if not isinstance(ciphertext, byte_cls): raise TypeError(pretty_message( ''' ciphertext must be a byte string, not %s ''', type_name(ciphertext) )) if not isinstance(rsa_oaep_padding, bool): raise TypeError(pretty_message( ''' rsa_oaep_padding must be a bool, not %s ''', type_name(rsa_oaep_padding) )) if _backend == 'winlegacy': return _advapi32_decrypt(private_key, ciphertext, rsa_oaep_padding) return _bcrypt_decrypt(private_key, ciphertext, rsa_oaep_padding) def _advapi32_decrypt(private_key, ciphertext, rsa_oaep_padding=False): """ Encrypts a value using an RSA private key via CryptoAPI :param private_key: A PrivateKey instance to decrypt with :param ciphertext: A byte string of the data to decrypt :param rsa_oaep_padding: If OAEP padding should be used instead of PKCS#1 v1.5 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ flags = 0 if rsa_oaep_padding: flags = Advapi32Const.CRYPT_OAEP ciphertext = ciphertext[::-1] buffer = buffer_from_bytes(ciphertext) out_len = new(advapi32, 'DWORD *', len(ciphertext)) res = advapi32.CryptDecrypt( private_key.ex_key_handle, null(), True, flags, buffer, out_len ) handle_error(res) return bytes_from_buffer(buffer, deref(out_len)) def _bcrypt_decrypt(private_key, ciphertext, rsa_oaep_padding=False): """ Encrypts a value using an RSA private key via CNG :param private_key: A PrivateKey instance to decrypt with :param ciphertext: A byte string of the data to decrypt :param rsa_oaep_padding: If OAEP padding should be used instead of PKCS#1 v1.5 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ flags = BcryptConst.BCRYPT_PAD_PKCS1 if rsa_oaep_padding is True: flags = BcryptConst.BCRYPT_PAD_OAEP padding_info_struct_pointer = struct(bcrypt, 'BCRYPT_OAEP_PADDING_INFO') padding_info_struct = unwrap(padding_info_struct_pointer) # This has to be assigned to a variable to prevent cffi from gc'ing it hash_buffer = buffer_from_unicode(BcryptConst.BCRYPT_SHA1_ALGORITHM) padding_info_struct.pszAlgId = cast(bcrypt, 'wchar_t *', hash_buffer) padding_info_struct.pbLabel = null() padding_info_struct.cbLabel = 0 padding_info = cast(bcrypt, 'void *', padding_info_struct_pointer) else: padding_info = null() out_len = new(bcrypt, 'ULONG *') res = bcrypt.BCryptDecrypt( private_key.key_handle, ciphertext, len(ciphertext), padding_info, null(), 0, null(), 0, out_len, flags ) handle_error(res) buffer_len = deref(out_len) buffer = buffer_from_bytes(buffer_len) res = bcrypt.BCryptDecrypt( private_key.key_handle, ciphertext, len(ciphertext), padding_info, null(), 0, buffer, buffer_len, out_len, flags ) handle_error(res) return bytes_from_buffer(buffer, deref(out_len)) def rsa_pkcs1v15_encrypt(certificate_or_public_key, data): """ Encrypts a byte string using an RSA public key or certificate. Uses PKCS#1 v1.5 padding. :param certificate_or_public_key: A PublicKey or Certificate object :param data: A byte string, with a maximum length 11 bytes less than the key length (in bytes) :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the encrypted data """ return _encrypt(certificate_or_public_key, data) def rsa_pkcs1v15_decrypt(private_key, ciphertext): """ Decrypts a byte string using an RSA private key. Uses PKCS#1 v1.5 padding. :param private_key: A PrivateKey object :param ciphertext: A byte string of the encrypted data :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the original plaintext """ return _decrypt(private_key, ciphertext) def rsa_oaep_encrypt(certificate_or_public_key, data): """ Encrypts a byte string using an RSA public key or certificate. Uses PKCS#1 OAEP padding with SHA1. :param certificate_or_public_key: A PublicKey or Certificate object :param data: A byte string, with a maximum length 41 bytes (or more) less than the key length (in bytes) :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the encrypted data """ return _encrypt(certificate_or_public_key, data, rsa_oaep_padding=True) def rsa_oaep_decrypt(private_key, ciphertext): """ Decrypts a byte string using an RSA private key. Uses PKCS#1 OAEP padding with SHA1. :param private_key: A PrivateKey object :param ciphertext: A byte string of the encrypted data :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the original plaintext """ return _decrypt(private_key, ciphertext, rsa_oaep_padding=True) PK!xx symmetric.pynu[# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function from .._errors import pretty_message from .._ffi import ( buffer_from_bytes, bytes_from_buffer, deref, new, null, pointer_set, struct, struct_bytes, unwrap, write_to_buffer, ) from .util import rand_bytes from .. import backend from .._types import type_name, byte_cls _backend = backend() if _backend == 'winlegacy': from ._advapi32 import advapi32, Advapi32Const, handle_error, open_context_handle, close_context_handle else: from ._cng import bcrypt, BcryptConst, handle_error, open_alg_handle, close_alg_handle __all__ = [ 'aes_cbc_no_padding_decrypt', 'aes_cbc_no_padding_encrypt', 'aes_cbc_pkcs7_decrypt', 'aes_cbc_pkcs7_encrypt', 'des_cbc_pkcs5_decrypt', 'des_cbc_pkcs5_encrypt', 'rc2_cbc_pkcs5_decrypt', 'rc2_cbc_pkcs5_encrypt', 'rc4_decrypt', 'rc4_encrypt', 'tripledes_cbc_pkcs5_decrypt', 'tripledes_cbc_pkcs5_encrypt', ] def aes_cbc_no_padding_encrypt(key, data, iv): """ Encrypts plaintext using AES in CBC mode with a 128, 192 or 256 bit key and no padding. This means the ciphertext must be an exact multiple of 16 bytes long. :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - either a byte string 16-bytes long or None to generate an IV :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext) """ if len(key) not in [16, 24, 32]: raise ValueError(pretty_message( ''' key must be either 16, 24 or 32 bytes (128, 192 or 256 bits) long - is %s ''', len(key) )) if not iv: iv = rand_bytes(16) elif len(iv) != 16: raise ValueError(pretty_message( ''' iv must be 16 bytes long - is %s ''', len(iv) )) if len(data) % 16 != 0: raise ValueError(pretty_message( ''' data must be a multiple of 16 bytes long - is %s ''', len(data) )) return (iv, _encrypt('aes', key, data, iv, False)) def aes_cbc_no_padding_decrypt(key, data, iv): """ Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key and no padding. :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector - a byte string 16-bytes long :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if len(key) not in [16, 24, 32]: raise ValueError(pretty_message( ''' key must be either 16, 24 or 32 bytes (128, 192 or 256 bits) long - is %s ''', len(key) )) if len(iv) != 16: raise ValueError(pretty_message( ''' iv must be 16 bytes long - is %s ''', len(iv) )) return _decrypt('aes', key, data, iv, False) def aes_cbc_pkcs7_encrypt(key, data, iv): """ Encrypts plaintext using AES in CBC mode with a 128, 192 or 256 bit key and PKCS#7 padding. :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - either a byte string 16-bytes long or None to generate an IV :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext) """ if len(key) not in [16, 24, 32]: raise ValueError(pretty_message( ''' key must be either 16, 24 or 32 bytes (128, 192 or 256 bits) long - is %s ''', len(key) )) if not iv: iv = rand_bytes(16) elif len(iv) != 16: raise ValueError(pretty_message( ''' iv must be 16 bytes long - is %s ''', len(iv) )) return (iv, _encrypt('aes', key, data, iv, True)) def aes_cbc_pkcs7_decrypt(key, data, iv): """ Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector - a byte string 16-bytes long :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if len(key) not in [16, 24, 32]: raise ValueError(pretty_message( ''' key must be either 16, 24 or 32 bytes (128, 192 or 256 bits) long - is %s ''', len(key) )) if len(iv) != 16: raise ValueError(pretty_message( ''' iv must be 16 bytes long - is %s ''', len(iv) )) return _decrypt('aes', key, data, iv, True) def rc4_encrypt(key, data): """ Encrypts plaintext using RC4 with a 40-128 bit key :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext """ if len(key) < 5 or len(key) > 16: raise ValueError(pretty_message( ''' key must be 5 to 16 bytes (40 to 128 bits) long - is %s ''', len(key) )) return _encrypt('rc4', key, data, None, None) def rc4_decrypt(key, data): """ Decrypts RC4 ciphertext using a 40-128 bit key :param key: The encryption key - a byte string 5-16 bytes long :param data: The ciphertext - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if len(key) < 5 or len(key) > 16: raise ValueError(pretty_message( ''' key must be 5 to 16 bytes (40 to 128 bits) long - is %s ''', len(key) )) return _decrypt('rc4', key, data, None, None) def rc2_cbc_pkcs5_encrypt(key, data, iv): """ Encrypts plaintext using RC2 with a 64 bit key :param key: The encryption key - a byte string 8 bytes long :param data: The plaintext - a byte string :param iv: The 8-byte initialization vector to use - a byte string - set as None to generate an appropriate one :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext) """ if len(key) < 5 or len(key) > 16: raise ValueError(pretty_message( ''' key must be 5 to 16 bytes (40 to 128 bits) long - is %s ''', len(key) )) if not iv: iv = rand_bytes(8) elif len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - is %s ''', len(iv) )) return (iv, _encrypt('rc2', key, data, iv, True)) def rc2_cbc_pkcs5_decrypt(key, data, iv): """ Decrypts RC2 ciphertext using a 64 bit key :param key: The encryption key - a byte string 8 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector used for encryption - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if len(key) < 5 or len(key) > 16: raise ValueError(pretty_message( ''' key must be 5 to 16 bytes (40 to 128 bits) long - is %s ''', len(key) )) if len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - is %s ''', len(iv) )) return _decrypt('rc2', key, data, iv, True) def tripledes_cbc_pkcs5_encrypt(key, data, iv): """ Encrypts plaintext using 3DES in either 2 or 3 key mode :param key: The encryption key - a byte string 16 or 24 bytes long (2 or 3 key mode) :param data: The plaintext - a byte string :param iv: The 8-byte initialization vector to use - a byte string - set as None to generate an appropriate one :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext) """ if len(key) != 16 and len(key) != 24: raise ValueError(pretty_message( ''' key must be 16 bytes (2 key) or 24 bytes (3 key) long - is %s ''', len(key) )) if not iv: iv = rand_bytes(8) elif len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - is %s ''', len(iv) )) cipher = 'tripledes_3key' if len(key) == 16: cipher = 'tripledes_2key' return (iv, _encrypt(cipher, key, data, iv, True)) def tripledes_cbc_pkcs5_decrypt(key, data, iv): """ Decrypts 3DES ciphertext in either 2 or 3 key mode :param key: The encryption key - a byte string 16 or 24 bytes long (2 or 3 key mode) :param data: The ciphertext - a byte string :param iv: The initialization vector used for encryption - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if len(key) != 16 and len(key) != 24: raise ValueError(pretty_message( ''' key must be 16 bytes (2 key) or 24 bytes (3 key) long - is %s ''', len(key) )) if len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - is %s ''', len(iv) )) cipher = 'tripledes_3key' if len(key) == 16: cipher = 'tripledes_2key' return _decrypt(cipher, key, data, iv, True) def des_cbc_pkcs5_encrypt(key, data, iv): """ Encrypts plaintext using DES with a 56 bit key :param key: The encryption key - a byte string 8 bytes long (includes error correction bits) :param data: The plaintext - a byte string :param iv: The 8-byte initialization vector to use - a byte string - set as None to generate an appropriate one :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext) """ if len(key) != 8: raise ValueError(pretty_message( ''' key must be 8 bytes (56 bits + 8 parity bits) long - is %s ''', len(key) )) if not iv: iv = rand_bytes(8) elif len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - is %s ''', len(iv) )) return (iv, _encrypt('des', key, data, iv, True)) def des_cbc_pkcs5_decrypt(key, data, iv): """ Decrypts DES ciphertext using a 56 bit key :param key: The encryption key - a byte string 8 bytes long (includes error correction bits) :param data: The ciphertext - a byte string :param iv: The initialization vector used for encryption - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if len(key) != 8: raise ValueError(pretty_message( ''' key must be 8 bytes (56 bits + 8 parity bits) long - is %s ''', len(key) )) if len(iv) != 8: raise ValueError(pretty_message( ''' iv must be 8 bytes long - is %s ''', len(iv) )) return _decrypt('des', key, data, iv, True) def _advapi32_create_handles(cipher, key, iv): """ Creates an HCRYPTPROV and HCRYPTKEY for symmetric encryption/decryption. The HCRYPTPROV must be released by close_context_handle() and the HCRYPTKEY must be released by advapi32.CryptDestroyKey() when done. :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: A byte string of the symmetric key :param iv: The initialization vector - a byte string - unused for RC4 :return: A tuple of (HCRYPTPROV, HCRYPTKEY) """ context_handle = None if cipher == 'aes': algorithm_id = { 16: Advapi32Const.CALG_AES_128, 24: Advapi32Const.CALG_AES_192, 32: Advapi32Const.CALG_AES_256, }[len(key)] else: algorithm_id = { 'des': Advapi32Const.CALG_DES, 'tripledes_2key': Advapi32Const.CALG_3DES_112, 'tripledes_3key': Advapi32Const.CALG_3DES, 'rc2': Advapi32Const.CALG_RC2, 'rc4': Advapi32Const.CALG_RC4, }[cipher] provider = Advapi32Const.MS_ENH_RSA_AES_PROV context_handle = open_context_handle(provider, verify_only=False) blob_header_pointer = struct(advapi32, 'BLOBHEADER') blob_header = unwrap(blob_header_pointer) blob_header.bType = Advapi32Const.PLAINTEXTKEYBLOB blob_header.bVersion = Advapi32Const.CUR_BLOB_VERSION blob_header.reserved = 0 blob_header.aiKeyAlg = algorithm_id blob_struct_pointer = struct(advapi32, 'PLAINTEXTKEYBLOB') blob_struct = unwrap(blob_struct_pointer) blob_struct.hdr = blob_header blob_struct.dwKeySize = len(key) blob = struct_bytes(blob_struct_pointer) + key flags = 0 if cipher in set(['rc2', 'rc4']) and len(key) == 5: flags = Advapi32Const.CRYPT_NO_SALT key_handle_pointer = new(advapi32, 'HCRYPTKEY *') res = advapi32.CryptImportKey( context_handle, blob, len(blob), null(), flags, key_handle_pointer ) handle_error(res) key_handle = unwrap(key_handle_pointer) if cipher == 'rc2': buf = new(advapi32, 'DWORD *', len(key) * 8) res = advapi32.CryptSetKeyParam( key_handle, Advapi32Const.KP_EFFECTIVE_KEYLEN, buf, 0 ) handle_error(res) if cipher != 'rc4': res = advapi32.CryptSetKeyParam( key_handle, Advapi32Const.KP_IV, iv, 0 ) handle_error(res) buf = new(advapi32, 'DWORD *', Advapi32Const.CRYPT_MODE_CBC) res = advapi32.CryptSetKeyParam( key_handle, Advapi32Const.KP_MODE, buf, 0 ) handle_error(res) buf = new(advapi32, 'DWORD *', Advapi32Const.PKCS5_PADDING) res = advapi32.CryptSetKeyParam( key_handle, Advapi32Const.KP_PADDING, buf, 0 ) handle_error(res) return (context_handle, key_handle) def _bcrypt_create_key_handle(cipher, key): """ Creates a BCRYPT_KEY_HANDLE for symmetric encryption/decryption. The handle must be released by bcrypt.BCryptDestroyKey() when done. :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: A byte string of the symmetric key :return: A BCRYPT_KEY_HANDLE """ alg_handle = None alg_constant = { 'aes': BcryptConst.BCRYPT_AES_ALGORITHM, 'des': BcryptConst.BCRYPT_DES_ALGORITHM, 'tripledes_2key': BcryptConst.BCRYPT_3DES_112_ALGORITHM, 'tripledes_3key': BcryptConst.BCRYPT_3DES_ALGORITHM, 'rc2': BcryptConst.BCRYPT_RC2_ALGORITHM, 'rc4': BcryptConst.BCRYPT_RC4_ALGORITHM, }[cipher] try: alg_handle = open_alg_handle(alg_constant) blob_type = BcryptConst.BCRYPT_KEY_DATA_BLOB blob_struct_pointer = struct(bcrypt, 'BCRYPT_KEY_DATA_BLOB_HEADER') blob_struct = unwrap(blob_struct_pointer) blob_struct.dwMagic = BcryptConst.BCRYPT_KEY_DATA_BLOB_MAGIC blob_struct.dwVersion = BcryptConst.BCRYPT_KEY_DATA_BLOB_VERSION1 blob_struct.cbKeyData = len(key) blob = struct_bytes(blob_struct_pointer) + key if cipher == 'rc2': buf = new(bcrypt, 'DWORD *', len(key) * 8) res = bcrypt.BCryptSetProperty( alg_handle, BcryptConst.BCRYPT_EFFECTIVE_KEY_LENGTH, buf, 4, 0 ) handle_error(res) key_handle_pointer = new(bcrypt, 'BCRYPT_KEY_HANDLE *') res = bcrypt.BCryptImportKey( alg_handle, null(), blob_type, key_handle_pointer, null(), 0, blob, len(blob), 0 ) handle_error(res) return unwrap(key_handle_pointer) finally: if alg_handle: close_alg_handle(alg_handle) def _encrypt(cipher, key, data, iv, padding): """ Encrypts plaintext :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - a byte string - unused for RC4 :param padding: Boolean, if padding should be used - unused for RC4 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext """ if not isinstance(key, byte_cls): raise TypeError(pretty_message( ''' key must be a byte string, not %s ''', type_name(key) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) if cipher != 'rc4' and not isinstance(iv, byte_cls): raise TypeError(pretty_message( ''' iv must be a byte string, not %s ''', type_name(iv) )) if cipher != 'rc4' and not padding: # AES in CBC mode can be allowed with no padding if # the data is an exact multiple of the block size if not (cipher == 'aes' and len(data) % 16 == 0): raise ValueError('padding must be specified') if _backend == 'winlegacy': return _advapi32_encrypt(cipher, key, data, iv, padding) return _bcrypt_encrypt(cipher, key, data, iv, padding) def _advapi32_encrypt(cipher, key, data, iv, padding): """ Encrypts plaintext via CryptoAPI :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - a byte string - unused for RC4 :param padding: Boolean, if padding should be used - unused for RC4 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext """ context_handle = None key_handle = None try: context_handle, key_handle = _advapi32_create_handles(cipher, key, iv) out_len = new(advapi32, 'DWORD *', len(data)) res = advapi32.CryptEncrypt( key_handle, null(), True, 0, null(), out_len, 0 ) handle_error(res) buffer_len = deref(out_len) buffer = buffer_from_bytes(buffer_len) write_to_buffer(buffer, data) pointer_set(out_len, len(data)) res = advapi32.CryptEncrypt( key_handle, null(), True, 0, buffer, out_len, buffer_len ) handle_error(res) output = bytes_from_buffer(buffer, deref(out_len)) # Remove padding when not required. CryptoAPI doesn't support this, so # we just manually remove it. if cipher == 'aes' and not padding and len(output) == len(data) + 16: output = output[:-16] return output finally: if key_handle: advapi32.CryptDestroyKey(key_handle) if context_handle: close_context_handle(context_handle) def _bcrypt_encrypt(cipher, key, data, iv, padding): """ Encrypts plaintext via CNG :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - a byte string - unused for RC4 :param padding: Boolean, if padding should be used - unused for RC4 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext """ key_handle = None try: key_handle = _bcrypt_create_key_handle(cipher, key) if iv is None: iv_len = 0 else: iv_len = len(iv) flags = 0 if padding is True: flags = BcryptConst.BCRYPT_BLOCK_PADDING out_len = new(bcrypt, 'ULONG *') res = bcrypt.BCryptEncrypt( key_handle, data, len(data), null(), null(), 0, null(), 0, out_len, flags ) handle_error(res) buffer_len = deref(out_len) buffer = buffer_from_bytes(buffer_len) iv_buffer = buffer_from_bytes(iv) if iv else null() res = bcrypt.BCryptEncrypt( key_handle, data, len(data), null(), iv_buffer, iv_len, buffer, buffer_len, out_len, flags ) handle_error(res) return bytes_from_buffer(buffer, deref(out_len)) finally: if key_handle: bcrypt.BCryptDestroyKey(key_handle) def _decrypt(cipher, key, data, iv, padding): """ Decrypts AES/RC4/RC2/3DES/DES ciphertext :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector - a byte string - unused for RC4 :param padding: Boolean, if padding should be used - unused for RC4 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ if not isinstance(key, byte_cls): raise TypeError(pretty_message( ''' key must be a byte string, not %s ''', type_name(key) )) if not isinstance(data, byte_cls): raise TypeError(pretty_message( ''' data must be a byte string, not %s ''', type_name(data) )) if cipher != 'rc4' and not isinstance(iv, byte_cls): raise TypeError(pretty_message( ''' iv must be a byte string, not %s ''', type_name(iv) )) if cipher not in set(['rc4', 'aes']) and not padding: raise ValueError('padding must be specified') if _backend == 'winlegacy': return _advapi32_decrypt(cipher, key, data, iv, padding) return _bcrypt_decrypt(cipher, key, data, iv, padding) def _advapi32_decrypt(cipher, key, data, iv, padding): """ Decrypts AES/RC4/RC2/3DES/DES ciphertext via CryptoAPI :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector - a byte string - unused for RC4 :param padding: Boolean, if padding should be used - unused for RC4 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ context_handle = None key_handle = None try: context_handle, key_handle = _advapi32_create_handles(cipher, key, iv) if cipher == 'aes' and not padding and len(data) % 16 != 0: raise ValueError('Invalid data - ciphertext length must be a multiple of 16') buffer = buffer_from_bytes(data) out_len = new(advapi32, 'DWORD *', len(data)) res = advapi32.CryptDecrypt( key_handle, null(), # To skip padding, we have to tell the API that this is not # the final block False if cipher == 'aes' and not padding else True, 0, buffer, out_len ) handle_error(res) return bytes_from_buffer(buffer, deref(out_len)) finally: if key_handle: advapi32.CryptDestroyKey(key_handle) if context_handle: close_context_handle(context_handle) def _bcrypt_decrypt(cipher, key, data, iv, padding): """ Decrypts AES/RC4/RC2/3DES/DES ciphertext via CNG :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector - a byte string - unused for RC4 :param padding: Boolean, if padding should be used - unused for RC4 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext """ key_handle = None try: key_handle = _bcrypt_create_key_handle(cipher, key) if iv is None: iv_len = 0 else: iv_len = len(iv) flags = 0 if padding is True: flags = BcryptConst.BCRYPT_BLOCK_PADDING out_len = new(bcrypt, 'ULONG *') res = bcrypt.BCryptDecrypt( key_handle, data, len(data), null(), null(), 0, null(), 0, out_len, flags ) handle_error(res) buffer_len = deref(out_len) buffer = buffer_from_bytes(buffer_len) iv_buffer = buffer_from_bytes(iv) if iv else null() res = bcrypt.BCryptDecrypt( key_handle, data, len(data), null(), iv_buffer, iv_len, buffer, buffer_len, out_len, flags ) handle_error(res) return bytes_from_buffer(buffer, deref(out_len)) finally: if key_handle: bcrypt.BCryptDestroyKey(key_handle) PK!}tls.pynu[# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import sys import re import socket as socket_ import select import numbers from .._asn1 import Certificate as Asn1Certificate from .._errors import pretty_message from .._ffi import ( buffer_from_bytes, buffer_from_unicode, bytes_from_buffer, cast, deref, is_null, native, new, null, ref, sizeof, struct, unwrap, write_to_buffer, ) from ._secur32 import secur32, Secur32Const, handle_error from ._crypt32 import crypt32, Crypt32Const, handle_error as handle_crypt32_error from ._kernel32 import kernel32 from .._types import type_name, str_cls, byte_cls, int_types from ..errors import TLSError, TLSVerificationError, TLSDisconnectError, TLSGracefulDisconnectError from .._tls import ( detect_client_auth_request, detect_other_protocol, extract_chain, get_dh_params_length, parse_alert, parse_session_info, raise_client_auth, raise_dh_params, raise_disconnection, raise_expired_not_yet_valid, raise_handshake, raise_hostname, raise_no_issuer, raise_protocol_error, raise_protocol_version, raise_revoked, raise_self_signed, raise_verification, raise_weak_signature, ) from .asymmetric import load_certificate, Certificate from ..keys import parse_certificate if sys.version_info < (3,): range = xrange # noqa socket_error_cls = socket_.error else: socket_error_cls = WindowsError if sys.version_info < (3, 7): Pattern = re._pattern_type else: Pattern = re.Pattern __all__ = [ 'TLSSession', 'TLSSocket', ] _line_regex = re.compile(b'(\r\n|\r|\n)') _gwv = sys.getwindowsversion() _win_version_info = (_gwv[0], _gwv[1]) class _TLSDowngradeError(TLSVerificationError): pass class _TLSRetryError(TLSError): """ TLSv1.2 on Windows 7 and 8 seems to have isuses with some DHE_RSA ServerKeyExchange messages due to variable length integer encoding. This exception is used to trigger a reconnection to attempt the handshake again. """ pass class TLSSession(object): """ A TLS session object that multiple TLSSocket objects can share for the sake of session reuse """ _protocols = None _ciphers = None _manual_validation = None _extra_trust_roots = None _credentials_handle = None def __init__(self, protocol=None, manual_validation=False, extra_trust_roots=None): """ :param protocol: A unicode string or set of unicode strings representing allowable protocols to negotiate with the server: - "TLSv1.2" - "TLSv1.1" - "TLSv1" - "SSLv3" Default is: {"TLSv1", "TLSv1.1", "TLSv1.2"} :param manual_validation: If certificate and certificate path validation should be skipped and left to the developer to implement :param extra_trust_roots: A list containing one or more certificates to be treated as trust roots, in one of the following formats: - A byte string of the DER encoded certificate - A unicode string of the certificate filename - An asn1crypto.x509.Certificate object - An oscrypto.asymmetric.Certificate object :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library """ if not isinstance(manual_validation, bool): raise TypeError(pretty_message( ''' manual_validation must be a boolean, not %s ''', type_name(manual_validation) )) self._manual_validation = manual_validation if protocol is None: protocol = set(['TLSv1', 'TLSv1.1', 'TLSv1.2']) if isinstance(protocol, str_cls): protocol = set([protocol]) elif not isinstance(protocol, set): raise TypeError(pretty_message( ''' protocol must be a unicode string or set of unicode strings, not %s ''', type_name(protocol) )) unsupported_protocols = protocol - set(['SSLv3', 'TLSv1', 'TLSv1.1', 'TLSv1.2']) if unsupported_protocols: raise ValueError(pretty_message( ''' protocol must contain only the unicode strings "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2", not %s ''', repr(unsupported_protocols) )) self._protocols = protocol self._extra_trust_roots = [] if extra_trust_roots: for extra_trust_root in extra_trust_roots: if isinstance(extra_trust_root, Certificate): extra_trust_root = extra_trust_root.asn1 elif isinstance(extra_trust_root, byte_cls): extra_trust_root = parse_certificate(extra_trust_root) elif isinstance(extra_trust_root, str_cls): with open(extra_trust_root, 'rb') as f: extra_trust_root = parse_certificate(f.read()) elif not isinstance(extra_trust_root, Asn1Certificate): raise TypeError(pretty_message( ''' extra_trust_roots must be a list of byte strings, unicode strings, asn1crypto.x509.Certificate objects or oscrypto.asymmetric.Certificate objects, not %s ''', type_name(extra_trust_root) )) self._extra_trust_roots.append(extra_trust_root) self._obtain_credentials() def _obtain_credentials(self): """ Obtains a credentials handle from secur32.dll for use with SChannel """ protocol_values = { 'SSLv3': Secur32Const.SP_PROT_SSL3_CLIENT, 'TLSv1': Secur32Const.SP_PROT_TLS1_CLIENT, 'TLSv1.1': Secur32Const.SP_PROT_TLS1_1_CLIENT, 'TLSv1.2': Secur32Const.SP_PROT_TLS1_2_CLIENT, } protocol_bit_mask = 0 for key, value in protocol_values.items(): if key in self._protocols: protocol_bit_mask |= value algs = [ Secur32Const.CALG_AES_128, Secur32Const.CALG_AES_256, Secur32Const.CALG_3DES, Secur32Const.CALG_SHA1, Secur32Const.CALG_ECDHE, Secur32Const.CALG_DH_EPHEM, Secur32Const.CALG_RSA_KEYX, Secur32Const.CALG_RSA_SIGN, Secur32Const.CALG_ECDSA, Secur32Const.CALG_DSS_SIGN, ] if 'TLSv1.2' in self._protocols: algs.extend([ Secur32Const.CALG_SHA512, Secur32Const.CALG_SHA384, Secur32Const.CALG_SHA256, ]) alg_array = new(secur32, 'ALG_ID[%s]' % len(algs)) for index, alg in enumerate(algs): alg_array[index] = alg flags = Secur32Const.SCH_USE_STRONG_CRYPTO | Secur32Const.SCH_CRED_NO_DEFAULT_CREDS if not self._manual_validation and not self._extra_trust_roots: flags |= Secur32Const.SCH_CRED_AUTO_CRED_VALIDATION else: flags |= Secur32Const.SCH_CRED_MANUAL_CRED_VALIDATION schannel_cred_pointer = struct(secur32, 'SCHANNEL_CRED') schannel_cred = unwrap(schannel_cred_pointer) schannel_cred.dwVersion = Secur32Const.SCHANNEL_CRED_VERSION schannel_cred.cCreds = 0 schannel_cred.paCred = null() schannel_cred.hRootStore = null() schannel_cred.cMappers = 0 schannel_cred.aphMappers = null() schannel_cred.cSupportedAlgs = len(alg_array) schannel_cred.palgSupportedAlgs = alg_array schannel_cred.grbitEnabledProtocols = protocol_bit_mask schannel_cred.dwMinimumCipherStrength = 0 schannel_cred.dwMaximumCipherStrength = 0 # Default session lifetime is 10 hours schannel_cred.dwSessionLifespan = 0 schannel_cred.dwFlags = flags schannel_cred.dwCredFormat = 0 cred_handle_pointer = new(secur32, 'CredHandle *') result = secur32.AcquireCredentialsHandleW( null(), Secur32Const.UNISP_NAME, Secur32Const.SECPKG_CRED_OUTBOUND, null(), schannel_cred_pointer, null(), null(), cred_handle_pointer, null() ) handle_error(result) self._credentials_handle = cred_handle_pointer def __del__(self): if self._credentials_handle: result = secur32.FreeCredentialsHandle(self._credentials_handle) handle_error(result) self._credentials_handle = None class TLSSocket(object): """ A wrapper around a socket.socket that adds TLS """ _socket = None _session = None _context_handle_pointer = None _context_flags = None _hostname = None _header_size = None _message_size = None _trailer_size = None _received_bytes = None _decrypted_bytes = None _encrypt_desc = None _encrypt_buffers = None _encrypt_data_buffer = None _decrypt_desc = None _decrypt_buffers = None _decrypt_data_buffer = None _certificate = None _intermediates = None _protocol = None _cipher_suite = None _compression = None _session_id = None _session_ticket = None _remote_closed = False @classmethod def wrap(cls, socket, hostname, session=None): """ Takes an existing socket and adds TLS :param socket: A socket.socket object to wrap with TLS :param hostname: A unicode string of the hostname or IP the socket is connected to :param session: An existing TLSSession object to allow for session reuse, specific protocol or manual certificate validation :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library """ if not isinstance(socket, socket_.socket): raise TypeError(pretty_message( ''' socket must be an instance of socket.socket, not %s ''', type_name(socket) )) if not isinstance(hostname, str_cls): raise TypeError(pretty_message( ''' hostname must be a unicode string, not %s ''', type_name(hostname) )) if session is not None and not isinstance(session, TLSSession): raise TypeError(pretty_message( ''' session must be an instance of oscrypto.tls.TLSSession, not %s ''', type_name(session) )) new_socket = cls(None, None, session=session) new_socket._socket = socket new_socket._hostname = hostname # Since we don't create the socket connection here, we can't try to # reconnect with a lower version of the TLS protocol, so we just # move the data to public exception type TLSVerificationError() try: new_socket._handshake() except (_TLSDowngradeError) as e: new_e = TLSVerificationError(e.message, e.certificate) raise new_e except (_TLSRetryError) as e: new_e = TLSError(e.message) raise new_e return new_socket def __init__(self, address, port, timeout=10, session=None): """ :param address: A unicode string of the domain name or IP address to connect to :param port: An integer of the port number to connect to :param timeout: An integer timeout to use for the socket :param session: An oscrypto.tls.TLSSession object to allow for session reuse and controlling the protocols and validation performed """ self._received_bytes = b'' self._decrypted_bytes = b'' if address is None and port is None: self._socket = None else: if not isinstance(address, str_cls): raise TypeError(pretty_message( ''' address must be a unicode string, not %s ''', type_name(address) )) if not isinstance(port, int_types): raise TypeError(pretty_message( ''' port must be an integer, not %s ''', type_name(port) )) if timeout is not None and not isinstance(timeout, numbers.Number): raise TypeError(pretty_message( ''' timeout must be a number, not %s ''', type_name(timeout) )) self._socket = socket_.create_connection((address, port), timeout) self._socket.settimeout(timeout) if session is None: session = TLSSession() elif not isinstance(session, TLSSession): raise TypeError(pretty_message( ''' session must be an instance of oscrypto.tls.TLSSession, not %s ''', type_name(session) )) self._session = session if self._socket: self._hostname = address try: self._handshake() except (_TLSDowngradeError): self.close() new_session = TLSSession( session._protocols - set(['TLSv1.2']), session._manual_validation, session._extra_trust_roots ) session.__del__() self._received_bytes = b'' self._session = new_session self._socket = socket_.create_connection((address, port), timeout) self._socket.settimeout(timeout) self._handshake() except (_TLSRetryError): self._received_bytes = b'' self._socket = socket_.create_connection((address, port), timeout) self._socket.settimeout(timeout) self._handshake() def _create_buffers(self, number): """ Creates a SecBufferDesc struct and contained SecBuffer structs :param number: The number of contains SecBuffer objects to create :return: A tuple of (SecBufferDesc pointer, SecBuffer array) """ buffers = new(secur32, 'SecBuffer[%d]' % number) for index in range(0, number): buffers[index].cbBuffer = 0 buffers[index].BufferType = Secur32Const.SECBUFFER_EMPTY buffers[index].pvBuffer = null() sec_buffer_desc_pointer = struct(secur32, 'SecBufferDesc') sec_buffer_desc = unwrap(sec_buffer_desc_pointer) sec_buffer_desc.ulVersion = Secur32Const.SECBUFFER_VERSION sec_buffer_desc.cBuffers = number sec_buffer_desc.pBuffers = buffers return (sec_buffer_desc_pointer, buffers) def _extra_trust_root_validation(self): """ Manually invoked windows certificate chain builder and verification step when there are extra trust roots to include in the search process """ store = None cert_chain_context_pointer = None try: # We set up an in-memory store to pass as an extra store to grab # certificates from when performing the verification store = crypt32.CertOpenStore( Crypt32Const.CERT_STORE_PROV_MEMORY, Crypt32Const.X509_ASN_ENCODING, null(), 0, null() ) if is_null(store): handle_crypt32_error(0) cert_hashes = set() for cert in self._session._extra_trust_roots: cert_data = cert.dump() result = crypt32.CertAddEncodedCertificateToStore( store, Crypt32Const.X509_ASN_ENCODING, cert_data, len(cert_data), Crypt32Const.CERT_STORE_ADD_USE_EXISTING, null() ) if not result: handle_crypt32_error(0) cert_hashes.add(cert.sha256) cert_context_pointer_pointer = new(crypt32, 'PCERT_CONTEXT *') result = secur32.QueryContextAttributesW( self._context_handle_pointer, Secur32Const.SECPKG_ATTR_REMOTE_CERT_CONTEXT, cert_context_pointer_pointer ) handle_error(result) cert_context_pointer = unwrap(cert_context_pointer_pointer) cert_context_pointer = cast(crypt32, 'PCERT_CONTEXT', cert_context_pointer) # We have to do a funky shuffle here because FILETIME from kernel32 # is different than FILETIME from crypt32 when using cffi. If we # overwrite the "now_pointer" variable, cffi releases the backing # memory and we end up getting a validation error about certificate # expiration time. orig_now_pointer = new(kernel32, 'FILETIME *') kernel32.GetSystemTimeAsFileTime(orig_now_pointer) now_pointer = cast(crypt32, 'FILETIME *', orig_now_pointer) usage_identifiers = new(crypt32, 'char *[3]') usage_identifiers[0] = cast(crypt32, 'char *', Crypt32Const.PKIX_KP_SERVER_AUTH) usage_identifiers[1] = cast(crypt32, 'char *', Crypt32Const.SERVER_GATED_CRYPTO) usage_identifiers[2] = cast(crypt32, 'char *', Crypt32Const.SGC_NETSCAPE) cert_enhkey_usage_pointer = struct(crypt32, 'CERT_ENHKEY_USAGE') cert_enhkey_usage = unwrap(cert_enhkey_usage_pointer) cert_enhkey_usage.cUsageIdentifier = 3 cert_enhkey_usage.rgpszUsageIdentifier = cast(crypt32, 'char **', usage_identifiers) cert_usage_match_pointer = struct(crypt32, 'CERT_USAGE_MATCH') cert_usage_match = unwrap(cert_usage_match_pointer) cert_usage_match.dwType = Crypt32Const.USAGE_MATCH_TYPE_OR cert_usage_match.Usage = cert_enhkey_usage cert_chain_para_pointer = struct(crypt32, 'CERT_CHAIN_PARA') cert_chain_para = unwrap(cert_chain_para_pointer) cert_chain_para.RequestedUsage = cert_usage_match cert_chain_para_size = sizeof(crypt32, cert_chain_para) cert_chain_para.cbSize = cert_chain_para_size cert_chain_context_pointer_pointer = new(crypt32, 'PCERT_CHAIN_CONTEXT *') result = crypt32.CertGetCertificateChain( null(), cert_context_pointer, now_pointer, store, cert_chain_para_pointer, Crypt32Const.CERT_CHAIN_CACHE_END_CERT | Crypt32Const.CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY, null(), cert_chain_context_pointer_pointer ) handle_crypt32_error(result) cert_chain_policy_para_flags = Crypt32Const.CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS cert_chain_context_pointer = unwrap(cert_chain_context_pointer_pointer) # Unwrap the chain and if the final element in the chain is one of # extra trust roots, set flags so that we trust the certificate even # though it is not in the Trusted Roots store cert_chain_context = unwrap(cert_chain_context_pointer) num_chains = native(int, cert_chain_context.cChain) if num_chains == 1: first_simple_chain_pointer = unwrap(cert_chain_context.rgpChain) first_simple_chain = unwrap(first_simple_chain_pointer) num_elements = native(int, first_simple_chain.cElement) last_element_pointer = first_simple_chain.rgpElement[num_elements - 1] last_element = unwrap(last_element_pointer) last_element_cert = unwrap(last_element.pCertContext) last_element_cert_data = bytes_from_buffer( last_element_cert.pbCertEncoded, native(int, last_element_cert.cbCertEncoded) ) last_cert = Asn1Certificate.load(last_element_cert_data) if last_cert.sha256 in cert_hashes: cert_chain_policy_para_flags |= Crypt32Const.CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG ssl_extra_cert_chain_policy_para_pointer = struct(crypt32, 'SSL_EXTRA_CERT_CHAIN_POLICY_PARA') ssl_extra_cert_chain_policy_para = unwrap(ssl_extra_cert_chain_policy_para_pointer) ssl_extra_cert_chain_policy_para.cbSize = sizeof(crypt32, ssl_extra_cert_chain_policy_para) ssl_extra_cert_chain_policy_para.dwAuthType = Crypt32Const.AUTHTYPE_SERVER ssl_extra_cert_chain_policy_para.fdwChecks = 0 ssl_extra_cert_chain_policy_para.pwszServerName = cast( crypt32, 'wchar_t *', buffer_from_unicode(self._hostname) ) cert_chain_policy_para_pointer = struct(crypt32, 'CERT_CHAIN_POLICY_PARA') cert_chain_policy_para = unwrap(cert_chain_policy_para_pointer) cert_chain_policy_para.cbSize = sizeof(crypt32, cert_chain_policy_para) cert_chain_policy_para.dwFlags = cert_chain_policy_para_flags cert_chain_policy_para.pvExtraPolicyPara = cast(crypt32, 'void *', ssl_extra_cert_chain_policy_para_pointer) cert_chain_policy_status_pointer = struct(crypt32, 'CERT_CHAIN_POLICY_STATUS') cert_chain_policy_status = unwrap(cert_chain_policy_status_pointer) cert_chain_policy_status.cbSize = sizeof(crypt32, cert_chain_policy_status) result = crypt32.CertVerifyCertificateChainPolicy( Crypt32Const.CERT_CHAIN_POLICY_SSL, cert_chain_context_pointer, cert_chain_policy_para_pointer, cert_chain_policy_status_pointer ) handle_crypt32_error(result) cert_context = unwrap(cert_context_pointer) cert_data = bytes_from_buffer(cert_context.pbCertEncoded, native(int, cert_context.cbCertEncoded)) cert = Asn1Certificate.load(cert_data) error = cert_chain_policy_status.dwError if error: if error == Crypt32Const.CERT_E_EXPIRED: raise_expired_not_yet_valid(cert) if error == Crypt32Const.CERT_E_UNTRUSTEDROOT: oscrypto_cert = load_certificate(cert) if oscrypto_cert.self_signed: raise_self_signed(cert) else: raise_no_issuer(cert) if error == Crypt32Const.CERT_E_CN_NO_MATCH: raise_hostname(cert, self._hostname) if error == Crypt32Const.TRUST_E_CERT_SIGNATURE: raise_weak_signature(cert) if error == Crypt32Const.CRYPT_E_REVOKED: raise_revoked(cert) raise_verification(cert) if cert.hash_algo in set(['md5', 'md2']): raise_weak_signature(cert) finally: if store: crypt32.CertCloseStore(store, 0) if cert_chain_context_pointer: crypt32.CertFreeCertificateChain(cert_chain_context_pointer) def _handshake(self, renegotiate=False): """ Perform an initial TLS handshake, or a renegotiation :param renegotiate: If the handshake is for a renegotiation """ in_buffers = None out_buffers = None new_context_handle_pointer = None try: if renegotiate: temp_context_handle_pointer = self._context_handle_pointer else: new_context_handle_pointer = new(secur32, 'CtxtHandle *') temp_context_handle_pointer = new_context_handle_pointer requested_flags = { Secur32Const.ISC_REQ_REPLAY_DETECT: 'replay detection', Secur32Const.ISC_REQ_SEQUENCE_DETECT: 'sequence detection', Secur32Const.ISC_REQ_CONFIDENTIALITY: 'confidentiality', Secur32Const.ISC_REQ_ALLOCATE_MEMORY: 'memory allocation', Secur32Const.ISC_REQ_INTEGRITY: 'integrity', Secur32Const.ISC_REQ_STREAM: 'stream orientation', Secur32Const.ISC_REQ_USE_SUPPLIED_CREDS: 'disable automatic client auth', } self._context_flags = 0 for flag in requested_flags: self._context_flags |= flag in_sec_buffer_desc_pointer, in_buffers = self._create_buffers(2) in_buffers[0].BufferType = Secur32Const.SECBUFFER_TOKEN out_sec_buffer_desc_pointer, out_buffers = self._create_buffers(2) out_buffers[0].BufferType = Secur32Const.SECBUFFER_TOKEN out_buffers[1].BufferType = Secur32Const.SECBUFFER_ALERT output_context_flags_pointer = new(secur32, 'ULONG *') if renegotiate: first_handle = temp_context_handle_pointer second_handle = null() else: first_handle = null() second_handle = temp_context_handle_pointer result = secur32.InitializeSecurityContextW( self._session._credentials_handle, first_handle, self._hostname, self._context_flags, 0, 0, null(), 0, second_handle, out_sec_buffer_desc_pointer, output_context_flags_pointer, null() ) if result not in set([Secur32Const.SEC_E_OK, Secur32Const.SEC_I_CONTINUE_NEEDED]): handle_error(result, TLSError) if not renegotiate: temp_context_handle_pointer = second_handle else: temp_context_handle_pointer = first_handle handshake_server_bytes = b'' handshake_client_bytes = b'' if out_buffers[0].cbBuffer > 0: token = bytes_from_buffer(out_buffers[0].pvBuffer, out_buffers[0].cbBuffer) handshake_client_bytes += token self._socket.send(token) out_buffers[0].cbBuffer = 0 secur32.FreeContextBuffer(out_buffers[0].pvBuffer) out_buffers[0].pvBuffer = null() in_data_buffer = buffer_from_bytes(32768) in_buffers[0].pvBuffer = cast(secur32, 'BYTE *', in_data_buffer) bytes_read = b'' while result != Secur32Const.SEC_E_OK: try: fail_late = False bytes_read = self._socket.recv(8192) if bytes_read == b'': raise_disconnection() except (socket_error_cls): fail_late = True handshake_server_bytes += bytes_read self._received_bytes += bytes_read in_buffers[0].cbBuffer = len(self._received_bytes) write_to_buffer(in_data_buffer, self._received_bytes) result = secur32.InitializeSecurityContextW( self._session._credentials_handle, temp_context_handle_pointer, self._hostname, self._context_flags, 0, 0, in_sec_buffer_desc_pointer, 0, null(), out_sec_buffer_desc_pointer, output_context_flags_pointer, null() ) if result == Secur32Const.SEC_E_INCOMPLETE_MESSAGE: in_buffers[0].BufferType = Secur32Const.SECBUFFER_TOKEN # Windows 10 seems to fill the second input buffer with # a BufferType of SECBUFFER_MISSING (4), which if not # cleared causes the handshake to fail. if in_buffers[1].BufferType != Secur32Const.SECBUFFER_EMPTY: in_buffers[1].BufferType = Secur32Const.SECBUFFER_EMPTY in_buffers[1].cbBuffer = 0 if not is_null(in_buffers[1].pvBuffer): secur32.FreeContextBuffer(in_buffers[1].pvBuffer) in_buffers[1].pvBuffer = null() if fail_late: raise_disconnection() continue if result == Secur32Const.SEC_E_ILLEGAL_MESSAGE: if detect_client_auth_request(handshake_server_bytes): raise_client_auth() alert_info = parse_alert(handshake_server_bytes) if alert_info and alert_info == (2, 70): raise_protocol_version() raise_handshake() if result == Secur32Const.SEC_E_WRONG_PRINCIPAL: chain = extract_chain(handshake_server_bytes) raise_hostname(chain[0], self._hostname) if result == Secur32Const.SEC_E_CERT_EXPIRED: chain = extract_chain(handshake_server_bytes) raise_expired_not_yet_valid(chain[0]) if result == Secur32Const.SEC_E_UNTRUSTED_ROOT: chain = extract_chain(handshake_server_bytes) cert = chain[0] oscrypto_cert = load_certificate(cert) if not oscrypto_cert.self_signed: raise_no_issuer(cert) raise_self_signed(cert) if result == Secur32Const.SEC_E_INTERNAL_ERROR: if get_dh_params_length(handshake_server_bytes) < 1024: raise_dh_params() if result == Secur32Const.SEC_I_INCOMPLETE_CREDENTIALS: raise_client_auth() if result == Crypt32Const.TRUST_E_CERT_SIGNATURE: raise_weak_signature(cert) if result == Secur32Const.SEC_E_INVALID_TOKEN: # If an alert it present, there may have been a handshake # error due to the server using a certificate path with a # trust root using MD2 or MD5 combined with TLS 1.2. To # work around this, if the user allows anything other than # TLS 1.2, we just remove it from the acceptable protocols # and try again. if out_buffers[1].cbBuffer > 0: alert_bytes = bytes_from_buffer(out_buffers[1].pvBuffer, out_buffers[1].cbBuffer) handshake_client_bytes += alert_bytes alert_number = alert_bytes[6:7] if alert_number == b'\x28' or alert_number == b'\x2b': if 'TLSv1.2' in self._session._protocols and len(self._session._protocols) > 1: chain = extract_chain(handshake_server_bytes) raise _TLSDowngradeError( 'Server certificate verification failed - weak certificate signature algorithm', chain[0] ) if detect_client_auth_request(handshake_server_bytes): raise_client_auth() if detect_other_protocol(handshake_server_bytes): raise_protocol_error(handshake_server_bytes) raise_handshake() # These are semi-common errors with TLSv1.2 on Windows 7 an 8 # that appears to be due to poor handling of the # ServerKeyExchange for DHE_RSA cipher suites. The solution # is to retry the handshake. if result == Secur32Const.SEC_E_BUFFER_TOO_SMALL or result == Secur32Const.SEC_E_MESSAGE_ALTERED: if 'TLSv1.2' in self._session._protocols: raise _TLSRetryError('TLS handshake failed') if fail_late: raise_disconnection() if result == Secur32Const.SEC_E_INVALID_PARAMETER: if get_dh_params_length(handshake_server_bytes) < 1024: raise_dh_params() if result not in set([Secur32Const.SEC_E_OK, Secur32Const.SEC_I_CONTINUE_NEEDED]): handle_error(result, TLSError) if out_buffers[0].cbBuffer > 0: token = bytes_from_buffer(out_buffers[0].pvBuffer, out_buffers[0].cbBuffer) handshake_client_bytes += token self._socket.send(token) out_buffers[0].cbBuffer = 0 secur32.FreeContextBuffer(out_buffers[0].pvBuffer) out_buffers[0].pvBuffer = null() if in_buffers[1].BufferType == Secur32Const.SECBUFFER_EXTRA: extra_amount = in_buffers[1].cbBuffer self._received_bytes = self._received_bytes[-extra_amount:] in_buffers[1].BufferType = Secur32Const.SECBUFFER_EMPTY in_buffers[1].cbBuffer = 0 secur32.FreeContextBuffer(in_buffers[1].pvBuffer) in_buffers[1].pvBuffer = null() # The handshake is complete, so discard any extra bytes if result == Secur32Const.SEC_E_OK: handshake_server_bytes = handshake_server_bytes[-extra_amount:] else: self._received_bytes = b'' connection_info_pointer = struct(secur32, 'SecPkgContext_ConnectionInfo') result = secur32.QueryContextAttributesW( temp_context_handle_pointer, Secur32Const.SECPKG_ATTR_CONNECTION_INFO, connection_info_pointer ) handle_error(result, TLSError) connection_info = unwrap(connection_info_pointer) self._protocol = { Secur32Const.SP_PROT_SSL2_CLIENT: 'SSLv2', Secur32Const.SP_PROT_SSL3_CLIENT: 'SSLv3', Secur32Const.SP_PROT_TLS1_CLIENT: 'TLSv1', Secur32Const.SP_PROT_TLS1_1_CLIENT: 'TLSv1.1', Secur32Const.SP_PROT_TLS1_2_CLIENT: 'TLSv1.2', }.get(native(int, connection_info.dwProtocol), str_cls(connection_info.dwProtocol)) if self._protocol in set(['SSLv3', 'TLSv1', 'TLSv1.1', 'TLSv1.2']): session_info = parse_session_info(handshake_server_bytes, handshake_client_bytes) self._cipher_suite = session_info['cipher_suite'] self._compression = session_info['compression'] self._session_id = session_info['session_id'] self._session_ticket = session_info['session_ticket'] output_context_flags = deref(output_context_flags_pointer) for flag in requested_flags: if (flag | output_context_flags) == 0: raise OSError(pretty_message( ''' Unable to obtain a credential context with the property %s ''', requested_flags[flag] )) if not renegotiate: self._context_handle_pointer = temp_context_handle_pointer new_context_handle_pointer = None stream_sizes_pointer = struct(secur32, 'SecPkgContext_StreamSizes') result = secur32.QueryContextAttributesW( self._context_handle_pointer, Secur32Const.SECPKG_ATTR_STREAM_SIZES, stream_sizes_pointer ) handle_error(result) stream_sizes = unwrap(stream_sizes_pointer) self._header_size = native(int, stream_sizes.cbHeader) self._message_size = native(int, stream_sizes.cbMaximumMessage) self._trailer_size = native(int, stream_sizes.cbTrailer) self._buffer_size = self._header_size + self._message_size + self._trailer_size if self._session._extra_trust_roots: self._extra_trust_root_validation() except (OSError, socket_.error): self.close() raise finally: if out_buffers: if not is_null(out_buffers[0].pvBuffer): secur32.FreeContextBuffer(out_buffers[0].pvBuffer) if not is_null(out_buffers[1].pvBuffer): secur32.FreeContextBuffer(out_buffers[1].pvBuffer) if new_context_handle_pointer: secur32.DeleteSecurityContext(new_context_handle_pointer) def read(self, max_length): """ Reads data from the TLS-wrapped socket :param max_length: The number of bytes to read :raises: socket.socket - when a non-TLS socket error occurs oscrypto.errors.TLSError - when a TLS-related error occurs ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the data read """ if not isinstance(max_length, int_types): raise TypeError(pretty_message( ''' max_length must be an integer, not %s ''', type_name(max_length) )) if self._context_handle_pointer is None: # Allow the user to read any remaining decrypted data if self._decrypted_bytes != b'': output = self._decrypted_bytes[0:max_length] self._decrypted_bytes = self._decrypted_bytes[max_length:] return output self._raise_closed() # The first time read is called, set up a single contiguous buffer that # it used by DecryptMessage() to populate the three output buffers. # Since we are creating the buffer, we do not need to free it other # than allowing Python to GC it once this object is GCed. if not self._decrypt_data_buffer: self._decrypt_data_buffer = buffer_from_bytes(self._buffer_size) self._decrypt_desc, self._decrypt_buffers = self._create_buffers(4) self._decrypt_buffers[0].BufferType = Secur32Const.SECBUFFER_DATA self._decrypt_buffers[0].pvBuffer = cast(secur32, 'BYTE *', self._decrypt_data_buffer) to_recv = max(max_length, self._buffer_size) # These variables are set to reduce dict access and function calls # in the read loop. Also makes the code easier to read. null_value = null() buf0 = self._decrypt_buffers[0] buf1 = self._decrypt_buffers[1] buf2 = self._decrypt_buffers[2] buf3 = self._decrypt_buffers[3] def _reset_buffers(): buf0.BufferType = Secur32Const.SECBUFFER_DATA buf0.pvBuffer = cast(secur32, 'BYTE *', self._decrypt_data_buffer) buf0.cbBuffer = 0 buf1.BufferType = Secur32Const.SECBUFFER_EMPTY buf1.pvBuffer = null_value buf1.cbBuffer = 0 buf2.BufferType = Secur32Const.SECBUFFER_EMPTY buf2.pvBuffer = null_value buf2.cbBuffer = 0 buf3.BufferType = Secur32Const.SECBUFFER_EMPTY buf3.pvBuffer = null_value buf3.cbBuffer = 0 output = self._decrypted_bytes output_len = len(output) self._decrypted_bytes = b'' # Don't block if we have buffered data available if output_len > 0 and not self.select_read(0): self._decrypted_bytes = b'' return output # This read loop will only be run if there wasn't enough # buffered data to fulfill the requested max_length do_read = len(self._received_bytes) == 0 while output_len < max_length: if do_read: self._received_bytes += self._socket.recv(to_recv) if len(self._received_bytes) == 0: raise_disconnection() data_len = min(len(self._received_bytes), self._buffer_size) if data_len == 0: break self._decrypt_buffers[0].cbBuffer = data_len write_to_buffer(self._decrypt_data_buffer, self._received_bytes[0:data_len]) result = secur32.DecryptMessage( self._context_handle_pointer, self._decrypt_desc, 0, null() ) do_read = False if result == Secur32Const.SEC_E_INCOMPLETE_MESSAGE: _reset_buffers() do_read = True continue elif result == Secur32Const.SEC_I_CONTEXT_EXPIRED: self._remote_closed = True self.shutdown() break elif result == Secur32Const.SEC_I_RENEGOTIATE: self._handshake(renegotiate=True) return self.read(max_length) elif result != Secur32Const.SEC_E_OK: handle_error(result, TLSError) valid_buffer_types = set([ Secur32Const.SECBUFFER_EMPTY, Secur32Const.SECBUFFER_STREAM_HEADER, Secur32Const.SECBUFFER_STREAM_TRAILER ]) extra_amount = None for buf in (buf0, buf1, buf2, buf3): buffer_type = buf.BufferType if buffer_type == Secur32Const.SECBUFFER_DATA: output += bytes_from_buffer(buf.pvBuffer, buf.cbBuffer) output_len = len(output) elif buffer_type == Secur32Const.SECBUFFER_EXTRA: extra_amount = native(int, buf.cbBuffer) elif buffer_type not in valid_buffer_types: raise OSError(pretty_message( ''' Unexpected decrypt output buffer of type %s ''', buffer_type )) if extra_amount: self._received_bytes = self._received_bytes[data_len - extra_amount:] else: self._received_bytes = self._received_bytes[data_len:] # Here we reset the structs for the next call to DecryptMessage() _reset_buffers() # If we have read something, but there is nothing left to read, we # break so that we don't block for longer than necessary if self.select_read(0): do_read = True if not do_read and len(self._received_bytes) == 0: break # If the output is more than we requested (because data is decrypted in # blocks), we save the extra in a buffer if len(output) > max_length: self._decrypted_bytes = output[max_length:] output = output[0:max_length] return output def select_read(self, timeout=None): """ Blocks until the socket is ready to be read from, or the timeout is hit :param timeout: A float - the period of time to wait for data to be read. None for no time limit. :return: A boolean - if data is ready to be read. Will only be False if timeout is not None. """ # If we have buffered data, we consider a read possible if len(self._decrypted_bytes) > 0: return True read_ready, _, _ = select.select([self._socket], [], [], timeout) return len(read_ready) > 0 def read_until(self, marker): """ Reads data from the socket until a marker is found. Data read may include data beyond the marker. :param marker: A byte string or regex object from re.compile(). Used to determine when to stop reading. Regex objects are more inefficient since they must scan the entire byte string of read data each time data is read off the socket. :return: A byte string of the data read """ if not isinstance(marker, byte_cls) and not isinstance(marker, Pattern): raise TypeError(pretty_message( ''' marker must be a byte string or compiled regex object, not %s ''', type_name(marker) )) output = b'' is_regex = isinstance(marker, Pattern) while True: if len(self._decrypted_bytes) > 0: chunk = self._decrypted_bytes self._decrypted_bytes = b'' else: chunk = self.read(8192) offset = len(output) output += chunk if is_regex: match = marker.search(output) if match is not None: end = match.end() break else: # If the marker was not found last time, we have to start # at a position where the marker would have its final char # in the newly read chunk start = max(0, offset - len(marker) - 1) match = output.find(marker, start) if match != -1: end = match + len(marker) break self._decrypted_bytes = output[end:] + self._decrypted_bytes return output[0:end] def read_line(self): r""" Reads a line from the socket, including the line ending of "\r\n", "\r", or "\n" :return: A byte string of the next line from the socket """ return self.read_until(_line_regex) def read_exactly(self, num_bytes): """ Reads exactly the specified number of bytes from the socket :param num_bytes: An integer - the exact number of bytes to read :return: A byte string of the data that was read """ output = b'' remaining = num_bytes while remaining > 0: output += self.read(remaining) remaining = num_bytes - len(output) return output def write(self, data): """ Writes data to the TLS-wrapped socket :param data: A byte string to write to the socket :raises: socket.socket - when a non-TLS socket error occurs oscrypto.errors.TLSError - when a TLS-related error occurs ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library """ if self._context_handle_pointer is None: self._raise_closed() if not self._encrypt_data_buffer: self._encrypt_data_buffer = buffer_from_bytes(self._header_size + self._message_size + self._trailer_size) self._encrypt_desc, self._encrypt_buffers = self._create_buffers(4) self._encrypt_buffers[0].BufferType = Secur32Const.SECBUFFER_STREAM_HEADER self._encrypt_buffers[0].cbBuffer = self._header_size self._encrypt_buffers[0].pvBuffer = cast(secur32, 'BYTE *', self._encrypt_data_buffer) self._encrypt_buffers[1].BufferType = Secur32Const.SECBUFFER_DATA self._encrypt_buffers[1].pvBuffer = ref(self._encrypt_data_buffer, self._header_size) self._encrypt_buffers[2].BufferType = Secur32Const.SECBUFFER_STREAM_TRAILER self._encrypt_buffers[2].cbBuffer = self._trailer_size self._encrypt_buffers[2].pvBuffer = ref(self._encrypt_data_buffer, self._header_size + self._message_size) while len(data) > 0: to_write = min(len(data), self._message_size) write_to_buffer(self._encrypt_data_buffer, data[0:to_write], self._header_size) self._encrypt_buffers[1].cbBuffer = to_write self._encrypt_buffers[2].pvBuffer = ref(self._encrypt_data_buffer, self._header_size + to_write) result = secur32.EncryptMessage( self._context_handle_pointer, 0, self._encrypt_desc, 0 ) if result != Secur32Const.SEC_E_OK: handle_error(result, TLSError) to_send = native(int, self._encrypt_buffers[0].cbBuffer) to_send += native(int, self._encrypt_buffers[1].cbBuffer) to_send += native(int, self._encrypt_buffers[2].cbBuffer) try: self._socket.send(bytes_from_buffer(self._encrypt_data_buffer, to_send)) except (socket_.error) as e: if e.errno == 10053: raise_disconnection() raise data = data[to_send:] def select_write(self, timeout=None): """ Blocks until the socket is ready to be written to, or the timeout is hit :param timeout: A float - the period of time to wait for the socket to be ready to written to. None for no time limit. :return: A boolean - if the socket is ready for writing. Will only be False if timeout is not None. """ _, write_ready, _ = select.select([], [self._socket], [], timeout) return len(write_ready) > 0 def shutdown(self): """ Shuts down the TLS session and then shuts down the underlying socket :raises: OSError - when an error is returned by the OS crypto library """ if self._context_handle_pointer is None: return out_buffers = None try: # ApplyControlToken fails with SEC_E_UNSUPPORTED_FUNCTION # when called on Windows 7 if _win_version_info >= (6, 2): buffers = new(secur32, 'SecBuffer[1]') # This is a SCHANNEL_SHUTDOWN token (DWORD of 1) buffers[0].cbBuffer = 4 buffers[0].BufferType = Secur32Const.SECBUFFER_TOKEN buffers[0].pvBuffer = cast(secur32, 'BYTE *', buffer_from_bytes(b'\x01\x00\x00\x00')) sec_buffer_desc_pointer = struct(secur32, 'SecBufferDesc') sec_buffer_desc = unwrap(sec_buffer_desc_pointer) sec_buffer_desc.ulVersion = Secur32Const.SECBUFFER_VERSION sec_buffer_desc.cBuffers = 1 sec_buffer_desc.pBuffers = buffers result = secur32.ApplyControlToken(self._context_handle_pointer, sec_buffer_desc_pointer) handle_error(result, TLSError) out_sec_buffer_desc_pointer, out_buffers = self._create_buffers(2) out_buffers[0].BufferType = Secur32Const.SECBUFFER_TOKEN out_buffers[1].BufferType = Secur32Const.SECBUFFER_ALERT output_context_flags_pointer = new(secur32, 'ULONG *') result = secur32.InitializeSecurityContextW( self._session._credentials_handle, self._context_handle_pointer, self._hostname, self._context_flags, 0, 0, null(), 0, null(), out_sec_buffer_desc_pointer, output_context_flags_pointer, null() ) acceptable_results = set([ Secur32Const.SEC_E_OK, Secur32Const.SEC_E_CONTEXT_EXPIRED, Secur32Const.SEC_I_CONTINUE_NEEDED ]) if result not in acceptable_results: handle_error(result, TLSError) token = bytes_from_buffer(out_buffers[0].pvBuffer, out_buffers[0].cbBuffer) try: # If there is an error sending the shutdown, ignore it since the # connection is likely gone at this point self._socket.send(token) except (socket_.error): pass finally: if out_buffers: if not is_null(out_buffers[0].pvBuffer): secur32.FreeContextBuffer(out_buffers[0].pvBuffer) if not is_null(out_buffers[1].pvBuffer): secur32.FreeContextBuffer(out_buffers[1].pvBuffer) secur32.DeleteSecurityContext(self._context_handle_pointer) self._context_handle_pointer = None try: self._socket.shutdown(socket_.SHUT_RDWR) except (socket_.error): pass def close(self): """ Shuts down the TLS session and socket and forcibly closes it """ try: self.shutdown() finally: if self._socket: try: self._socket.close() except (socket_.error): pass self._socket = None def _read_certificates(self): """ Reads end-entity and intermediate certificate information from the TLS session """ cert_context_pointer_pointer = new(crypt32, 'CERT_CONTEXT **') result = secur32.QueryContextAttributesW( self._context_handle_pointer, Secur32Const.SECPKG_ATTR_REMOTE_CERT_CONTEXT, cert_context_pointer_pointer ) handle_error(result, TLSError) cert_context_pointer = unwrap(cert_context_pointer_pointer) cert_context_pointer = cast(crypt32, 'CERT_CONTEXT *', cert_context_pointer) cert_context = unwrap(cert_context_pointer) cert_data = bytes_from_buffer(cert_context.pbCertEncoded, native(int, cert_context.cbCertEncoded)) self._certificate = Asn1Certificate.load(cert_data) self._intermediates = [] store_handle = None try: store_handle = cert_context.hCertStore context_pointer = crypt32.CertEnumCertificatesInStore(store_handle, null()) while not is_null(context_pointer): context = unwrap(context_pointer) data = bytes_from_buffer(context.pbCertEncoded, native(int, context.cbCertEncoded)) # The cert store seems to include the end-entity certificate as # the last entry, but we already have that from the struct. if data != cert_data: self._intermediates.append(Asn1Certificate.load(data)) context_pointer = crypt32.CertEnumCertificatesInStore(store_handle, context_pointer) finally: if store_handle: crypt32.CertCloseStore(store_handle, 0) def _raise_closed(self): """ Raises an exception describing if the local or remote end closed the connection """ if self._remote_closed: raise TLSGracefulDisconnectError('The remote end closed the connection') else: raise TLSDisconnectError('The connection was already closed') @property def certificate(self): """ An asn1crypto.x509.Certificate object of the end-entity certificate presented by the server """ if self._context_handle_pointer is None: self._raise_closed() if self._certificate is None: self._read_certificates() return self._certificate @property def intermediates(self): """ A list of asn1crypto.x509.Certificate objects that were presented as intermediates by the server """ if self._context_handle_pointer is None: self._raise_closed() if self._certificate is None: self._read_certificates() return self._intermediates @property def cipher_suite(self): """ A unicode string of the IANA cipher suite name of the negotiated cipher suite """ return self._cipher_suite @property def protocol(self): """ A unicode string of: "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3" """ return self._protocol @property def compression(self): """ A boolean if compression is enabled """ return self._compression @property def session_id(self): """ A unicode string of "new" or "reused" or None for no ticket """ return self._session_id @property def session_ticket(self): """ A unicode string of "new" or "reused" or None for no ticket """ return self._session_ticket @property def session(self): """ The oscrypto.tls.TLSSession object used for this connection """ return self._session @property def hostname(self): """ A unicode string of the TLS server domain name or IP address """ return self._hostname @property def port(self): """ An integer of the port number the socket is connected to """ return self.socket.getpeername()[1] @property def socket(self): """ The underlying socket.socket connection """ if self._context_handle_pointer is None: self._raise_closed() return self._socket def __del__(self): self.close() PK!U trust_list.pynu[# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import datetime import hashlib import struct from .._asn1 import Certificate from .._ffi import ( array_from_pointer, buffer_from_bytes, bytes_from_buffer, cast, deref, is_null, new, null, struct_from_buffer, unwrap, ) from ._crypt32 import crypt32, Crypt32Const, get_error, handle_error from .._types import str_cls __all__ = [ 'extract_from_system', 'system_path', ] def system_path(): return None def extract_from_system(cert_callback=None, callback_only_on_failure=False): """ Extracts trusted CA certificates from the Windows certificate store :param cert_callback: A callback that is called once for each certificate in the trust store. It should accept two parameters: an asn1crypto.x509.Certificate object, and a reason. The reason will be None if the certificate is being exported, otherwise it will be a unicode string of the reason it won't. :param callback_only_on_failure: A boolean - if the callback should only be called when a certificate is not exported. :raises: OSError - when an error is returned by the OS crypto library :return: A list of 3-element tuples: - 0: a byte string of a DER-encoded certificate - 1: a set of unicode strings that are OIDs of purposes to trust the certificate for - 2: a set of unicode strings that are OIDs of purposes to reject the certificate for """ certificates = {} processed = {} now = datetime.datetime.utcnow() for store in ["ROOT", "CA"]: store_handle = crypt32.CertOpenSystemStoreW(null(), store) handle_error(store_handle) context_pointer = null() while True: context_pointer = crypt32.CertEnumCertificatesInStore(store_handle, context_pointer) if is_null(context_pointer): break context = unwrap(context_pointer) trust_all = False data = None digest = None if context.dwCertEncodingType != Crypt32Const.X509_ASN_ENCODING: continue data = bytes_from_buffer(context.pbCertEncoded, int(context.cbCertEncoded)) digest = hashlib.sha1(data).digest() if digest in processed: continue processed[digest] = True cert_info = unwrap(context.pCertInfo) not_before_seconds = _convert_filetime_to_timestamp(cert_info.NotBefore) try: not_before = datetime.datetime.fromtimestamp(not_before_seconds) if not_before > now: if cert_callback: cert_callback(Certificate.load(data), 'not yet valid') continue except (ValueError, OSError): # If there is an error converting the not before timestamp, # it is almost certainly because it is from too long ago, # which means the cert is definitely valid by now. pass not_after_seconds = _convert_filetime_to_timestamp(cert_info.NotAfter) try: not_after = datetime.datetime.fromtimestamp(not_after_seconds) if not_after < now: if cert_callback: cert_callback(Certificate.load(data), 'no longer valid') continue except (ValueError, OSError) as e: # The only reason we would get an exception here is if the # expiration time is so far in the future that it can't be # used as a timestamp, or it is before 0. If it is very far # in the future, the cert is still valid, so we only raise # an exception if the timestamp is less than zero. if not_after_seconds < 0: message = e.args[0] + ' - ' + str_cls(not_after_seconds) e.args = (message,) + e.args[1:] raise e trust_oids = set() reject_oids = set() # Here we grab the extended key usage properties that Windows # layers on top of the extended key usage extension that is # part of the certificate itself. For highest security, users # should only use certificates for the intersection of the two # lists of purposes. However, many seen to treat the OS trust # list as an override. to_read = new(crypt32, 'DWORD *', 0) res = crypt32.CertGetEnhancedKeyUsage( context_pointer, Crypt32Const.CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, null(), to_read ) # Per the Microsoft documentation, if CRYPT_E_NOT_FOUND is returned # from get_error(), it means the certificate is valid for all purposes error_code, _ = get_error() if not res and error_code != Crypt32Const.CRYPT_E_NOT_FOUND: handle_error(res) if error_code == Crypt32Const.CRYPT_E_NOT_FOUND: trust_all = True else: usage_buffer = buffer_from_bytes(deref(to_read)) res = crypt32.CertGetEnhancedKeyUsage( context_pointer, Crypt32Const.CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, cast(crypt32, 'CERT_ENHKEY_USAGE *', usage_buffer), to_read ) handle_error(res) key_usage_pointer = struct_from_buffer(crypt32, 'CERT_ENHKEY_USAGE', usage_buffer) key_usage = unwrap(key_usage_pointer) # Having no enhanced usage properties means a cert is distrusted if key_usage.cUsageIdentifier == 0: if cert_callback: cert_callback(Certificate.load(data), 'explicitly distrusted') continue oids = array_from_pointer( crypt32, 'LPCSTR', key_usage.rgpszUsageIdentifier, key_usage.cUsageIdentifier ) for oid in oids: trust_oids.add(oid.decode('ascii')) cert = None # If the certificate is not under blanket trust, we have to # determine what purposes it is rejected for by diffing the # set of OIDs from the certificate with the OIDs that are # trusted. if not trust_all: cert = Certificate.load(data) if cert.extended_key_usage_value: for cert_oid in cert.extended_key_usage_value: oid = cert_oid.dotted if oid not in trust_oids: reject_oids.add(oid) if cert_callback and not callback_only_on_failure: if cert is None: cert = Certificate.load(data) cert_callback(cert, None) certificates[digest] = (data, trust_oids, reject_oids) result = crypt32.CertCloseStore(store_handle, 0) handle_error(result) store_handle = None return certificates.values() def _convert_filetime_to_timestamp(filetime): """ Windows returns times as 64-bit unsigned longs that are the number of hundreds of nanoseconds since Jan 1 1601. This converts it to a datetime object. :param filetime: A FILETIME struct object :return: An integer unix timestamp """ hundreds_nano_seconds = struct.unpack( b'>Q', struct.pack( b'>LL', filetime.dwHighDateTime, filetime.dwLowDateTime ) )[0] seconds_since_1601 = hundreds_nano_seconds / 10000000 return seconds_since_1601 - 11644473600 # Seconds from Jan 1 1601 to Jan 1 1970 PK!Lrrutil.pynu[# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function from .. import backend from .._errors import pretty_message from .._ffi import buffer_from_bytes, bytes_from_buffer from .._pkcs12 import pkcs12_kdf from .._types import type_name, byte_cls, int_types __all__ = [ 'pbkdf2', 'pkcs12_kdf', 'rand_bytes', ] _backend = backend() if _backend == 'win': from ._cng import bcrypt, BcryptConst, handle_error, open_alg_handle, close_alg_handle def pbkdf2(hash_algorithm, password, salt, iterations, key_length): """ PBKDF2 from PKCS#5 :param hash_algorithm: The string name of the hash algorithm to use: "sha1", "sha256", "sha384", "sha512" :param password: A byte string of the password to use an input to the KDF :param salt: A cryptographic random byte string :param iterations: The numbers of iterations to use when deriving the key :param key_length: The length of the desired key in bytes :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: The derived key as a byte string """ if not isinstance(password, byte_cls): raise TypeError(pretty_message( ''' password must be a byte string, not %s ''', type_name(password) )) if not isinstance(salt, byte_cls): raise TypeError(pretty_message( ''' salt must be a byte string, not %s ''', type_name(salt) )) if not isinstance(iterations, int_types): raise TypeError(pretty_message( ''' iterations must be an integer, not %s ''', type_name(iterations) )) if iterations < 1: raise ValueError('iterations must be greater than 0') if not isinstance(key_length, int_types): raise TypeError(pretty_message( ''' key_length must be an integer, not %s ''', type_name(key_length) )) if key_length < 1: raise ValueError('key_length must be greater than 0') if hash_algorithm not in set(['sha1', 'sha256', 'sha384', 'sha512']): raise ValueError(pretty_message( ''' hash_algorithm must be one of "sha1", "sha256", "sha384", "sha512", not %s ''', repr(hash_algorithm) )) alg_constant = { 'sha1': BcryptConst.BCRYPT_SHA1_ALGORITHM, 'sha256': BcryptConst.BCRYPT_SHA256_ALGORITHM, 'sha384': BcryptConst.BCRYPT_SHA384_ALGORITHM, 'sha512': BcryptConst.BCRYPT_SHA512_ALGORITHM }[hash_algorithm] alg_handle = None try: alg_handle = open_alg_handle(alg_constant, BcryptConst.BCRYPT_ALG_HANDLE_HMAC_FLAG) output_buffer = buffer_from_bytes(key_length) res = bcrypt.BCryptDeriveKeyPBKDF2( alg_handle, password, len(password), salt, len(salt), iterations, output_buffer, key_length, 0 ) handle_error(res) return bytes_from_buffer(output_buffer) finally: if alg_handle: close_alg_handle(alg_handle) pbkdf2.pure_python = False def rand_bytes(length): """ Returns a number of random bytes suitable for cryptographic purposes :param length: The desired number of bytes :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string """ if not isinstance(length, int_types): raise TypeError(pretty_message( ''' length must be an integer, not %s ''', type_name(length) )) if length < 1: raise ValueError('length must be greater than 0') if length > 1024: raise ValueError('length must not be greater than 1024') alg_handle = None try: alg_handle = open_alg_handle(BcryptConst.BCRYPT_RNG_ALGORITHM) buffer = buffer_from_bytes(length) res = bcrypt.BCryptGenRandom(alg_handle, buffer, length, 0) handle_error(res) return bytes_from_buffer(buffer) finally: if alg_handle: close_alg_handle(alg_handle) # winlegacy backend else: from .._pkcs5 import pbkdf2 from .._rand import rand_bytes PK!o9T#__pycache__/__init__.cpython-38.pycnu[U af@sdS)NrrrG/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/__init__.pyPK!ǁ $__pycache__/_advapi32.cpython-38.pycnu[U af@sddlmZmZmZmZddlZddlmZddlm Z ddl m Z ddl m Z mZmZdd lmZed krdd lmZmZndd lmZmZd d dgZeZededfZdddZddZddZGdd d Zedkrde_dS))unicode_literalsdivisionabsolute_importprint_functionN)ffi) _try_decode)SignatureError)newunwrapnull)str_clsZcffi)advapi32 get_errorr Advapi32Const handle_errorTcCs|tjkrtj}n|tjkr$tj}n td||s>|tjkrLt}tj}n tj}tj }t t d}t |||||}|st dtjkrt ||||d}t|t|S)NzInvalid provider specified: %sz HCRYPTPROV *r)rMS_ENH_RSA_AES_PROV PROV_RSA_AESMS_ENH_DSS_DH_PROV PROV_DSS_DH ValueErrorr CRYPT_VERIFYCONTEXTCONTAINER_NAMECRYPT_NEWKEYSETr rZCryptAcquireContextWr NTE_EXISTSrr )providerZ verify_onlyZ provider_typeZcontainer_nameflagsZcontext_handle_pointerresrH/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/_advapi32.pyopen_context_handles8    r!cCst|d}t|dS)Nr)rZCryptReleaseContextr)handlerrrr close_context_handleDs r#cCsB|rdSt\}}|tjkr$tdt|ts6t|}t|dS)z Extracts the last Windows error message into a python unicode string :param result: A function result, 0 or None indicates failure :return: A unicode string error message NzSignature is invalid)rrNTE_BAD_SIGNATUREr isinstancerr OSError)resultcodeZ error_stringrrr rIs    c@seZdZdZdZdZdZdZdZdZ dZ d Z d Z dZ d Zd Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZd Zd Z dZ!dZ"dZ#dZ$d Z%dZ&d Z'd!Z(d"Z)d#Z*d$Z+dZ,d%Z-d&Z.d'Z/d(Z0d)S)*rzoscrypto temporary DSS keyset ,(z@Microsoft Enhanced DSS and Diffie-Hellman Cryptographic Providerz5Microsoft Enhanced RSA and AES Cryptographic Providerrl`iii i iifihifi fififififi"i$ir@i i iRSA1iRSA2iDSS1iDSS2N)1__name__ __module__ __qualname__rrrZX509_PUBLIC_KEY_INFOZPKCS_PRIVATE_KEY_INFOZX509_DSS_SIGNATUREZ CRYPT_NO_SALTrrZCRYPT_EXPORTABLErrZCALG_MD5Z CALG_SHA1Z CALG_SHA_256Z CALG_SHA_384Z CALG_SHA_512ZCALG_RC2ZCALG_RC4ZCALG_DESZ CALG_3DES_112Z CALG_3DESZ CALG_AES_128Z CALG_AES_192Z CALG_AES_256Z CALG_DSS_SIGNZ CALG_RSA_SIGNZ CALG_RSA_KEYXZCRYPT_MODE_CBCZ PKCS5_PADDINGZCUR_BLOB_VERSIONZ PUBLICKEYBLOBZPRIVATEKEYBLOBZPLAINTEXTKEYBLOBZKP_IVZ KP_PADDINGZKP_MODEZKP_EFFECTIVE_KEYLENZ CRYPT_OAEPr$rZ AT_SIGNATUREZRSA1ZRSA2ZDSS1ZDSS2rrrr rbs\)rzAMicrosoft Enhanced RSA and AES Cryptographic Provider (Prototype))T) __future__rrrrsysr_decoder errorsr Z_ffir r r _typesrZ_advapi32_cffirrZ_advapi32_ctypes__all__getwindowsversionZ_gwvZ_win_version_infor!r#rrrrrrr s*      'APK!B#)__pycache__/_advapi32_cffi.cpython-38.pycnu[U af @sddlmZmZmZmZddlmZddlmZddl m Z ddl Z ddgZ e Ze jd krhed ed zed ZeeeWn>ek rZz eed dkre dW5dZ[XYnXddZdS))unicode_literalsdivisionabsolute_importprint_function) register_ffi)str_cls)LibraryNotFoundErrorNadvapi32 get_error)r Tao typedef HANDLE HCRYPTPROV; typedef HANDLE HCRYPTKEY; typedef HANDLE HCRYPTHASH; typedef unsigned int ALG_ID; typedef struct _CRYPTOAPI_BLOB { DWORD cbData; BYTE *pbData; } CRYPT_INTEGER_BLOB, CRYPT_OBJID_BLOB, CRYPT_DER_BLOB, CRYPT_ATTR_BLOB; typedef struct _CRYPT_ALGORITHM_IDENTIFIER { LPSTR pszObjId; CRYPT_OBJID_BLOB Parameters; } CRYPT_ALGORITHM_IDENTIFIER; typedef struct _CRYPT_BIT_BLOB { DWORD cbData; BYTE *pbData; DWORD cUnusedBits; } CRYPT_BIT_BLOB; typedef struct _CERT_PUBLIC_KEY_INFO { CRYPT_ALGORITHM_IDENTIFIER Algorithm; CRYPT_BIT_BLOB PublicKey; } CERT_PUBLIC_KEY_INFO; typedef struct _CRYPT_ATTRIBUTE { LPSTR pszObjId; DWORD cValue; CRYPT_ATTR_BLOB *rgValue; } CRYPT_ATTRIBUTE; typedef struct _CRYPT_ATTRIBUTES { DWORD cAttr; CRYPT_ATTRIBUTE *rgAttr; } CRYPT_ATTRIBUTES; typedef struct _CRYPT_PRIVATE_KEY_INFO { DWORD Version; CRYPT_ALGORITHM_IDENTIFIER Algorithm; CRYPT_DER_BLOB PrivateKey; CRYPT_ATTRIBUTES *pAttributes; } CRYPT_PRIVATE_KEY_INFO; typedef struct _PUBLICKEYSTRUC { BYTE bType; BYTE bVersion; WORD reserved; ALG_ID aiKeyAlg; } BLOBHEADER, PUBLICKEYSTRUC; typedef struct _DSSPUBKEY { DWORD magic; DWORD bitlen; } DSSPUBKEY; typedef struct _DSSBLOBHEADER { PUBLICKEYSTRUC publickeystruc; DSSPUBKEY dsspubkey; } DSSBLOBHEADER; typedef struct _RSAPUBKEY { DWORD magic; DWORD bitlen; DWORD pubexp; } RSAPUBKEY; typedef struct _RSABLOBHEADER { PUBLICKEYSTRUC publickeystruc; RSAPUBKEY rsapubkey; } RSABLOBHEADER; typedef struct _PLAINTEXTKEYBLOB { BLOBHEADER hdr; DWORD dwKeySize; // rgbKeyData omitted since it is a flexible array member } PLAINTEXTKEYBLOB; typedef struct _DSSSEED { DWORD counter; BYTE seed[20]; } DSSSEED; BOOL CryptAcquireContextW(HCRYPTPROV *phProv, LPCWSTR pszContainer, LPCWSTR pszProvider, DWORD dwProvType, DWORD dwFlags); BOOL CryptReleaseContext(HCRYPTPROV hProv, DWORD dwFlags); BOOL CryptImportKey(HCRYPTPROV hProv, BYTE *pbData, DWORD dwDataLen, HCRYPTKEY hPubKey, DWORD dwFlags, HCRYPTKEY *phKey); BOOL CryptGenKey(HCRYPTPROV hProv, ALG_ID Algid, DWORD dwFlags, HCRYPTKEY *phKey); BOOL CryptGetKeyParam(HCRYPTKEY hKey, DWORD dwParam, BYTE *pbData, DWORD *pdwDataLen, DWORD dwFlags); BOOL CryptSetKeyParam(HCRYPTKEY hKey, DWORD dwParam, void *pbData, DWORD dwFlags); BOOL CryptExportKey(HCRYPTKEY hKey, HCRYPTKEY hExpKey, DWORD dwBlobType, DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen); BOOL CryptDestroyKey(HCRYPTKEY hKey); BOOL CryptCreateHash(HCRYPTPROV hProv, ALG_ID Algid, HCRYPTKEY hKey, DWORD dwFlags, HCRYPTHASH *phHash); BOOL CryptHashData(HCRYPTHASH hHash, BYTE *pbData, DWORD dwDataLen, DWORD dwFlags); BOOL CryptSetHashParam(HCRYPTHASH hHash, DWORD dwParam, BYTE *pbData, DWORD dwFlags); BOOL CryptSignHashW(HCRYPTHASH hHash, DWORD dwKeySpec, LPCWSTR sDescription, DWORD dwFlags, BYTE *pbSignature, DWORD *pdwSigLen); BOOL CryptVerifySignatureW(HCRYPTHASH hHash, BYTE *pbSignature, DWORD dwSigLen, HCRYPTKEY hPubKey, LPCWSTR sDescription, DWORD dwFlags); BOOL CryptDestroyHash(HCRYPTHASH hHash); BOOL CryptEncrypt(HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final, DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen, DWORD dwBufLen); BOOL CryptDecrypt(HCRYPTKEY hKey, HCRYPTHASH hHash, BOOL Final, DWORD dwFlags, BYTE *pbData, DWORD *pdwDataLen); z advapi32.dllzcannot load libraryzadvapi32.dll could not be foundcCstS)N)ffiZ getwinerrorrrM/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/_advapi32_cffi.pyr s) __future__rrrrZ_ffir_typesrerrorsr Zcffi__all__ZFFIr__version_info__Z set_unicodeZcdefdlopenr OSErrorefindr rrrrs&      r PK!̠+__pycache__/_advapi32_ctypes.cpython-38.pycnu[U af> @sddlmZmZmZmZddlZddlmZmZmZm Z m Z m Z m Z ddl mZmZddlmZddlmZddlmZd d gZz ejZWn>ek rZz eed d kred W5dZ[XYnXejZejZejZe Ze Z zGddde Z!e!Z"e!Z#e!Z$e!Z%Gddde Z&Gddde Z'Gddde Z(Gddde Z)Gddde Z*Gddde Z+Gddde Z,e,Z-Gddde Z.Gd d!d!e Z/Gd"d#d#e Z0Gd$d%d%e Z1Gd&d'd'e Z2Gd(d)d)e Z3eeej4ej4eegej5_6ejej5_7eegej8_6ejej8_7eeeeeeegej9_6eej9_7ee eeegej:_6ejej:_7eeeeeegej;_6ejej;_7eee egej<_6ejej<_7eeeeeeegej=_6eej=_7egej>_6ejej>_7ee eeeegej?_6eej?_7eeeegej@_6eej@_7eeeegejA_6eejA_7eeej4eeeegejB_6eejB_7eeeeej4egejC_6eejC_7egejD_6ejejD_7eeeeeeeegejE_6eejE_7eeeeeeegejF_6eejF_7WneGk red*YnXeHed+eeHed,eeHed-eeHed.e"eHed/e#eHed0e$eHed1e%eHede&eHede'eHede(eHede+eHede)eHede*eHede,eHede.eHed!e/eHed#e0eHed%e1eHed2e-eHed'e2eHed)e3d3d ZIdS)4)unicode_literalsdivisionabsolute_importprint_functionN)windllwintypesPOINTER Structurec_void_pc_char_pc_uint)BOOLDWORD)FFIEngineError)str_cls)LibraryNotFoundErroradvapi32 get_errorz'The specified module could not be foundzadvapi32.dll could not be foundc@s"eZdZdefdeejfgZdS)CRYPTOAPI_BLOBcbDatapbDataN)__name__ __module__ __qualname__rrctypesc_byte_fields_rrO/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/_advapi32_ctypes.pyr!s rc@seZdZdejfdefgZdS)CRYPT_ALGORITHM_IDENTIFIERpszObjIdZ ParametersN)rrrrLPSTRCRYPT_OBJID_BLOB_fieldsrrrr r!+sr!c@s"eZdZdefdefdefgZdS)CRYPT_BIT_BLOBrrZ cUnusedBitsN)rrrrPBYTErrrrr r&1sr&c@seZdZdefdefgZdS)CERT_PUBLIC_KEY_INFO AlgorithmZ PublicKeyN)rrrr!r&rrrrr r(8sr(c@s(eZdZdejfdefdeefgZdS)CRYPT_ATTRIBUTEr"ZcValueZrgValueN) rrrrr#rrCRYPT_ATTR_BLOBrrrrr r*>s r*c@s eZdZdefdeefgZdS)CRYPT_ATTRIBUTESZcAttrZrgAttrN)rrrrrr*rrrrr r,Es r,c@s,eZdZdefdefdefdeefgZdS)CRYPT_PRIVATE_KEY_INFOVersionr)Z PrivateKeyZ pAttributesN) rrrrr!CRYPT_DER_BLOBrr,rrrrr r-Ks  r-c@s.eZdZdejfdejfdejfdefgZdS)PUBLICKEYSTRUCZbTypeZbVersionreservedZaiKeyAlgN)rrrrBYTEZWORDALG_IDrrrrr r0Ss r0c@seZdZdefdefgZdS) DSSPUBKEYmagicbitlenNrrrrrrrrr r4\sr4c@seZdZdefdefgZdS) DSSBLOBHEADERpublickeystrucZ dsspubkeyN)rrrr0r4rrrrr r8bsr8c@s"eZdZdefdefdefgZdS) RSAPUBKEYr5r6ZpubexpNr7rrrr r:hsr:c@seZdZdefdefgZdS) RSABLOBHEADERr9Z rsapubkeyN)rrrr0r:rrrrr r;osr;c@seZdZdefdefgZdS)PLAINTEXTKEYBLOBhdrZ dwKeySizeN)rrr BLOBHEADERrrrrrr r<usr<c@s"eZdZdefdejdfgZdS)DSSSEEDcounterseedN)rrrrrr2rrrrr r?|s r?zError initializing ctypes HCRYPTPROV HCRYPTKEY HCRYPTHASHCRYPT_INTEGER_BLOBr$r/r+r>cCst}|t|fS)N)rZ GetLastError FormatError)errorrrr r%s)J __future__rrrrrrrrr r r r Zctypes.wintypesr rZ_ffir_typesrerrorsr__all__rOSErrorefindZHANDLErCrDrEr'r3rrFr$r/r+r!r&r(r*r,r-r0r>r4r8r:r;r<r?ZLPCWSTRZCryptAcquireContextWargtypesrestypeZCryptReleaseContextZCryptImportKeyZ CryptGenKeyZCryptGetKeyParamZCryptSetKeyParamZCryptExportKeyZCryptDestroyKeyZCryptCreateHashZ CryptHashDataZCryptSetHashParamZCryptSignHashWZCryptVerifySignatureWZCryptDestroyHashZ CryptEncryptZ CryptDecryptAttributeErrorsetattrrrrrr sP$                                  PK!J gg__pycache__/_cng.cpython-38.pycnu[U af@sddlmZmZmZmZddlmZddlmZm Z m Z edkrPddl m Z n ddl m Z dd d d d gZdd d Zdd Zdd ZGdd d ZdS))unicode_literalsdivisionabsolute_importprint_function)ffi)newnullunwrapZcffi)bcryptr BcryptConstclose_alg_handle handle_erroropen_alg_handlecCs,ttd}t||t|}t|t|S)NzBCRYPT_ALG_HANDLE *)rr ZBCryptOpenAlgorithmProviderr rr )ZconstantflagsZhandle_pointerresrC/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/_cng.pyrs cCst|d}t|dS)Nr)r ZBCryptCloseAlgorithmProviderr)handlerrrrrs cCst|dkr dStjdtjdtjdtjdtjdtjdtjd tjd i}d |}|dk rh||krh|d ||7}t |dS) z Extracts the last Windows error message into a python unicode string :param error_num: The number to get the error string for :return: A unicode string error message rNzThe object was not foundz8An invalid parameter was passed to a service or functionz_Not enough virtual memory or paging file quota is available to complete the specified operationzAn invalid HANDLE was specifiedz&The cryptographic signature is invalidzThe request is not supportedz,The buffer is too small to contain the entryz=The size of the buffer is invalid for the specified operationzNTSTATUS error 0x%0.2Xz: ) r STATUS_NOT_FOUNDSTATUS_INVALID_PARAMETERSTATUS_NO_MEMORYSTATUS_INVALID_HANDLESTATUS_INVALID_SIGNATURESTATUS_NOT_SUPPORTEDSTATUS_BUFFER_TOO_SMALLSTATUS_INVALID_BUFFER_SIZEOSError)Z error_nummessagesoutputrrrr#s.  c@seZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!dZ"dZ#dZ$d Z%d!Z&d"Z'd#Z(d$Z)dZ*d%Z+dZ,d&Z-dZ.d'Z/d(Z0d)Z1d*Z2d+Z3d,Z4d-Z5d.Z6d/Z7d0Z8d1Z9d2Z:d3Z;d4ZdZ?dZ@d7S)8r ZRNGZ KeyLengthZEffectiveKeyLengthZRSAPRIVATEBLOBZRSAFULLPRIVATEBLOBZ RSAPUBLICBLOBZDSAPRIVATEBLOBZ DSAPUBLICBLOBZECCPRIVATEBLOBZ ECCPUBLICBLOBiRSA1iRSA2iRSA3iDSPBiDSPViDPB2iDPV2rr riECS1iECS2iECS3iECS4iECS5iECS6l%l lll ll#liKDBMZ KeyDataBlobZ3DESZ3DES_112AESZDESZRC2ZRC4ZDSAZ ECDSA_P256Z ECDSA_P384Z ECDSA_P521ZRSAMD5SHA1SHA256SHA384SHA512N)A__name__ __module__ __qualname__ZBCRYPT_RNG_ALGORITHMZBCRYPT_KEY_LENGTHZBCRYPT_EFFECTIVE_KEY_LENGTHZBCRYPT_RSAPRIVATE_BLOBZBCRYPT_RSAFULLPRIVATE_BLOBZBCRYPT_RSAPUBLIC_BLOBZBCRYPT_DSA_PRIVATE_BLOBZBCRYPT_DSA_PUBLIC_BLOBZBCRYPT_ECCPRIVATE_BLOBZBCRYPT_ECCPUBLIC_BLOBZBCRYPT_RSAPUBLIC_MAGICZBCRYPT_RSAPRIVATE_MAGICZBCRYPT_RSAFULLPRIVATE_MAGICZBCRYPT_DSA_PUBLIC_MAGICZBCRYPT_DSA_PRIVATE_MAGICZBCRYPT_DSA_PUBLIC_MAGIC_V2ZBCRYPT_DSA_PRIVATE_MAGIC_V2ZDSA_HASH_ALGORITHM_SHA1ZDSA_HASH_ALGORITHM_SHA256ZDSA_HASH_ALGORITHM_SHA512Z DSA_FIPS186_2Z DSA_FIPS186_3ZBCRYPT_NO_KEY_VALIDATIONZBCRYPT_ECDSA_PUBLIC_P256_MAGICZBCRYPT_ECDSA_PRIVATE_P256_MAGICZBCRYPT_ECDSA_PUBLIC_P384_MAGICZBCRYPT_ECDSA_PRIVATE_P384_MAGICZBCRYPT_ECDSA_PUBLIC_P521_MAGICZBCRYPT_ECDSA_PRIVATE_P521_MAGICZSTATUS_SUCCESSrrrrrrrrZBCRYPT_KEY_DATA_BLOB_MAGICZBCRYPT_KEY_DATA_BLOB_VERSION1ZBCRYPT_KEY_DATA_BLOBZBCRYPT_PAD_PKCS1ZBCRYPT_PAD_OAEPZBCRYPT_PAD_PSSZBCRYPT_3DES_ALGORITHMZBCRYPT_3DES_112_ALGORITHMZBCRYPT_AES_ALGORITHMZBCRYPT_DES_ALGORITHMZBCRYPT_RC2_ALGORITHMZBCRYPT_RC4_ALGORITHMZBCRYPT_DSA_ALGORITHMZBCRYPT_ECDSA_P256_ALGORITHMZBCRYPT_ECDSA_P384_ALGORITHMZBCRYPT_ECDSA_P521_ALGORITHMZBCRYPT_RSA_ALGORITHMZBCRYPT_MD5_ALGORITHMZBCRYPT_SHA1_ALGORITHMZBCRYPT_SHA256_ALGORITHMZBCRYPT_SHA384_ALGORITHMZBCRYPT_SHA512_ALGORITHMZBCRYPT_ALG_HANDLE_HMAC_FLAGZBCRYPT_BLOCK_PADDINGrrrrr Fs|N)r) __future__rrrrrZ_ffirr r Z _cng_cffir Z _cng_ctypes__all__rrrr rrrrs    #PK!=FF$__pycache__/_cng_cffi.cpython-38.pycnu[U af~ @sddlmZmZmZmZddlmZddlmZddl m Z ddl m Z dgZ e Zedzed ZeeeWn>ek rZz eed d kre d W5d Z[XYnXd S))unicode_literalsdivisionabsolute_importprint_function) register_ffi)str_cls)LibraryNotFoundError)FFIbcryptaK typedef HANDLE BCRYPT_ALG_HANDLE; typedef HANDLE BCRYPT_KEY_HANDLE; typedef ULONG NTSTATUS; typedef unsigned char *PUCHAR; typedef unsigned char *PBYTE; typedef struct _BCRYPT_RSAKEY_BLOB { ULONG Magic; ULONG BitLength; ULONG cbPublicExp; ULONG cbModulus; ULONG cbPrime1; ULONG cbPrime2; } BCRYPT_RSAKEY_BLOB; typedef struct _BCRYPT_DSA_KEY_BLOB { ULONG dwMagic; ULONG cbKey; UCHAR Count[4]; UCHAR Seed[20]; UCHAR q[20]; } BCRYPT_DSA_KEY_BLOB; typedef struct _BCRYPT_DSA_KEY_BLOB_V2 { ULONG dwMagic; ULONG cbKey; INT hashAlgorithm; INT standardVersion; ULONG cbSeedLength; ULONG cbGroupSize; UCHAR Count[4]; } BCRYPT_DSA_KEY_BLOB_V2; typedef struct _BCRYPT_ECCKEY_BLOB { ULONG dwMagic; ULONG cbKey; } BCRYPT_ECCKEY_BLOB; typedef struct _BCRYPT_PKCS1_PADDING_INFO { LPCWSTR pszAlgId; } BCRYPT_PKCS1_PADDING_INFO; typedef struct _BCRYPT_PSS_PADDING_INFO { LPCWSTR pszAlgId; ULONG cbSalt; } BCRYPT_PSS_PADDING_INFO; typedef struct _BCRYPT_OAEP_PADDING_INFO { LPCWSTR pszAlgId; PUCHAR pbLabel; ULONG cbLabel; } BCRYPT_OAEP_PADDING_INFO; typedef struct _BCRYPT_KEY_DATA_BLOB_HEADER { ULONG dwMagic; ULONG dwVersion; ULONG cbKeyData; } BCRYPT_KEY_DATA_BLOB_HEADER; NTSTATUS BCryptOpenAlgorithmProvider(BCRYPT_ALG_HANDLE *phAlgorithm, LPCWSTR pszAlgId, LPCWSTR pszImplementation, DWORD dwFlags); NTSTATUS BCryptCloseAlgorithmProvider(BCRYPT_ALG_HANDLE hAlgorithm, DWORD dwFlags); NTSTATUS BCryptSetProperty(HANDLE hObject, LPCWSTR pszProperty, ULONG *pbInput, ULONG cbInput, ULONG dwFlags); NTSTATUS BCryptImportKeyPair(BCRYPT_ALG_HANDLE hAlgorithm, BCRYPT_KEY_HANDLE hImportKey, LPCWSTR pszBlobType, BCRYPT_KEY_HANDLE *phKey, PUCHAR pbInput, ULONG cbInput, ULONG dwFlags); NTSTATUS BCryptImportKey(BCRYPT_ALG_HANDLE hAlgorithm, BCRYPT_KEY_HANDLE hImportKey, LPCWSTR pszBlobType, BCRYPT_KEY_HANDLE *phKey, PUCHAR pbKeyObject, ULONG cbKeyObject, PUCHAR pbInput, ULONG cbInput, ULONG dwFlags); NTSTATUS BCryptDestroyKey(BCRYPT_KEY_HANDLE hKey); NTSTATUS BCryptVerifySignature(BCRYPT_KEY_HANDLE hKey, void *pPaddingInfo, PUCHAR pbHash, ULONG cbHash, PUCHAR pbSignature, ULONG cbSignature, ULONG dwFlags); NTSTATUS BCryptSignHash(BCRYPT_KEY_HANDLE hKey, void * pPaddingInfo, PBYTE pbInput, DWORD cbInput, PBYTE pbOutput, DWORD cbOutput, DWORD *pcbResult, ULONG dwFlags); NTSTATUS BCryptEncrypt(BCRYPT_KEY_HANDLE hKey, PUCHAR pbInput, ULONG cbInput, void *pPaddingInfo, PUCHAR pbIV, ULONG cbIV, PUCHAR pbOutput, ULONG cbOutput, ULONG *pcbResult, ULONG dwFlags); NTSTATUS BCryptDecrypt(BCRYPT_KEY_HANDLE hKey, PUCHAR pbInput, ULONG cbInput, void *pPaddingInfo, PUCHAR pbIV, ULONG cbIV, PUCHAR pbOutput, ULONG cbOutput, ULONG *pcbResult, ULONG dwFlags); NTSTATUS BCryptDeriveKeyPBKDF2(BCRYPT_ALG_HANDLE hPrf, PUCHAR pbPassword, ULONG cbPassword, PUCHAR pbSalt, ULONG cbSalt, ULONGLONG cIterations, PUCHAR pbDerivedKey, ULONG cbDerivedKey, ULONG dwFlags); NTSTATUS BCryptGenRandom(BCRYPT_ALG_HANDLE hAlgorithm, PUCHAR pbBuffer, ULONG cbBuffer, ULONG dwFlags); NTSTATUS BCryptGenerateKeyPair(BCRYPT_ALG_HANDLE hAlgorithm, BCRYPT_KEY_HANDLE *phKey, ULONG dwLength, ULONG dwFlags); NTSTATUS BCryptFinalizeKeyPair(BCRYPT_KEY_HANDLE hKey, ULONG dwFlags); NTSTATUS BCryptExportKey(BCRYPT_KEY_HANDLE hKey, BCRYPT_KEY_HANDLE hExportKey, LPCWSTR pszBlobType, PUCHAR pbOutput, ULONG cbOutput, ULONG *pcbResult, ULONG dwFlags); z bcrypt.dllzcannot load libraryzLbcrypt.dll could not be found - Windows XP and Server 2003 are not supportedN) __future__rrrrZ_ffir_typesrerrorsr Zcffir __all__ffiZcdefdlopenr OSErrorefindrrH/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/_cng_cffi.pys     ` PK!.+22&__pycache__/_cng_ctypes.cpython-38.pycnu[U af  @sddlmZmZmZmZddlmZmZmZm Z m Z m Z m Z m Z ddlmZmZmZddlmZddlmZddlmZdgZz ejZWn>ek rZz eed d kred W5d Z[XYnXejZejZejZ e Z!e Z"zeeeeegej#_$e ej#_%eegej&_$e ej&_%eeeeee!eegej'_$e ej'_%eeeeee!ee!eeg ej(_$e ej(_%egej)_$e ej)_%ee e!ee!eegej*_$e ej*_%ee e"ee"eeeegej+_$e ej+_%eee eegej,_$e ej,_%ee!ee e!ee!eeeeg ej-_$e ej-_%ee!ee e!ee!eeeeg ej._$e ej._%ee!ee!ee e!eeg ej/_$e ej/_%ee!eegej0_$e ej0_%eeeeegej1_$e ej1_%eegej2_$e ej2_%eeee!eeeegej3_$e ej3_%Wne4k red YnXGddde Z5Gddde Z6Gddde Z7Gddde Z8Gddde Z9Gddde Z:Gddde Z;Gddde Z __future__rrrrctypesrrrr r r r r Zctypes.wintypesrrrZ_ffir_typesrerrorsr__all__rOSErrorefindZHANDLEr/r0ZNTSTATUSr-ZPBYTEZBCryptOpenAlgorithmProviderargtypesrestypeZBCryptCloseAlgorithmProviderZBCryptImportKeyPairZBCryptImportKeyZBCryptDestroyKeyZBCryptVerifySignatureZBCryptSignHashZBCryptSetPropertyZ BCryptEncryptZ BCryptDecryptZBCryptDeriveKeyPBKDF2ZBCryptGenRandomZBCryptGenerateKeyPairZBCryptFinalizeKeyPairZBCryptExportKeyAttributeErrorrrr&r(r)r+r,r.setattrrrrrs<(                        PK!5Saa#__pycache__/_crypt32.cpython-38.pycnu[U afi@sddlmZmZmZmZddlmZddlmZddl m Z ddl m Z edkrddd l mZmZndd lmZmZd d d gZd d ZGdd d ZdS))unicode_literalsdivisionabsolute_importprint_function)ffi) _try_decode)buffer_from_bytes)str_clsZcffi)crypt32 get_errorr Crypt32Const handle_errorcCs0|rdSt\}}t|ts$t|}t|dS)z Extracts the last Windows error message into a python unicode string :param result: A function result, 0 or None indicates failure :return: A unicode string error message N)r isinstancer r OSError)result_Z error_stringrG/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/_crypt32.pyrs   c@sxeZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ d ZdZd Zd Zd Zd ZdZdZdZdZedZedZedZdS)rrzi sMemoryi rill`llll ll s1.3.6.1.5.5.7.3.1s1.3.6.1.4.1.311.10.3.3s2.16.840.1.113730.4.1N)__name__ __module__ __qualname__ZX509_ASN_ENCODINGZERROR_INSUFFICIENT_BUFFERZ%CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAGZCRYPT_E_NOT_FOUNDZCERT_STORE_PROV_MEMORYZCERT_STORE_CREATE_NEW_FLAGZCERT_STORE_ADD_USE_EXISTINGZUSAGE_MATCH_TYPE_ORZCERT_CHAIN_POLICY_SSLZAUTHTYPE_SERVERZ'CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAGZ.CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGSZCERT_CHAIN_CACHE_END_CERTZ&CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLYZTRUST_E_CERT_SIGNATUREZCERT_E_EXPIREDZ CERT_E_ROLEZCERT_E_PURPOSEZCERT_E_UNTRUSTEDROOTZCERT_E_CN_NO_MATCHZCRYPT_E_REVOKEDr ZPKIX_KP_SERVER_AUTHZSERVER_GATED_CRYPTOZ SGC_NETSCAPErrrrr,s0N) __future__rrrrr_decoder Z_ffir _typesr Z _crypt32_cffir r Z_crypt32_ctypes__all__rrrrrrs     PK!**(__pycache__/_crypt32_cffi.cpython-38.pycnu[U af  @sddlmZmZmZmZddlZddlmZddlm Z ddl m Z ddl Z ddgZ e Ze jd krped ejd kred n ed edzedZeeeWn>ek rZz e eddkre dW5dZ[XYnXddZdS))unicode_literalsdivisionabsolute_importprint_functionN) register_ffi)str_cls)LibraryNotFoundErrorcrypt32 get_error)r Tlztypedef uint64_t ULONG_PTR;z typedef unsigned long ULONG_PTR;a typedef HANDLE HCERTSTORE; typedef unsigned char *PBYTE; typedef struct _CRYPTOAPI_BLOB { DWORD cbData; PBYTE pbData; } CRYPTOAPI_BLOB; typedef CRYPTOAPI_BLOB CRYPT_INTEGER_BLOB; typedef CRYPTOAPI_BLOB CERT_NAME_BLOB; typedef CRYPTOAPI_BLOB CRYPT_BIT_BLOB; typedef CRYPTOAPI_BLOB CRYPT_OBJID_BLOB; typedef struct _CRYPT_ALGORITHM_IDENTIFIER { LPSTR pszObjId; CRYPT_OBJID_BLOB Parameters; } CRYPT_ALGORITHM_IDENTIFIER; typedef struct _FILETIME { DWORD dwLowDateTime; DWORD dwHighDateTime; } FILETIME; typedef struct _CERT_PUBLIC_KEY_INFO { CRYPT_ALGORITHM_IDENTIFIER Algorithm; CRYPT_BIT_BLOB PublicKey; } CERT_PUBLIC_KEY_INFO; typedef struct _CERT_EXTENSION { LPSTR pszObjId; BOOL fCritical; CRYPT_OBJID_BLOB Value; } CERT_EXTENSION, *PCERT_EXTENSION; typedef struct _CERT_INFO { DWORD dwVersion; CRYPT_INTEGER_BLOB SerialNumber; CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm; CERT_NAME_BLOB Issuer; FILETIME NotBefore; FILETIME NotAfter; CERT_NAME_BLOB Subject; CERT_PUBLIC_KEY_INFO SubjectPublicKeyInfo; CRYPT_BIT_BLOB IssuerUniqueId; CRYPT_BIT_BLOB SubjectUniqueId; DWORD cExtension; PCERT_EXTENSION *rgExtension; } CERT_INFO, *PCERT_INFO; typedef struct _CERT_CONTEXT { DWORD dwCertEncodingType; PBYTE pbCertEncoded; DWORD cbCertEncoded; PCERT_INFO pCertInfo; HCERTSTORE hCertStore; } CERT_CONTEXT, *PCERT_CONTEXT; typedef struct _CERT_TRUST_STATUS { DWORD dwErrorStatus; DWORD dwInfoStatus; } CERT_TRUST_STATUS, *PCERT_TRUST_STATUS; typedef struct _CERT_ENHKEY_USAGE { DWORD cUsageIdentifier; LPSTR *rgpszUsageIdentifier; } CERT_ENHKEY_USAGE, *PCERT_ENHKEY_USAGE; typedef struct _CERT_CHAIN_ELEMENT { DWORD cbSize; PCERT_CONTEXT pCertContext; CERT_TRUST_STATUS TrustStatus; void *pRevocationInfo; PCERT_ENHKEY_USAGE pIssuanceUsage; PCERT_ENHKEY_USAGE pApplicationUsage; LPCWSTR pwszExtendedErrorInfo; } CERT_CHAIN_ELEMENT, *PCERT_CHAIN_ELEMENT; typedef struct _CERT_SIMPLE_CHAIN { DWORD cbSize; CERT_TRUST_STATUS TrustStatus; DWORD cElement; PCERT_CHAIN_ELEMENT *rgpElement; void *pTrustListInfo; BOOL fHasRevocationFreshnessTime; DWORD dwRevocationFreshnessTime; } CERT_SIMPLE_CHAIN, *PCERT_SIMPLE_CHAIN; typedef struct _CERT_CHAIN_CONTEXT { DWORD cbSize; CERT_TRUST_STATUS TrustStatus; DWORD cChain; PCERT_SIMPLE_CHAIN *rgpChain; DWORD cLowerQualityChainContext; void *rgpLowerQualityChainContext; BOOL fHasRevocationFreshnessTime; DWORD dwRevocationFreshnessTime; } CERT_CHAIN_CONTEXT, *PCERT_CHAIN_CONTEXT; typedef struct _CERT_USAGE_MATCH { DWORD dwType; CERT_ENHKEY_USAGE Usage; } CERT_USAGE_MATCH; typedef struct _CERT_CHAIN_PARA { DWORD cbSize; CERT_USAGE_MATCH RequestedUsage; } CERT_CHAIN_PARA; typedef struct _CERT_CHAIN_POLICY_PARA { DWORD cbSize; DWORD dwFlags; void *pvExtraPolicyPara; } CERT_CHAIN_POLICY_PARA; typedef struct _HTTPSPolicyCallbackData { DWORD cbSize; DWORD dwAuthType; DWORD fdwChecks; WCHAR *pwszServerName; } SSL_EXTRA_CERT_CHAIN_POLICY_PARA; typedef struct _CERT_CHAIN_POLICY_STATUS { DWORD cbSize; DWORD dwError; LONG lChainIndex; LONG lElementIndex; void *pvExtraPolicyStatus; } CERT_CHAIN_POLICY_STATUS; typedef HANDLE HCERTCHAINENGINE; typedef HANDLE HCRYPTPROV; HCERTSTORE CertOpenStore(LPCSTR lpszStoreProvider, DWORD dwMsgAndCertEncodingType, HCRYPTPROV hCryptProv, DWORD dwFlags, void *pvPara); BOOL CertAddEncodedCertificateToStore(HCERTSTORE hCertStore, DWORD dwCertEncodingType, BYTE *pbCertEncoded, DWORD cbCertEncoded, DWORD dwAddDisposition, PCERT_CONTEXT *ppCertContext); BOOL CertGetCertificateChain(HCERTCHAINENGINE hChainEngine, CERT_CONTEXT *pCertContext, FILETIME *pTime, HCERTSTORE hAdditionalStore, CERT_CHAIN_PARA *pChainPara, DWORD dwFlags, void *pvReserved, PCERT_CHAIN_CONTEXT *ppChainContext); BOOL CertVerifyCertificateChainPolicy(ULONG_PTR pszPolicyOID, PCERT_CHAIN_CONTEXT pChainContext, CERT_CHAIN_POLICY_PARA *pPolicyPara, CERT_CHAIN_POLICY_STATUS *pPolicyStatus); void CertFreeCertificateChain(PCERT_CHAIN_CONTEXT pChainContext); HCERTSTORE CertOpenSystemStoreW(HANDLE hprov, LPCWSTR szSubsystemProtocol); PCERT_CONTEXT CertEnumCertificatesInStore(HCERTSTORE hCertStore, CERT_CONTEXT *pPrevCertContext); BOOL CertCloseStore(HCERTSTORE hCertStore, DWORD dwFlags); BOOL CertGetEnhancedKeyUsage(CERT_CONTEXT *pCertContext, DWORD dwFlags, CERT_ENHKEY_USAGE *pUsage, DWORD *pcbUsage); z crypt32.dllzcannot load libraryzcrypt32.dll could not be foundcCstS)N)ffiZ getwinerrorrrL/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/_crypt32_cffi.pyr s) __future__rrrrsysZ_ffir_typesrerrorsr Zcffi__all__ZFFIr__version_info__Z set_unicodemaxsizeZcdefdlopenr OSErrorefindr rrrrs0          PK!|!!*__pycache__/_crypt32_ctypes.cpython-38.pycnu[U af @sddlmZmZmZmZddlZddlZddlmZmZm Z m Z m Z m Z ddl mZddlmZddlmZddlmZd d lmZd d gZz ejZWn>ek rZz eed dkredW5dZ[XYnXejZejZejZejZ e Z!ej"dkrej#Z$nej%Z$zNGddde Z&e&Z'e&Z(e&Z)e&Z*Gddde Z+Gddde Z,Gddde Z-e e-Z.Gddde Z/e e/Z0Gddde Z1e e1Z2Gddde Z3e e3Z4Gdd d e Z5Gd!d"d"e Z6e e6Z7Gd#d$d$e Z8e e8Z9Gd%d&d&e Z:e e:Z;Gd'd(d(e ZGd-d.d.e Z?Gd/d0d0e Z@ejAeeee gejB_CeejB_Deee!eee e2gejE_CejFejE_Dee2e ejGee e=ee e e;gejH_CejFejH_De$e;e e>e e@gejI_CejFejI_De;gejJ_CdejJ_DejejKgejL_CeejL_Dee2gejM_Ce2ejM_DeegejN_CejFejN_De2ee e egejO_CejFejO_DWnePk rzed1YnXeQed2ejGeQede3eQede1eQed3e2eQed(e<eQed*e=eQed,e>eQed.e?eQed0e@eQed4e;d5d ZRdS)6)unicode_literalsdivisionabsolute_importprint_functionN)windllwintypesPOINTER Structurec_void_pc_char_p)DWORD)FFIEngineError)str_cls)LibraryNotFoundError)kernel32crypt32 get_errorz'The specified module could not be foundzcrypt32.dll could not be foundlc@seZdZdefdefgZdS)CRYPTOAPI_BLOBZcbDataZpbDataN__name__ __module__ __qualname__r r _fields_rrN/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/_crypt32_ctypes.pyr(src@seZdZdejfdefgZdS)CRYPT_ALGORITHM_IDENTIFIERpszObjIdZ ParametersN)rrrrLPSTRCRYPT_OBJID_BLOBrrrrrr2src@seZdZdefdefgZdS)CERT_PUBLIC_KEY_INFOZ AlgorithmZ PublicKeyN)rrrrCRYPT_BIT_BLOBrrrrrr"8sr"c@s&eZdZdejfdejfdefgZdS)CERT_EXTENSIONrZ fCriticalValueN)rrrrr BOOLr!rrrrrr$>sr$c@s`eZdZdefdefdefdefdejfdejfdefde fd e fd e fd efd e e fg Z d S) CERT_INFOZ dwVersionZ SerialNumberZSignatureAlgorithmZIssuerZ NotBeforeZNotAfterSubjectZSubjectPublicKeyInfoZIssuerUniqueIdZSubjectUniqueIdZ cExtensionZ rgExtensionN)rrrr CRYPT_INTEGER_BLOBrCERT_NAME_BLOBrFILETIMEr"r#rPCERT_EXTENSIONrrrrrr'Fs r'c@s.eZdZdefdefdefdefdefgZdS) CERT_CONTEXTZdwCertEncodingTypeZ pbCertEncodedZ cbCertEncodedZ pCertInfoZ hCertStoreN)rrrr r PCERT_INFO HCERTSTORErrrrrr-Ws r-c@s&eZdZdefdeeejfgZdS)CERT_ENHKEY_USAGEZcUsageIdentifierZrgpszUsageIdentifierN)rrrr rrZBYTErrrrrr0bsr0c@seZdZdefdefgZdS)CERT_TRUST_STATUSZ dwErrorStatusZ dwInfoStatusN)rrrr rrrrrr1jsr1c@s<eZdZdefdefdefdefdefdefdej fgZ dS) CERT_CHAIN_ELEMENTcbSizeZ pCertContext TrustStatusZpRevocationInfoZpIssuanceUsageZpApplicationUsageZpwszExtendedErrorInfoN) rrrr PCERT_CONTEXTr1r PCERT_ENHKEY_USAGErLPCWSTRrrrrrr2psr2c@s@eZdZdefdefdefdeefdefdej fdefgZ dS) CERT_SIMPLE_CHAINr3r4ZcElementZ rgpElementZpTrustListInfofHasRevocationFreshnessTimedwRevocationFreshnessTimeN) rrrr r1rPCERT_CHAIN_ELEMENTr rr&rrrrrr8}s r8c @sFeZdZdefdefdefdeefdefdefdej fdefgZ d S) CERT_CHAIN_CONTEXTr3r4ZcChainZrgpChainZcLowerQualityChainContextZrgpLowerQualityChainContextr9r:N) rrrr r1rPCERT_SIMPLE_CHAINr rr&rrrrrr<s r<c@seZdZdefdefgZdS)CERT_USAGE_MATCHZdwTypeUsageN)rrrr r0rrrrrr>sr>c@seZdZdefdefgZdS)CERT_CHAIN_PARAr3ZRequestedUsageN)rrrr r>rrrrrr@sr@c@s"eZdZdefdefdefgZdS)CERT_CHAIN_POLICY_PARAr3ZdwFlagsZpvExtraPolicyParaNrrrrrrAsrAc@s*eZdZdefdefdefdejfgZdS) SSL_EXTRA_CERT_CHAIN_POLICY_PARAr3Z dwAuthTypeZ fdwChecksZpwszServerNameN)rrrr rr7rrrrrrBs rBc@s2eZdZdefdefdejfdejfdefgZdS)CERT_CHAIN_POLICY_STATUSr3ZdwErrorZ lChainIndexZ lElementIndexZpvExtraPolicyStatusN)rrrr rLONGr rrrrrrCs rCzError initializing ctypesr+r5PCERT_CHAIN_CONTEXTcCst}|t|fS)N)ctypesZ GetLastError FormatError)errorrrrrs)S __future__rrrrsysrFrrrr r r Zctypes.wintypesr Z_ffir_typesrerrorsrZ _kernel32r__all__rOSErrorefindZHANDLEr/ZHCERTCHAINENGINEZ HCRYPTPROVZ HCRYPTKEYZPBYTEmaxsizec_uint64Z ULONG_PTRc_ulongrr)r*r#r!rr"r$r,r'r.r-r5r0r6r1r2r;r8r=r<rEr>r@rArBrCZLPCSTRZ CertOpenStoreargtypesrestypeZ CertAddEncodedCertificateToStorer&r+ZCertGetCertificateChainZ CertVerifyCertificateChainPolicyZCertFreeCertificateChainr7ZCertOpenSystemStoreWZCertEnumCertificatesInStoreZCertCloseStoreZCertGetEnhancedKeyUsageAttributeErrorsetattrrrrrrs                          PK!Yzz"__pycache__/_decode.cpython-38.pycnu[U af@sHddlmZmZmZmZddlZddlmZeZ ddgZ ddZ dS) )unicode_literalsdivisionabsolute_importprint_functionN)str_clszutf-8cp1252c Csfz t|tWStk rXtD]2}zt||ddWYStk rPYq Xq YnXt|ddS)z Tries decoding a byte string from the OS into a unicode string :param byte_string: A byte string :return: A unicode string strict)errorsreplace)r _encodingUnicodeDecodeError_fallback_encodings)Z byte_stringencodingrF/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/_decode.py _try_decode s  r) __future__rrrrlocale_typesrgetpreferredencodingr rrrrrrs  PK!׺@$__pycache__/_kernel32.cpython-38.pycnu[U af&@s|ddlmZmZmZmZddlmZddlmZddl m Z edkrXddl m Z m Z nddlm Z m Z d d gZd d Zd S) )unicode_literalsdivisionabsolute_importprint_function)ffi) _try_decode)str_clsZcffi)kernel32 get_error handle_errorr cCs0|rdSt\}}t|ts$t|}t|dS)z Extracts the last Windows error message into a python unicode string :param result: A function result, 0 or None indicates failure :return: A unicode string error message N)r isinstancer r OSError)result_Z error_stringrH/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/_kernel32.pyr s   N) __future__rrrrr_decoder _typesr Z_kernel32_cffir r Z_kernel32_ctypes__all__r rrrrs    PK!̵)__pycache__/_kernel32_cffi.cpython-38.pycnu[U af @sddlmZmZmZmZddlmZddlmZddl m Z ddl Z ddgZ e Ze jd krhed ed zed ZeeeWn>ek rZz eed dkre dW5dZ[XYnXddZdS))unicode_literalsdivisionabsolute_importprint_function) register_ffi)str_cls)LibraryNotFoundErrorN get_errorkernel32)r Ta typedef long long LARGE_INTEGER; BOOL QueryPerformanceCounter(LARGE_INTEGER *lpPerformanceCount); typedef struct _FILETIME { DWORD dwLowDateTime; DWORD dwHighDateTime; } FILETIME; void GetSystemTimeAsFileTime(FILETIME *lpSystemTimeAsFileTime); z kernel32.dllzcannot load libraryzkernel32.dll could not be foundcCstS)N)ffiZ getwinerrorrrM/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/_kernel32_cffi.pyr +s) __future__rrrrZ_ffir_typesrerrorsr Zcffi__all__ZFFIr__version_info__Z set_unicodeZcdefdlopenr OSErrorefindr rrrrs&       PK!\+__pycache__/_kernel32_ctypes.cpython-38.pycnu[U af @s<ddlmZmZmZmZddlZddlmZmZmZm Z m Z ddl m Z ddl mZddlmZdd gZz ejZWn>ek rZz eed d kred W5dZ[XYnXe ZzBeegej_ejej_Gd dde Zeegej_dej_Wnek re dYnXeedeeededdZdS))unicode_literalsdivisionabsolute_importprint_functionN)windllwintypesPOINTER c_longlong Structure)FFIEngineError)str_cls)LibraryNotFoundError get_errorkernel32z'The specified module could not be foundzkernel32.dll could not be foundc@s eZdZdejfdejfgZdS)FILETIMEZ dwLowDateTimeZdwHighDateTimeN)__name__ __module__ __qualname__rZDWORD_fields_rrO/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/_kernel32_ctypes.pyrsrzError initializing ctypes LARGE_INTEGERcCst}|t|fS)N)ctypesZ GetLastError FormatError)errorrrrr0s) __future__rrrrrrrrr r Z_ffir _typesr errorsr__all__rOSErrorefindrZQueryPerformanceCounterargtypesZBOOLrestyperZGetSystemTimeAsFileTimeAttributeErrorsetattrrrrrrs4        PK!=w#__pycache__/_secur32.cpython-38.pycnu[U af@sddlmZmZmZmZddlmZddlmZddl m Z ddl m Z edkrddd l mZmZndd lmZmZd d d gZddd ZGdd d Zd S))unicode_literalsdivisionabsolute_importprint_function)ffi) _try_decode)TLSError)str_clsZcffi)secur32 get_error handle_errorr Secur32ConstNcCs~|dkr dS|tjkrtd|tjkr0td|tjkrBtdt\}}t|ts^t|}|dkrjt }|d||dS)a5 Extracts the last Windows error message into a python unicode string :param result: A function result, 0 or None indicates failure :param exception_class: The exception class to use for the exception if an error occurred :return: A unicode string error message rNz"A packet was received out of orderzA packet was received alteredzThe TLS session expiredzSECURITY_STATUS error 0x%0.2X: ) rSEC_E_OUT_OF_SEQUENCEr SEC_E_MESSAGE_ALTEREDSEC_E_CONTEXT_EXPIREDr isinstancer r OSError)resultZexception_class_Z error_stringrG/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/_secur32.pyrs     c@s,eZdZdZdZdZdZdZdZdZ dZ dZ d Z d Z d Zd Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!dZ"dZ#dZ$dZ%dZ&dZ'dZ(dZ)dZ*dZ+d Z,dZ-d!Z.dZ/dZ0d"Z1d#Z2d$Z3d%Z4dZ5dZ6dZ7d&Z8d'Z9d(Z:d)Z;d*Zd-Z?d.Z@d/ZAd0ZBd1ZCd2ZDd3ZEd4ZFd5ZGd6ZHd7ZId8ZJd9S):rrz,Microsoft Unified Security Protocol Provider i@ri i i! lli1lll]l"l%l(l&ll!i  iirZSiiifififihififiii i iiiiiii$i"i"N)K__name__ __module__ __qualname__ZSCHANNEL_CRED_VERSIONZSECPKG_CRED_OUTBOUNDZ UNISP_NAMEZSCH_CRED_MANUAL_CRED_VALIDATIONZSCH_CRED_AUTO_CRED_VALIDATIONZSCH_USE_STRONG_CRYPTOZSCH_CRED_NO_DEFAULT_CREDSZSECBUFFER_VERSIONZSEC_E_OKZSEC_I_CONTINUE_NEEDEDZSEC_I_CONTEXT_EXPIREDZSEC_I_RENEGOTIATEZSEC_E_INCOMPLETE_MESSAGEZSEC_E_INVALID_TOKENrrrZSEC_E_INVALID_PARAMETERZSEC_E_WRONG_PRINCIPALZSEC_E_UNTRUSTED_ROOTZSEC_E_CERT_EXPIREDZSEC_E_ILLEGAL_MESSAGEZSEC_E_INTERNAL_ERRORZSEC_E_BUFFER_TOO_SMALLZSEC_I_INCOMPLETE_CREDENTIALSZISC_REQ_REPLAY_DETECTZISC_REQ_SEQUENCE_DETECTZISC_REQ_CONFIDENTIALITYZISC_REQ_ALLOCATE_MEMORYZISC_REQ_INTEGRITYZISC_REQ_STREAMZISC_REQ_USE_SUPPLIED_CREDSZISC_RET_REPLAY_DETECTZISC_RET_SEQUENCE_DETECTZISC_RET_CONFIDENTIALITYZISC_RET_ALLOCATED_MEMORYZISC_RET_INTEGRITYZISC_RET_STREAMZSECBUFFER_ALERTZSECBUFFER_STREAM_HEADERZSECBUFFER_STREAM_TRAILERZSECBUFFER_EXTRAZSECBUFFER_TOKENZSECBUFFER_DATAZSECBUFFER_EMPTYZSECPKG_ATTR_STREAM_SIZESZSECPKG_ATTR_CONNECTION_INFOZSECPKG_ATTR_REMOTE_CERT_CONTEXTZSP_PROT_TLS1_2_CLIENTZSP_PROT_TLS1_1_CLIENTZSP_PROT_TLS1_CLIENTZSP_PROT_SSL3_CLIENTZSP_PROT_SSL2_CLIENTZ CALG_AES_256Z CALG_AES_128Z CALG_3DESZCALG_RC4ZCALG_RC2ZCALG_DESZCALG_MD5Z CALG_SHA1Z CALG_SHA256Z CALG_SHA384Z CALG_SHA512Z CALG_DH_SFZ CALG_DH_EPHEMZ CALG_ECDHZ CALG_ECDHEZ CALG_RSA_KEYXZ CALG_RSA_SIGNZ CALG_ECDSAZ CALG_DSS_SIGNrrrrr;s)N) __future__rrrrr_decoder errorsr _typesr Z _secur32_cffir r Z_secur32_ctypes__all__rrrrrrs      %PK!LJ(__pycache__/_secur32_cffi.cpython-38.pycnu[U af @sddlmZmZmZmZddlZddlmZddlm Z ddl m Z ddl Z ddgZ e Ze jd krped ejd kred n ed edzedZeeeWn>ek rZz e eddkre dW5dZ[XYnXddZdS))unicode_literalsdivisionabsolute_importprint_functionN) register_ffi)str_cls)LibraryNotFoundError get_errorsecur32)r Tlztypedef uint64_t ULONG_PTR;z typedef unsigned long ULONG_PTR;ar typedef HANDLE HCERTSTORE; typedef unsigned int ALG_ID; typedef WCHAR SEC_WCHAR; typedef unsigned long SECURITY_STATUS; typedef void *LUID; typedef void *SEC_GET_KEY_FN; typedef struct _SecHandle { ULONG_PTR dwLower; ULONG_PTR dwUpper; } SecHandle; typedef SecHandle CredHandle; typedef SecHandle CtxtHandle; typedef struct _SCHANNEL_CRED { DWORD dwVersion; DWORD cCreds; void *paCred; HCERTSTORE hRootStore; DWORD cMappers; void **aphMappers; DWORD cSupportedAlgs; ALG_ID *palgSupportedAlgs; DWORD grbitEnabledProtocols; DWORD dwMinimumCipherStrength; DWORD dwMaximumCipherStrength; DWORD dwSessionLifespan; DWORD dwFlags; DWORD dwCredFormat; } SCHANNEL_CRED; typedef struct _TimeStamp { DWORD dwLowDateTime; DWORD dwHighDateTime; } TimeStamp; typedef struct _SecBuffer { ULONG cbBuffer; ULONG BufferType; BYTE *pvBuffer; } SecBuffer; typedef struct _SecBufferDesc { ULONG ulVersion; ULONG cBuffers; SecBuffer *pBuffers; } SecBufferDesc; typedef struct _SecPkgContext_StreamSizes { ULONG cbHeader; ULONG cbTrailer; ULONG cbMaximumMessage; ULONG cBuffers; ULONG cbBlockSize; } SecPkgContext_StreamSizes; typedef struct _CERT_CONTEXT { DWORD dwCertEncodingType; BYTE *pbCertEncoded; DWORD cbCertEncoded; void *pCertInfo; HCERTSTORE hCertStore; } CERT_CONTEXT; typedef struct _SecPkgContext_ConnectionInfo { DWORD dwProtocol; ALG_ID aiCipher; DWORD dwCipherStrength; ALG_ID aiHash; DWORD dwHashStrength; ALG_ID aiExch; DWORD dwExchStrength; } SecPkgContext_ConnectionInfo; SECURITY_STATUS AcquireCredentialsHandleW(SEC_WCHAR *pszPrincipal, SEC_WCHAR *pszPackage, ULONG fCredentialUse, LUID *pvLogonID, void *pAuthData, SEC_GET_KEY_FN pGetKeyFn, void *pvGetKeyArgument, CredHandle *phCredential, TimeStamp *ptsExpiry); SECURITY_STATUS FreeCredentialsHandle(CredHandle *phCredential); SECURITY_STATUS InitializeSecurityContextW(CredHandle *phCredential, CtxtHandle *phContext, SEC_WCHAR *pszTargetName, ULONG fContextReq, ULONG Reserved1, ULONG TargetDataRep, SecBufferDesc *pInput, ULONG Reserved2, CtxtHandle *phNewContext, SecBufferDesc *pOutput, ULONG *pfContextAttr, TimeStamp *ptsExpiry); SECURITY_STATUS FreeContextBuffer(void *pvContextBuffer); SECURITY_STATUS ApplyControlToken(CtxtHandle *phContext, SecBufferDesc *pInput); SECURITY_STATUS DeleteSecurityContext(CtxtHandle *phContext); SECURITY_STATUS QueryContextAttributesW(CtxtHandle *phContext, ULONG ulAttribute, void *pBuffer); SECURITY_STATUS EncryptMessage(CtxtHandle *phContext, ULONG fQOP, SecBufferDesc *pMessage, ULONG MessageSeqNo); SECURITY_STATUS DecryptMessage(CtxtHandle *phContext, SecBufferDesc *pMessage, ULONG MessageSeqNo, ULONG *pfQOP); z secur32.dllzcannot load libraryzsecur32.dll could not be foundcCstS)N)ffiZ getwinerrorrrL/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/_secur32_cffi.pyr s) __future__rrrrsysZ_ffir_typesrerrorsr Zcffi__all__ZFFIr__version_info__Z set_unicodemaxsizeZcdefdlopenr OSErrorefindr rrrrs.         \ PK!C*__pycache__/_secur32_ctypes.cpython-38.pycnu[U af @sLddlmZmZmZmZddlZddlZddlmZmZm Z m Z m Z m Z ddl mZmZddlmZddlmZddlmZd d gZz ejZWn>ek rZz eed d kred W5dZ[XYnXejZe ZejdkrejZ nej!Z e Z"e Z#ej!Z$ej%Z&zGddde Z'e'Z(e'Z)Gddde Z*Gddde Z+Gddde Z,e e,Z-Gddde Z.Gddde Z/Gddde Z0e e&e e&ee e#e e"e e e(e e+g ej1_2e$ej1_3e e(gej4_2e$ej4_3e e(e e)e e&eeee e.ee e)e e.e ee e+g ej5_2e$ej5_3e gej6_2e$ej6_3e e)e e.gej7_2e$ej7_3e e)gej8_2e$ej8_3e e)ee gej9_2e$ej9_3e e)ee e.egej:_2e$ej:_3e e)e e.ee egej;_2e$ej;_3WnedS)")unicode_literalsdivisionabsolute_importprint_functionN)windllwintypesPOINTERc_void_pc_uint Structure)DWORDULONG)FFIEngineError)str_cls)LibraryNotFoundError get_errorsecur32z'The specified module could not be foundzsecur32.dll could not be foundlc@seZdZdefdefgZdS) SecHandleZdwLowerZdwUpperN)__name__ __module__ __qualname__ ULONG_PTR_fields_rrN/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/_secur32_ctypes.pyr(src@sleZdZdefdefdefdefdefdeefdefdeefd efd efd efd efd efdefgZdS) SCHANNEL_CREDZ dwVersionZcCredsZpaCredZ hRootStoreZcMappersZ aphMappersZcSupportedAlgsZpalgSupportedAlgsZgrbitEnabledProtocolsZdwMinimumCipherStrengthZdwMaximumCipherStrengthZdwSessionLifespanZdwFlagsZ dwCredFormatN) rrrr r HCERTSTORErALG_IDrrrrrr1s  rc@seZdZdefdefgZdS) TimeStampZ dwLowDateTimeZdwHighDateTimeN)rrrr rrrrrr Csr c@s(eZdZdefdefdeejfgZdS) SecBufferZcbBufferZ BufferTypeZpvBufferN)rrrr rctypesc_byterrrrrr!Is r!c@s"eZdZdefdefdefgZdS) SecBufferDescZ ulVersioncBuffersZpBuffersN)rrrr PSecBufferrrrrrr$Rsr$c@s.eZdZdefdefdefdefdefgZdS)SecPkgContext_StreamSizesZcbHeaderZ cbTrailerZcbMaximumMessager%Z cbBlockSizeN)rrrr rrrrrr'Ys r'c@s:eZdZdefdefdefdefdefdefdefgZdS) SecPkgContext_ConnectionInfoZ dwProtocolZaiCipherZdwCipherStrengthZaiHashZdwHashStrengthZaiExchZdwExchStrengthN)rrrr rrrrrrr(bsr(zError initializing ctypesr CredHandle CtxtHandlecCst}|t|fS)N)r"Z GetLastError FormatError)errorrrrrs)? __future__rrrrsysr"rrrr r r Zctypes.wintypesr r Z_ffir_typesrerrorsr__all__rOSErrorefindZHANDLErrmaxsizec_uint64rc_ulongZSEC_GET_KEY_FNZLUIDZSECURITY_STATUSZWCHARZ SEC_WCHARrr)r*rr r!r&r$r'r(ZAcquireCredentialsHandleWargtypesrestypeZFreeCredentialsHandleZInitializeSecurityContextWZFreeContextBufferZApplyControlTokenZDeleteSecurityContextZQueryContextAttributesWZEncryptMessageZDecryptMessageAttributeErrorsetattrrrrrrs                  PK!HiHi%__pycache__/asymmetric.cpython-38.pycnu[U af@s#ddlmZmZmZmZddlZddlZddlZddlZddl m Z m Z m Z mZmZmZmZmZmZmZmZmZmZmZmZddlmZmZmZmZmZm Z m!Z!m"Z"m#Z#ddl$m%Z%ddl&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6ddl7m8Z8dd l9m:Z:dd l;mZ>dd l?m@Z@mAZAmBZBmCZCdd lDmEZEmFZFmGZGmHZHmIZImJZJdd lKmLZLeMZNeNdeNdfZOe8ZPePdkrddlQmRZRmSZSmTZTmUZUmVZVddlWmXZYmZZ[m\Z\m]Z^m_Z`nddlambZbmcZcmTZTmdZdmeZedddddddddddddd d!d"d#d$d%d&d'gZfdd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;dd?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddÐdĐdŐdƐdǐdȐdɐdʐdːd̐d͐dΐdϐdАdѐdҐdӐdԐdՐd֐dאdؐdِdڐdېdܐdݐdސdߐdddddddddddddddddddddddddddddddddddddddddd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddÐdĐdŐdƐdǐdȐdɐdʐdːd̐d͐dΐdϐdАdѐdҐdӐdԐdՐd֐dאdؐdِdڐdېdܐdݐdސdߐdddddddddddddddddddddddddddddddddddddddddd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddÐdĐdŐdƐdǐdȐdɐdʐdːd̐d͐dΐdϐdАdѐdҐdӐdԐdՐd֐dאdؐdِdڐdېdܐdݐdސdߐdddddddddddddddddddddddddddddddddddddddddd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddÐdĐdŐdƐdǐdȐdɐdʐdːd̐d͐dΐdϐdАdѐdҐdӐdԐdՐd֐dאdؐdِdڐdېdܐdݐdސdߐdddddddddddddddddddddddddddddddddddddddddd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddÐdĐdŐdƐdǐdȐdɐdʐdːd̐d͐dΐdϐdАdѐdҐdӐdԐdՐd֐dאdؐdِdڐdېdܐdݐdސdߐdddddddddddddddddddddddddddddddddddddddddd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddÐdĐdŐdƐdǐdȐdɐdʐdːd̐d͐dΐdϐdАdѐdҐdӐdԐdՐd֐dאdؐdِdڐdېdܐdݐdސdߐdddddddddddddddddddddddddddddddddddddddddd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddÐdĐdŐdƐdǐdȐdɐdʐdːd̐d͐dΐdϐdАdѐdҐdӐdԐdՐd֐dאdؐdِdڐdېdܐdݐdސdߐdddddddddddddddddddddddddddddddddddddddddd d d d d ddddddddddddddddddd d!d"d#d$d%d&gZgGd'd(d(ZhGd)ddeheZiGd*ddeheZjGd+ddeheZ dvd,dZkd-d.Zldwd/d0Zmd1d2Zndxd3d4Zod5d6Zpd7d8Zqd9d:Zrd;d<Zsd=d>Ztd?d@ZudAdBZvdCdZwdDdEZxdFdGZydydIdJZzdKdLZ{dzdMdZ|dNdZ}d{dOdZ~d|dPdZdQd%ZdRd'ZdSdZdTdZ_d}dVdWZd~dXdYZddZd[Zd\d$Zd]d&Zd^dZd_dZ]dd`daZddbdcZddddeZddfdgZddhdiZddjdkZddldmZddndoZddpdqZdrd#Zdsd"Zdtd!Zdud ZdS()unicode_literalsdivisionabsolute_importprint_functionN) Certificate DHParameters DSAParams DSASignatureECDomainParameters ECPrivateKeyIntegerint_from_bytes int_to_bytesPrivateKeyAlgorithmPrivateKeyInfoPublicKeyAlgorithm PublicKeyInfo RSAPrivateKey RSAPublicKey) _CertificateBase _fingerprint _parse_pkcs12_PrivateKeyBase_PublicKeyBase_unwrap_private_key_infoparse_certificate parse_private parse_public)pretty_message)buffer_from_bytesbuffer_from_unicode byte_arraybytes_from_buffercastderefnativenewnull pointer_setsizeofstruct struct_bytesstruct_from_bufferunwrapwrite_to_buffer)backend) fill_width)AsymmetricKeyErrorIncompleteAsymmetricKeyErrorSignatureError) type_namestr_clsbyte_cls int_types)add_pkcs1v15_signature_paddingadd_pss_paddingraw_rsa_private_cryptraw_rsa_public_crypt!remove_pkcs1v15_signature_paddingverify_pss_padding)constant_compare winlegacy)advapi32 Advapi32Const handle_erroropen_context_handleclose_context_handle)ec_generate_pairec_compute_public_key_pointec_public_key_info ecdsa_sign ecdsa_verify)bcrypt BcryptConstrDopen_alg_handleclose_alg_handlerdsa_sign dsa_verifyrJrK generate_pairload_certificate load_pkcs12load_private_keyload_public_key parse_pkcs12 PrivateKey PublicKeyrsa_oaep_decryptrsa_oaep_encryptrsa_pkcs1v15_decryptrsa_pkcs1v15_encryptrsa_pkcs1v15_signrsa_pkcs1v15_verify rsa_pss_signrsa_pss_verify %)+/5;=CGIOSYaegkmqiii iiiii%i3i7i9i=iKiQi[i]iaigioiui{iiiiiiiiiiiiiiiiiiiiii i ii#i-i3i9i;iAiKiQiWiYi_ieiiikiwiiiiiiiiiiiiiiiiiiiiiiiii)i+i5i7i;i=iGiUiYi[i_imiqisiwiiiiiiiiiiiiiiiiiiii iiii%i'i-i?iCiEiIiOiUi]iciiiiiiiiiiiiiiiiiiiiii i iiiii'i)i/iQiWi]ieiwiiiiiiiiiiiiiiiiiiiiii iiii#i+i/i=iAiGiIiMiSiUi[ieiyiiiiiiiiiiiiiiiiiii iii'i7iEiKiOiQiUiWiaimisiyiiiiiiiiiiiiiiiiiiii!i#i'i)i3i?iAiQiSiYi]i_iiiqiiiiiiiiiiiiiiiii i i i# i% i+ i/ i5 iC iI iM iO iU iY i_ ik iq iw i i i i i i i i i i i i i i i i i i! i1 i9 i= iI iW ia ic ig io iu i{ i i i i i i i i i i i i i i i i i i i i i i i i i# i) i- i? iG iQ iW i] ie io i{ i i i i i i i i i i i i i i i i i i i% i/ i1 iA i[ i_ ia im is iw i i i i i i i i i i i i i i i i i i i i i i! i+ i- i= i? iO iU ii iy i i i i i i i i i i i i i i i i i i i i i iii!i'i/i5i;iKiWiYi]ikiqiui}iiiiiiiiiiiiiiii i ii%i)i1iCiGiMiOiSiYi[igikiiiiiiiiiiiiiiiiiiii!i%i+i9i=i?iQiiisiyi{iiiiiiiiiiiiiiiiii ii'i-i9iEiGiYi_iciiioiiiiiiiiiiiiiiiii iii#i)i+i1i7iAiGiSi_iqisiyi}iiiiiiiiiiiiii ii'i-i7iCiEiIiOiWi]igiiimi{iiiiiiiiiiiiiiiiiiii!i/i3i;iEiMiYikioiqiuiiiiiiiiiiiii iiii%i)i+i7i=iAiCiIi_ieigiki}iiiiiiiiiiiiiii iiiiii%i3i9i=iEiOiUiiimioiuiiiiiiiiiiiiiiiiiii ii#i'i3iAi]iciwi{iiiiiiiiiiiiiiiiiiii5i7i;iCiIiMiUigiqiwi}iiiiiiiiiiiiiiiiiiiiii1i3iEiIiQi[iyiiiiiiiiiiiiiiiiiii!i#i-i/i5i?iMiQiiiki{i}iiiiiiiiiiiiiiiiii#i%i/i1i7i;iAiGiOiUiYieikisiiiiiiiiiiiii iii'i+i-i3i=iEiKiOiUisiiiiiiiiiiiii ii!i#i5i9i?iAiKiSi]iciiiqiui{i}iiiiiiiiiiiiiiiiii iii%i+i/i=iIiMiOimiqiiiiiiiiiiiiiiiii iii9iIiKiQigiui{iiiiiiiiiiiiiiii i i i' i) i- i3 iG iM iQ i_ ic ie ii iw i} i i i i i i i i i i i i i i !i!i5!iA!iI!iO!iY!i[!i_!is!i}!i!i!i!i!i!i!i!i!i!i!i!i!i!i!i!i!i"i "i"i"i!"i%"i+"i1"i9"iK"iO"ic"ig"is"iu"i"i"i"i"i"i"i"i"i"i"i"i"i"i"i#i #i #i'#i)#i/#i3#i5#iE#iQ#iS#iY#ic#ik#i#i#i#i#i#i#i#i#i#i#i#i#i#i#i#i$i $i$i$i)$i=$iA$iC$iM$i_$ig$ik$iy$i}$i$i$i$i$i$i$i$i$i$i$i$i$i$i$i$i$i$i%i%i%i%i'%i1%i=%iC%iK%iO%is%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i&i &i&i&i'&i)&i5&i;&i?&iK&iS&iY&ie&ii&io&i{&i&i&i&i&i&i&i&i&i&i&i&i&i&i&i'i'i5'i7'iM'iS'iU'i_'ik'im'is'iw'i'i'i'i'i'i'i'i'i'i'i'i'i'i(i(i (i(i(i(i!(i1(i=(i?(iI(iQ(i[(i](ia(ig(iu(i(i(i(i(i(i(i(i(i(i(i(i(i)i)i)i!)i#)i?)iG)i])ie)ii)io)iu)i)i)i)i)i)i)i)i)i)i)i)i)i)i)i)i*i*i*i%*i/*iO*iU*i_*ie*ik*im*is*i*i*i*i*i*i*i*i*i*i*i*i*i*i*i+i'+i1+i3+i=+i?+iK+iO+iU+ii+im+io+i{+i+i+i+i+i+i+i+i+i+i+i+i+i+i ,i,i,i#,i/,i5,i9,iA,iW,iY,ii,iw,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i,i-i-i-i;-iC-iI-iM-ia-ie-iq-i-i-i-i-i-i-i-i-i-i-i.i.i.i .i.i.i%.i-.i3.i7.i9.i?.iW.i[.io.iy.i.i.i.i.i.i.i.i.i.i.i.i.i.i.i.i/i /i /i/i'/i)/iA/iE/iK/iM/iQ/iW/io/iu/i}/i/i/i/i/i/i/i/i/i/i/i/i/i/i/i0i 0i#0i)0i70i;0iU0iY0i[0ig0iq0iy0i}0i0i0i0i0i0i0i0i0i0i0i0i0i0i0i0i0i1i 1i1i!1i'1i-1i91iC1iE1iK1i]1ia1ig1im1is1i1i1i1i1i1i1i1i1i1i1i1i1i1i 2i2i2i2i)2i52iY2i]2ic2ik2io2iu2iw2i{2i2i2i2i2i2i2i2i2i2i2i2i2i2i2i2i3i%3i+3i/3i53iA3iG3i[3i_3ig3ik3is3iy3i3i3i3i3i3i3i3i3i3i3i3i3i4i4i4i4i4i74iE4iU4iW4ic4ii4im4i4i4i4i4i4i4i4i4i4i4i4i4i4i 5i5i5i-5i35i;5iA5iQ5ie5io5iq5iw5i{5i}5i5i5i5i5i5i5i5i5i5i5i5i5i5i5i6i6i6i#6i16i56i76i;6iM6iO6iS6iY6ia6ik6im6i6i6i6i6i6i6i6i6i6i6i6i7i7i7i7i?7iE7iI7iO7i]7ia7iu7i7i7i7i7i7i7i7i7i7i7i7i8i 8i!8i38i58iA8iG8iK8iS8iW8i_8ie8io8iq8i}8i8i8i8i8i8i8i8i8i8i8i8i8i8i9i9i#9i%9i)9i/9i=9iA9iM9i[9ik9iy9i}9i9i9i9i9i9i9i9i9i9i9i9i9i9i9i9i9i9i:i:i:i:i':i+:i1:iK:iQ:i[:ic:ig:im:iy:i:i:i:i:i:i:i:i:i:i:i:i;i;i;i!;i#;i-;i9;iE;iS;iY;i_;iq;i{;i;i;i;i;i;i;i;i;i;i;i;i;i;i;i;i;i;i<i <i<i<i<i)<i5<iC<iO<iS<i[<ie<ik<iq<i<i<i<i<i<i<i<i<i<i<i<i<i=i =i=i=i=i!=i-=i3=i7=i?=iC=io=is=iu=iy=i{=i=i=i=i=i=i=i=i=i=i=i=i=i>i >i>i>i>i#>i)>i/>i3>iA>iW>ic>ie>iw>i>i>i>i>i>i>i>i>i>i>i>i>i>i>i>i ?i ?i7?i;?i=?iA?iY?i_?ie?ig?iy?i}?i?i?i?i?i?i?i?i?i?i?i?i@i!@i%@i+@i1@i?@iC@iE@i]@ia@ig@im@i@i@i@i@i@i@i@i@i@i@i@i@i Ai AiAiAi!Ai3Ai5Ai;Ai?AiYAieAikAiwAi{AiAiAiAiAiAiAiAiAiAiAiBiBiBiBi#Bi)Bi/BiCBiSBiUBi[BiaBisBi}BiBiBiBiBiBiBiBiBiBiBiBiBiBiCiCiCi%Ci'Ci3Ci7Ci9CiOCiWCiiCiCiCiCiCiCiCiCiCiCiCiCiCiCiCiCiCi Di DiDi#Di)Di;Di?DiEDiKDiQDiSDiYDieDioDiDiDiDiDiDiDiDiDiDiDiDiDiDiEiEiEi+Ei1EiAEiIEiSEiUEiaEiwEi}EiEiEiEiEiEiEiEc@s,eZdZdZdZdZdZddZddZdS)_WinKeyNcCs&||_||_tdkrt|_nt|_dS)z :param key_handle: A CNG BCRYPT_KEY_HANDLE value (Vista and newer) or an HCRYPTKEY (XP and 2003) from loading/importing the key :param asn1: An asn1crypto object for the concrete type rAN) key_handleasn1_backendrB_librLselfrrrI/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/asymmetric.py__init__s z_WinKey.__init__cCsb|jr:tdkr|j|j}n|j|j}t|d|_|jrXtdkrXt|jd|_d|_dS)NrA)rrrCryptDestroyKeyBCryptDestroyKeyrDcontext_handlerF)rresrrr__del__s z_WinKey.__del__) __name__ __module__ __qualname__rr ex_key_handlerrrrrrrrvs rc@s4eZdZdZdZddZeddZeddZdS) rXzM Container for the OS crypto library representation of a private key NcCst|||dS)z :param key_handle: A CNG BCRYPT_KEY_HANDLE value (Vista and newer) or an HCRYPTKEY (XP and 2003) from loading/importing the key :param asn1: An asn1crypto.keys.PrivateKeyInfo object Nrrrrrrrs zPrivateKey.__init__cCstdkr|jdkr2t|j}tdt||j|_q|jdkr|jdd}tt d|dt t |dj |jd j j |d j d }t||_q|jd j }tt d d it|d|ddd }t||_n t|j|j|j\}}t||_|jS)z\ :return: A PublicKey object corresponding to this private key. rAecNdsaprivate_key_algorithm parameters algorithmrg private_keypr public_keyrrsamoduluspublic_exponentrr)rr(_pure_python_ec_compute_public_key_pointrrYrIcurve _public_keyrrr powr&parsedrVr_bcrypt_key_handle_to_asn1bit_sizer)rZ pub_pointparamsZpub_asn1r_rrrrsB        zPrivateKey.public_keycCs|jdkrt|jt|_|jS)aY Creates a fingerprint that can be compared with a public key to see if the two form a pair. This fingerprint is not compatible with fingerprints generated by any other software. :return: A byte string that is a sha256 hash of selected components (based on the key type) N)rrrUrrrr fingerprints zPrivateKey.fingerprint) rrr__doc__rrpropertyrrrrrrrXs  0c@seZdZdZddZdS)rYzL Container for the OS crypto library representation of a public key cCst|||dS)z :param key_handle: A CNG BCRYPT_KEY_HANDLE value (Vista and newer) or an HCRYPTKEY (XP and 2003) from loading/importing the key :param asn1: An asn1crypto.keys.PublicKeyInfo object Nrrrrrrs zPublicKey.__init__N)rrrrrrrrrrYsc@s8eZdZdZdZdZddZeddZeddZ dS) rzM Container for the OS crypto library representation of a certificate NcCst|||dS)z :param key_handle: A CNG BCRYPT_KEY_HANDLE value (Vista and newer) or an HCRYPTKEY (XP and 2003) from loading/importing the certificate :param asn1: An asn1crypto.x509.Certificate object Nrrrrrrs zCertificate.__init__cCs$|jdkrt|jdd|_|jS)zh :return: The PublicKey object for the public key this certificate contains Ntbs_certificatesubject_public_key_info)rrVrrrrrrs zCertificate.public_keycCs|jdkrd|_|jjtddgkr|jdj}|jdj}|dkrJt}n8|dkrXt}n*|dkrft}n|d krtt }nt t d |z*|||jd j |jd  |d |_Wntk rYnX|jS)zT :return: A boolean - if the certificate is self-signed NFyesmaybeZsignature_algorithmZrsassa_pkcs1v15 rsassa_pssrZecdsaz Unable to verify the signature of the certificate since it uses the unsupported algorithm %s Zsignature_valuerT) _self_signedr self_signedsetsignature_algo hash_algor_rarQrKOSErrorrr&dumpr4)rrrZ verify_funcrrrr*s8      zCertificate.self_signed) rrrrrrrrrrrrrrr s  cCs(|tdddgkr$ttdt||dkrT|tddddgkrttd t|n|dkrtd ksltd kr|dkrttd t|q|tdddgkrttd t|n,|dkr|tdddgkrttdt|td kr|dkrt|\}}td|td|fSt ||St |||SdS)aB Generates a public/private key pair :param algorithm: The key algorithm - "rsa", "dsa" or "ec" :param bit_size: An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024, 2048, 3072 or 4096. For "dsa" the value may be 1024, plus 2048 or 3072 if on Windows 8 or newer. :param curve: A unicode string - used for "ec" keys. Valid values include "secp256r1", "secp384r1" and "secp521r1". :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A 2-element tuple of (PublicKey, PrivateKey). The contents of each key may be saved by calling .asn1.dump(). rrrzM algorithm must be one of "rsa", "dsa", "ec", not %s i zX bit_size must be one of 1024, 2048, 3072, 4096, not %s rrAzG bit_size must be 1024, not %s zZ bit_size must be one of 1024, 2048, 3072, not %s secp256r1 secp384r1 secp521r1zd curve must be one of "secp256r1", "secp384r1", "secp521r1", not %s N) r ValueErrorrrepr_win_version_infor_pure_python_ec_generate_pairrYrX_advapi32_generate_pair_bcrypt_generate_pair)rrrZpub_infoZ priv_inforrrrRWsF    cCs>|dkrd}nd}ttd}t|ttjdt|}t|t|}t|}t|ttjd||}t|t t||}t |} t t| } t ||| d} |dkrt || | \} } n~ttd}t|ttjdt|}t|t|}t|}t|ttjd||}t|t ||| d}t||| \} } | | fS)ao Accepts an key handle and exports it to ASN.1 :param algorithm: The key algorithm - "rsa" or "dsa" :param bit_size: An integer - only used when algorithm is "rsa" :param key_handle: The handle to export :return: A 2-element tuple of asn1crypto.keys.PrivateKeyInfo and asn1crypto.keys.PublicKeyInfo r RSABLOBHEADER DSSBLOBHEADERDWORD *rN)r'rBZCryptExportKeyr(rCPRIVATEKEYBLOBrDr%r r-r.r*r# _advapi32_interpret_rsa_key_blob PUBLICKEYBLOB _advapi32_interpret_dsa_key_blob)rrr struct_typeout_lenr buffer_lengthbuffer_blob_struct_pointer blob_struct struct_size private_blob public_info private_infopublic_out_lenpublic_buffer_length public_buffer public_blobrrr_advapi32_key_handle_to_asn1sl    rc Cs|dkrtj}tj}n tj}tj}d}d}zht|dd}t td}|d>tj B}t ||||}t |t |}t|||\} } t| t| fWS|rt||rt|XdS)a Generates a public/private key pair using CryptoAPI :param algorithm: The key algorithm - "rsa" or "dsa" :param bit_size: An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024, 2048, 3072 or 4096. For "dsa" the value may be 1024. :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A 2-element tuple of (PublicKey, PrivateKey). The contents of each key may be saved by calling .asn1.dump(). rNFZ verify_only HCRYPTKEY *)rCMS_ENH_RSA_AES_PROV CALG_RSA_SIGNMS_ENH_DSS_DH_PROV CALG_DSS_SIGNrFrBrrEr'ZCRYPT_EXPORTABLEZ CryptGenKeyrDr.rrVrU) rrprovider algorithm_idrrkey_handle_pointerflagsrrrrrrrs(  rc Cs |dkrd}tj}tj}n8|dkrB|dkr0d}nd}tj}tj}nd}tj}tj}ttd}t |t |t d |d }t |t |}t |} t |t || ||d }t |tt|| } t| } tt| } t| || d } |dkrtd | | }n@|dkr(|dkrtd d | | }ntd d | | }n td | | }ttd}t |t |t d |d }t |t |}t |}t |t ||||d }t |tt||}t|}tt|} t||| d }|dkrtd||}n@|dkr |dkrtdd ||}ntdd ||}n td||}||fS)au Accepts an key handle and exports it to ASN.1 :param algorithm: The key algorithm - "rsa", "dsa" or "ec" :param bit_size: An integer - only used when algorithm is "dsa" :param key_handle: The handle to export :return: A 2-element tuple of asn1crypto.keys.PrivateKeyInfo and asn1crypto.keys.PublicKeyInfo rBCRYPT_RSAKEY_BLOBrrBCRYPT_DSA_KEY_BLOB_V2BCRYPT_DSA_KEY_BLOBBCRYPT_ECCKEY_BLOBULONG *rNprivaterr@public)rMBCRYPT_RSAFULLPRIVATE_BLOBBCRYPT_RSAPUBLIC_BLOBBCRYPT_DSA_PRIVATE_BLOBBCRYPT_DSA_PUBLIC_BLOBBCRYPT_ECCPRIVATE_BLOBBCRYPT_ECCPUBLIC_BLOBr'rLZBCryptExportKeyr(rDr%r r-r.r*r#_bcrypt_interpret_rsa_key_blob_bcrypt_interpret_dsa_key_blob_bcrypt_interpret_ec_key_blob)rrrrZprivate_blob_typeZpublic_blob_typeZprivate_out_lenrZprivate_buffer_lengthZprivate_bufferZprivate_blob_struct_pointerZprivate_blob_structrrrrrrZpublic_blob_struct_pointerZpublic_blob_structrrrrrr3s               rc Cs|dkrtj}n6|dkr tj}n&tjtjtjd|}dddd|}d}zZt|}t td}t |||d }t |t |}t |d }t |t|||\}} W5|rt|Xt|t| fS) aL Generates a public/private key pair using CNG :param algorithm: The key algorithm - "rsa", "dsa" or "ec" :param bit_size: An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024, 2048, 3072 or 4096. For "dsa" the value may be 1024, plus 2048 or 3072 if on Windows 8 or newer. :param curve: A unicode string - used for "ec" keys. Valid values include "secp256r1", "secp384r1" and "secp521r1". :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A 2-element tuple of (PublicKey, PrivateKey). The contents of each key may be saved by calling .asn1.dump(). rrrrrirNBCRYPT_KEY_HANDLE *r)rMBCRYPT_RSA_ALGORITHMBCRYPT_DSA_ALGORITHMBCRYPT_ECDSA_P256_ALGORITHMBCRYPT_ECDSA_P384_ALGORITHMBCRYPT_ECDSA_P521_ALGORITHMrLrrNr'ZBCryptGenerateKeyPairrDr.ZBCryptFinalizeKeyPairrrVrU) rrr alg_constantr alg_handlerrrrrrrrs:   rc Cs|t|tsttdt||dkr,td|dkrr?r@rArBr=public_key_inforsa_private_keyprivate_key_inforrrrjs\  rc Csd}|d}|}||}||}|}t|d|ddd} t|||ddd} t|||ddd} t||||ddd} t||||ddd} ttdt| | | ddt| d }tdtdt| | | ddt| d }||fS) a Takes a CryptoAPI DSS private key blob and converts it into the ASN.1 structures for the public and private keys :param bit_size: The integer bit size of the key :param public_blob: A byte string of the binary data after the public key header :param private_blob: A byte string of the binary data after the private key header :return: A 2-element tuple of (asn1crypto.keys.PublicKeyInfo, asn1crypto.keys.PrivateKeyInfo) rrNr9rrr-rrrrC)rrrr r rr)rrrrGrHq_offsetg_offsetZx_offsetZy_offsetrr-rr8yrOrQrrrrsF  rc Cshtt|j}tt|j}|}t|d|}t||||}|dkrhttddit||ddS|dkrRtt|j}tt|j } ||} | |} | | } | | } | | }||}t|| | }t|| | }t|| | }t|| |}t|||}t||||}t d||||||||d }t dt ddi|d St td t|d S) a Take a CNG BCRYPT_RSAFULLPRIVATE_BLOB and converts it into an ASN.1 structure :param key_type: A unicode string of "private" or "public" :param blob_struct: An instance of BCRYPT_RSAKEY_BLOB :param blob: A byte string of the binary data contained after the struct :return: An asn1crypto.keys.PrivateKeyInfo or asn1crypto.keys.PublicKeyInfo object, based on the key_type param rr rrrrrr:r;rCM key_type must be one of "public", "private", not %s N)r&int cbPublicExp cbModulusrrrrcbPrime1cbPrime2rrrrrr)key_typerrFZpublic_exponent_byte_lengthZmodulus_byte_lengthZmodulus_offsetrrZprime1_byte_lengthZprime2_byte_lengthrIrJrKrLrMrNr>r?r@rArBr=rPrrrrsl       rc Cstt|j}|dkrZttt|j}|}||}||}t|d|} t|||} n|dkrtt|j} tt|j} | } | | }||}||}||}t|| |}t|||} t|||} ntdt ||dkr"t|||}t t dt | || ddt |d S|d krjt||||}tdtdt | || ddt |d Sttd t |d S)an Take a CNG BCRYPT_DSA_KEY_BLOB or BCRYPT_DSA_KEY_BLOB_V2 and converts it into an ASN.1 structure :param key_type: A unicode string of "private" or "public" :param version: An integer - 1 or 2, indicating the blob is BCRYPT_DSA_KEY_BLOB or BCRYPT_DSA_KEY_BLOB_V2 :param blob_struct: An instance of BCRYPT_DSA_KEY_BLOB or BCRYPT_DSA_KEY_BLOB_V2 :param blob: A byte string of the binary data contained after the struct :return: An asn1crypto.keys.PrivateKeyInfo or asn1crypto.keys.PublicKeyInfo object, based on the key_type param r@rrzversion must be 1 or 2, not %sr rrSrrrrCrWN)r&rXcbKeyrr7r- cbSeedLength cbGroupSizerrrrr r rrr)r]r<rrFkey_byte_lengthr-rUZ public_offsetZprivate_offsetrrZseed_byte_lengthZgroup_byte_lengthrTp_offsetr rrrrrCsf     rc Cstt|j}tt|j}tjdtjdtjdtjdtj dtj di|}d|d|d}|dkrt t dt d |d d |d S|d krt||d|d}tdtdt d |d d td||ddSttdt|dS)a Take a CNG BCRYPT_ECCKEY_BLOB and converts it into an ASN.1 structure :param key_type: A unicode string of "private" or "public" :param blob_struct: An instance of BCRYPT_ECCKEY_BLOB :param blob: A byte string of the binary data contained after the struct :return: An asn1crypto.keys.PrivateKeyInfo or asn1crypto.keys.PublicKeyInfo object, based on the key_type param rrrrrr rnamed)namevaluerrrrbZ ecPrivkeyVer1)r<rrrCrWN)r&rXdwMagicr^rMBCRYPT_ECDSA_PRIVATE_P256_MAGICBCRYPT_ECDSA_PRIVATE_P384_MAGICBCRYPT_ECDSA_PRIVATE_P521_MAGICBCRYPT_ECDSA_PUBLIC_P256_MAGICBCRYPT_ECDSA_PUBLIC_P384_MAGICBCRYPT_ECDSA_PUBLIC_P521_MAGICrrr rrrr rrr)r]rrFmagicrarr rrrrrsd    rc Csnt|tr|}nTt|tr$t|}n@t|trRt|d}t|}W5QRXnttdt |t |t S)a Loads an x509 certificate into a Certificate object :param source: A byte string of file contents or a unicode string filename :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A Certificate object r*z source must be a byte string, unicode string or asn1crypto.x509.Certificate object, not %s ) r"Asn1Certificater7rr6openreadr#rr5 _load_keyr)sourceZ certificatefrrrrSs     cCs|}t|tr|dd}|j}d}|dkrj|j\}}|dkrJttd|tddd gkrttd nt|d kr|jdkrttd nT|j d krt dkst dkrttd|j |j n |j dkr|jdkrttdt dkr|dkr|d|St |||St||||S)a Loads a certificate, public key or private key into a Certificate, PublicKey or PrivateKey object :param key_object: An asn1crypto.x509.Certificate, asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo object :param container: The class of the object to hold the key_handle :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type oscrypto.errors.AsymmetricKeyError - when the key is incompatible with the OS crypto library OSError - when an error is returned by the OS crypto library :return: A PrivateKey, PublicKey or Certificate object, based on container rrNrrdzR Windows only supports EC keys using named curves rrrz Windows only supports EC keys using the named curves secp256r1, secp384r1 and secp521r1 rz The DSA key does not contain the necessary p, q and g parameters and can not be used rrrAz Windows XP, 2003, Vista, 7 and Server 2008 only support DSA keys based on SHA1 (1024 bits or less) - this key is based on %s and is %s bits rsha1a Windows only supports 2048 bit DSA keys based on SHA2 - this key is 2048 bits and based on SHA1, a non-standard combination that is usually generated by old versions of OpenSSL )r"rorrr2rrrr3rrrupper_advapi32_load_key_bcrypt_load_key) key_object containerkey_infoalgo curve_nameZ curve_typerrrrr sF        rrcCsLt|trdnd}|j}|dkr$d}|dks4|dkrr?r@rArBr=Z DSSPUBKEYrrrrRrr-rZDSSSEEDl)rCrrrZ CALG_RSA_KEYXrr+rBr.ZbTypeZCUR_BLOB_VERSIONZbVersionreservedZaiKeyAlgZpublickeystrucrZbitlenrZRSA1rnr&rErZRSA2rDZDSS1ZDSS2Z dsspubkeycounterr,)r{r]r|r~ blob_typerrZblob_header_pointerZ blob_headerrrrrGrHZpubkey_pointerZpubkeyZparsed_key_infoZ blob_datarZkey_dataZdssseed_pointerZdssseedrrrrs|       "  """"""   "     rc+ Csfd}d}t|trdnd}|j}|dkr,d}z"|dkrB|jdn|}tjtjtjtj tj d|} t | }|dkr|dkrtj } tj } |d j} d } d }nztj} tj} |d j} t| d j}t| d j}t| dj}t| dj}t| dj}t| dj}t|} t|}t| dj}t| dj}ttd}t|}| |_|j|_t||_t||_| |_||_t|||}|dkr |||7}|t|| 7}|t||7}|t|| 7}|t|t|7}n2|dkr|dkrtj } |d jj}|dd}n0tj!} t"|d j}t|d jj}|dd}t|}t|dj}t|dj}t|dj} |jdkrt| }!nd}!t#t|t|t|}"t||"}t||"}t||"}t| |!} d}#d|!}$|jdkrx|dkrtj$} ntj%} ttd }t|}| |_&|"|_'tj(|_)tj*|_+|!|_,|!|_-t.|#|_/t|}||$| |||7}|dkr|t||!7}n|dkrtj0} ntj1} ttd!}t|}| |_&|"|_'t.|#|_/t.|$|_2t.| |_3t||||}|dkr |t||!7}n|dkr |dkr(tj4} |d 5\}%}&nDtj6} |d jd }|rP|5\}%}&nd }%d }&t|d jd j}ttd"}t|}tj7tj8tj9tj:tj;tj|t?| |)|t|tj@}*tA|*t|)}|||WS|r`t|XdS))a Loads a certificate, public key or private key into a Certificate, PublicKey or PrivateKey object via CNG :param key_object: An asn1crypto.x509.Certificate, asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo object :param key_info: An asn1crypto.keys.PublicKeyInfo or asn1crypto.keys.PrivateKeyInfo object :param container: The class of the object to hold the key_handle :param curve_name: None or a unicode string of the curve name for an EC key :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type oscrypto.errors.AsymmetricKeyError - when the key is incompatible with the OS crypto library OSError - when an error is returned by the OS crypto library :return: A PrivateKey, PublicKey or Certificate object, based on container Nr rrrrr@)rrrrrrrrr>r?r@rArBr=rrrrrrrrrr-rrRsrrr))r r)r r)r r)rr)rr)rr 0Brr)Br"rrrOrrMrrrrrrNr ZBCRYPT_RSAPUBLIC_MAGICrr ZBCRYPT_RSAFULLPRIVATE_MAGICrr&rr+rLr.ZMagicrZ BitLengthrYrZr[r\r,r1r r rmaxZBCRYPT_DSA_PUBLIC_MAGIC_V2ZBCRYPT_DSA_PRIVATE_MAGIC_V2rgr^ZDSA_HASH_ALGORITHM_SHA256Z hashAlgorithmZ DSA_FIPS186_3ZstandardVersionr_r`r"ZCountZBCRYPT_DSA_PUBLIC_MAGICZBCRYPT_DSA_PRIVATE_MAGICZSeedr-rZ to_coordsrrkrlrmrhrirjr'ZBCryptImportKeyPairr(ZBCRYPT_NO_KEY_VALIDATIONrD)+ryr{rzr}rrr]r|Z alg_selectorrrrnZ parsed_keyZ prime1_sizeZ prime2_sizer>r?r@rArBr=rrrrrFrrZ private_bytesZ public_bytesrrr-Zq_lenZ key_widthcountseedr8rVZx_bytesZy_bytesrrrrrrxs:                                      rxc Cst|tr|}n|dk rHt|tr,|d}t|tsHttdt|t|trrt|d}| }W5QRXnt|tsttdt|t ||}t |t S)a Loads a private key into a PrivateKey object :param source: A byte string of file contents, a unicode string filename or an asn1crypto.keys.PrivateKeyInfo object :param password: A byte or unicode string to decrypt the private key file. Unicode strings will be encoded using UTF-8. Not used is the source is a PrivateKeyInfo object. :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type oscrypto.errors.AsymmetricKeyError - when the private key is incompatible with the OS crypto library OSError - when an error is returned by the OS crypto library :return: A PrivateKey object Nutf-8zP password must be a byte string, not %s r*z source must be a byte string, unicode string or asn1crypto.keys.PrivateKeyInfo object, not %s ) r"rr6encoder7r#rr5rprqrrrrX)rspasswordZprivate_objectrtrrrrUs(        c Csnt|tr|}nTt|tr$t|}n@t|trRt|d}t|}W5QRXnttdt |t |t S)a3 Loads a public key into a PublicKey object :param source: A byte string of file contents, a unicode string filename or an asn1crypto.keys.PublicKeyInfo object :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type oscrypto.errors.AsymmetricKeyError - when the public key is incompatible with the OS crypto library OSError - when an error is returned by the OS crypto library :return: A PublicKey object r*z source must be a byte string, unicode string or asn1crypto.keys.PublicKeyInfo object, not %s ) r"rr7rr6rprqr#rr5rrrY)rsrrtrrrrV9s     cCs t||tS)a Parses a PKCS#12 ANS.1 DER-encoded structure and extracts certs and keys :param data: A byte string of a DER-encoded PKCS#12 file :param password: A byte string of the password to any encrypted data :raises: ValueError - when any of the parameters are of the wrong type or value OSError - when an error is returned by one of the OS decryption functions :return: A three-element tuple of: 1. An asn1crypto.keys.PrivateKeyInfo object 2. An asn1crypto.x509.Certificate object 3. A list of zero or more asn1crypto.x509.Certificate objects that are "extra" certificates, possibly intermediates from the cert chain )rrU)datarrrrrWasc Cs|dk r8t|tr|d}t|ts8ttdt|t|trbt|d}|}W5QRXnt|ts~ttdt|t ||\}}}d}d}|rt |t }|rt |j t }dd|D}|||fS)a Loads a .p12 or .pfx file into a PrivateKey object and one or more Certificates objects :param source: A byte string of file contents or a unicode string filename :param password: A byte or unicode string to decrypt the PKCS12 file. Unicode strings will be encoded using UTF-8. :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type oscrypto.errors.AsymmetricKeyError - when a contained key is incompatible with the OS crypto library OSError - when an error is returned by the OS crypto library :return: A three-element tuple containing (PrivateKey, Certificate, [Certificate, ...]) NrzH password must be a byte string, not %s r*zR source must be a byte string or a unicode string, not %s cSsg|]}t|jtqSr)rrrr).0inforrr szload_pkcs12..)r"r6rr7r#rr5rprqrWrrrXrr) rsrrtr{Z cert_infoZextra_certs_infokeycertZ extra_certsrrrrTzs2        cCs |jdkrtdt||||S)a Verifies an RSASSA-PKCS-v1.5 signature. When the hash_algorithm is "raw", the operation is identical to RSA public key decryption. That is: the data is not hashed and no ASN.1 structure with an algorithm identifier of the hash algorithm is placed in the encrypted byte string. :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte string of the signature to verify :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384", "sha512" or "raw" :raises: oscrypto.errors.SignatureError - when the signature is determined to be invalid ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library r*The key specified is not an RSA public keyrr_verifycertificate_or_public_key signaturerhash_algorithmrrrr_s cCs0|j}|dkr|dkrtdt||||ddS)a Verifies an RSASSA-PSS signature. For the PSS padding the mask gen algorithm will be mgf1 using the same hash algorithm as the signature. The salt length with be the length of the hash algorithm, and the trailer field with be the standard 0xBC byte. :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte string of the signature to verify :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384" or "sha512" :raises: oscrypto.errors.SignatureError - when the signature is determined to be invalid ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library rrrTrsa_pss_paddingr)rrrrcp_algrrrrascCs |jdkrtdt||||S)a Verifies a DSA signature :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte string of the signature to verify :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384" or "sha512" :raises: oscrypto.errors.SignatureError - when the signature is determined to be invalid ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library rz)The key specified is not a DSA public keyrrrrrrQs cCs |jdkrtdt||||S)a Verifies an ECDSA signature :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte string of the signature to verify :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384" or "sha512" :raises: oscrypto.errors.SignatureError - when the signature is determined to be invalid ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library rz)The key specified is not an EC public keyrrrrrrK s Fc Cs\t|ttfs ttdt|t|tsr4r=r(r?rrBCryptDestroyHashrCCALG_MD5 CALG_SHA1 CALG_SHA_256 CALG_SHA_384 CALG_SHA_512r'CryptCreateHashrr(rDr. CryptHashDatarr loadto_p1363 OverflowErrorr#ZCryptVerifySignatureWr)rrrrrr| algo_is_rsa hash_lengthZdecrypted_signatureZkey_sizeZpadded_plaintext plaintext hash_handlealg_idhash_handle_pointerrhalf_lenZreversed_signaturerrrr s          rc Csz|dkr|}n0tjtjtjtjtjd|}tt||}t }d}|j } | dkp\| dk} | r|rtj }t t d} t| } t|} tt d| | _t|| _n@tj}t t d} t| } |dkrt | _nt|} tt d| | _tt d | }n8zt|}Wn$tttfk r$td YnXt |j||t||t||}|tjk}|p^|tjk}|rntd t |d S) a0 Verifies an RSA, DSA or ECDSA signature via CNG :param certificate_or_public_key: A Certificate or PublicKey instance to verify the signature with :param signature: A byte string of the signature to verify :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384", "sha512" or "raw" :param rsa_pss_padding: If PSS padding should be used for RSA keys :raises: oscrypto.errors.SignatureError - when the signature is determined to be invalid ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library rrrrrBCRYPT_PSS_PADDING_INFO wchar_t *BCRYPT_PKCS1_PADDING_INFOvoid *rN)!rMBCRYPT_MD5_ALGORITHMBCRYPT_SHA1_ALGORITHMBCRYPT_SHA256_ALGORITHMBCRYPT_SHA384_ALGORITHMBCRYPT_SHA512_ALGORITHMgetattrhashlibdigestr(rBCRYPT_PAD_PSSr+rLr.r!r$pszAlgIdrcbSaltBCRYPT_PAD_PKCS1r rrrrr#r4ZBCryptVerifySignaturerZSTATUS_INVALID_SIGNATUREZSTATUS_INVALID_PARAMETERrD)rrrrrr hash_constant padding_inforrrpadding_info_struct_pointerpadding_info_struct hash_bufferrZfailurerrrr sb     rcCs|jdkrtdt|||S)aL Generates an RSASSA-PKCS-v1.5 signature. When the hash_algorithm is "raw", the operation is identical to RSA private key encryption. That is: the data is not hashed and no ASN.1 structure with an algorithm identifier of the hash algorithm is placed in the encrypted byte string. :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384", "sha512" or "raw" :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature r+The key specified is not an RSA private keyrr_signrrrrrrr^^ s cCs.|j}|dkr|dkrtdt|||ddS)a$ Generates an RSASSA-PSS signature. For the PSS padding the mask gen algorithm will be mgf1 using the same hash algorithm as the signature. The salt length with be the length of the hash algorithm, and the trailer field with be the standard 0xBC byte. :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384" or "sha512" :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature rrrTrr)rrrpkey_algrrrr` scCs|jdkrtdt|||S)a7 Generates a DSA signature :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384" or "sha512" :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature rz*The key specified is not a DSA private keyrrrrrrP s cCs|jdkrtdt|||S)a: Generates an ECDSA signature :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384" or "sha512" :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature rz*The key specified is not an EC private keyrrrrrrJ s cCs8t|tsttdt|t|ts8ttdt||j}|dkpL|dk}tddddd g}|jdkr||s||td gO}||krd }|r|s|d 7}ttd |t ||s|dk rttd| |d krt ||j dkrttd|j t |t dkr*|jdkrt|||St||||St||||S)a Generates an RSA, DSA or ECDSA signature :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384", "sha512" or "raw" :param rsa_pss_padding: If PSS padding should be used for RSA keys :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature zO private_key must be an instance of PrivateKey, not %s rrrrrurrrrrrrFrrez data must be 11 bytes shorter than the key size when hash_algorithm is "raw" - key size is %s bytes, but data is %s bytes long rAr)r"rXr#rr5r7rrrrrvrr(r_pure_python_ecdsa_sign_advapi32_sign _bcrypt_sign)rrrrr pkey_is_rsarrrrrr sR      rc Cs|j}|dkp|dk}|r8|dkr8t|j|}t||S|rr|rrdddddd |d }t|||j|}t||S|jd kr|d krttd d}z&t j t j t jt jt jd|} tt d} t |j| td | } t| t| }t ||t|d } t| tt d} t |t jtd t| } t| t| } t| }t |t jtd || } t| t|t| }|ddd}|d krt|d}||d|d|}t| }|WS|rt |XdS)a Generates an RSA, DSA or ECDSA signature via CryptoAPI :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384", "sha512" or "raw" :param rsa_pss_padding: If PSS padding should be used for RSA keys :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature rrrrRrrrrrrrrzO Windows does not support md5 signatures with DSA keys Nrrrr9r)!rr9r(r;rr:rrrrBrrCrrrrrr'rrr(rDr.rrZCryptSignHashWZ AT_SIGNATUREr%r r#r from_p1363r)rrrrr|rZ padded_datarrrrrrrrrrrrrr0 s        rc Cs|dkr|}n0tjtjtjtjtjd|}tt||}t }d}|j }|dkp\|dk} | r|rdddd d d|} tj }t t d } t| } t|} tt d | | _| | _n@tj}t t d } t| } |dkrt | _nt|} tt d | | _tt d| }|dkr0|jdkr0|tddgkr0ttdtt d}t |j||t|t d||}t|t|}t|}| rtt d| }t |j||t|||||}t|t|t|}| st !|"}|S)a Generates an RSA, DSA or ECDSA signature via CNG :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha256", "sha384", "sha512" or "raw" :param rsa_pss_padding: If PSS padding should be used for RSA keys :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the signature rrrrrrrRrrrrrrrrrrruz~ Windows does not support sha1 signatures with DSA keys based on sha224, sha256 or sha512 r)#rMrrrrrrrrr(rrr+rLr.r!r$rrrrrrrr'ZBCryptSignHashrrrDr%r r#r rr)rrrrrrrrrrrrrrrr buffer_lenr)rrrrr s    (    rcCsxt|ttfs ttdt|t|tsutilr?getwindowsversionZ_gwvrrZ _advapi32rBrCrDrErFZ_ecdsarGrrHrrIrJrrKrZ_cngrLrMrNrO__all__r&rrXrYrRrrrrr.r'rrrrrrSrrrwrrxrUrVrWrTr_rarQrrrr^r`rPrrrrrrrrrr]r\r[rZrrrrsD, H     ,WLP X4 e@ d . G = U [ G & P Wg i8 (= " "  bnY ! !  Xzy49H3+H   PK!ΘYY$__pycache__/symmetric.cpython-38.pycnu[U afx @sddlmZmZmZmZddlmZddlmZm Z m Z m Z m Z m Z mZmZmZmZddlmZddlmZddlmZmZeZed krdd lmZmZmZmZmZndd l m!Z!m"Z"mZm#Z#m$Z$d d ddddddddddg Z%dd Z&dd Z'ddZ(ddZ)ddZ*ddZ+ddZ,ddZ-d dZ.d!dZ/d"dZ0d#dZ1d$d%Z2d&d'Z3d(d)Z4d*d+Z5d,d-Z6d.d/Z7d0d1Z8d2d3Z9d4S)5)unicode_literalsdivisionabsolute_importprint_function)pretty_message) buffer_from_bytesbytes_from_bufferderefnewnull pointer_setstruct struct_bytesunwrapwrite_to_buffer) rand_bytes)backend) type_namebyte_cls winlegacy)advapi32 Advapi32Const handle_erroropen_context_handleclose_context_handle)bcrypt BcryptConstropen_alg_handleclose_alg_handleaes_cbc_no_padding_decryptaes_cbc_no_padding_encryptaes_cbc_pkcs7_decryptaes_cbc_pkcs7_encryptdes_cbc_pkcs5_decryptdes_cbc_pkcs5_encryptrc2_cbc_pkcs5_decryptrc2_cbc_pkcs5_encrypt rc4_decrypt rc4_encrypttripledes_cbc_pkcs5_decrypttripledes_cbc_pkcs5_encryptcCst|dkrttdt||s,td}nt|dkrJttdt|t|ddkrlttdt||td|||dfS) a Encrypts plaintext using AES in CBC mode with a 128, 192 or 256 bit key and no padding. This means the ciphertext must be an exact multiple of 16 bytes long. :param key: The encryption key - a byte string either 16, 24 or 32 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - either a byte string 16-bytes long or None to generate an IV :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext)  o key must be either 16, 24 or 32 bytes (128, 192 or 256 bits) long - is %s r.: iv must be 16 bytes long - is %s rzJ data must be a multiple of 16 bytes long - is %s aesFlen ValueErrorrr_encryptkeydataivr<H/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/symmetric.pyr"-s$   cCsLt|dkrttdt|t|dkrr8r<r<r=r#s  cCs:t|dkst|dkr*ttdt|td||ddS)a Encrypts plaintext using RC4 with a 40-128 bit key :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext r.Q key must be 5 to 16 bytes (40 to 128 bits) long - is %s rc4N)r5r6rr7r9r:r<r<r=r*s cCs:t|dkst|dkr*ttdt|td||ddS)a Decrypts RC4 ciphertext using a 40-128 bit key :param key: The encryption key - a byte string 5-16 bytes long :param data: The ciphertext - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext r@r.rArBNr>rCr<r<r=r)s cCsjt|dkst|dkr*ttdt||s8td}nt|dkrVttdt||td|||dfS)ab Encrypts plaintext using RC2 with a 64 bit key :param key: The encryption key - a byte string 8 bytes long :param data: The plaintext - a byte string :param iv: The 8-byte initialization vector to use - a byte string - set as None to generate an appropriate one :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext) r@r.rA9 iv must be 8 bytes long - is %s rc2Tr4r8r<r<r=r(#s  cCsXt|dkst|dkr*ttdt|t|dkrHttdt|td|||dS)a" Decrypts RC2 ciphertext using a 64 bit key :param key: The encryption key - a byte string 8 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector used for encryption - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext r@r.rArDrErFTr>r8r<r<r=r'Os cCs~t|dkr*t|dkr*ttdt||s8td}nt|dkrVttdt|d}t|dkrjd}|t||||dfS) a Encrypts plaintext using 3DES in either 2 or 3 key mode :param key: The encryption key - a byte string 16 or 24 bytes long (2 or 3 key mode) :param data: The plaintext - a byte string :param iv: The 8-byte initialization vector to use - a byte string - set as None to generate an appropriate one :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext) r.r/W key must be 16 bytes (2 key) or 24 bytes (3 key) long - is %s rDrEtripledes_3keytripledes_2keyTr4r9r:r;cipherr<r<r=r,xs    cCslt|dkr*t|dkr*ttdt|t|dkrHttdt|d}t|dkr\d}t||||dS) aC Decrypts 3DES ciphertext in either 2 or 3 key mode :param key: The encryption key - a byte string 16 or 24 bytes long (2 or 3 key mode) :param data: The ciphertext - a byte string :param iv: The initialization vector used for encryption - a byte string :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext r.r/rGrDrErHrITr>rJr<r<r=r+s  cCs^t|dkrttdt||s,td}nt|dkrJttdt||td|||dfS)a Encrypts plaintext using DES with a 56 bit key :param key: The encryption key - a byte string 8 bytes long (includes error correction bits) :param data: The plaintext - a byte string :param iv: The 8-byte initialization vector to use - a byte string - set as None to generate an appropriate one :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A tuple of two byte strings (iv, ciphertext) rDT key must be 8 bytes (56 bits + 8 parity bits) long - is %s rEdesTr4r8r<r<r=r&s   cCsLt|dkrttdt|t|dkrr8r<r<r=r%s  cCsd}|dkr(tjtjtjdt|}ntjtjtjtjtj d|}tj }t |dd}t t d}t|}tj|_tj|_d|_||_t t d }t|} || _t|| _t||} d} |td d gkrt|d krtj} tt d } t || t| t| | } t| t| }|d krFtt dt|d}t |tj|d} t| |d krt |tj |d} t| tt dtj!}t |tj"|d} t| tt dtj#}t |tj$|d} t| ||fS)a Creates an HCRYPTPROV and HCRYPTKEY for symmetric encryption/decryption. The HCRYPTPROV must be released by close_context_handle() and the HCRYPTKEY must be released by advapi32.CryptDestroyKey() when done. :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: A byte string of the symmetric key :param iv: The initialization vector - a byte string - unused for RC4 :return: A tuple of (HCRYPTPROV, HCRYPTKEY) Nr3r-)rMrIrHrFrBF)Z verify_onlyZ BLOBHEADERrPLAINTEXTKEYBLOBrFrBr@z HCRYPTKEY *DWORD *rD)%rZ CALG_AES_128Z CALG_AES_192Z CALG_AES_256r5ZCALG_DESZ CALG_3DES_112Z CALG_3DESZCALG_RC2ZCALG_RC4ZMS_ENH_RSA_AES_PROVrrrrrNZbTypeZCUR_BLOB_VERSIONZbVersionreservedZaiKeyAlghdrZ dwKeySizersetZ CRYPT_NO_SALTr ZCryptImportKeyr rZCryptSetKeyParamZKP_EFFECTIVE_KEYLENZKP_IVZCRYPT_MODE_CBCZKP_MODEZ PKCS5_PADDINGZ KP_PADDING)rKr9r;context_handleZ algorithm_idproviderZblob_header_pointerZ blob_headerblob_struct_pointer blob_structblobflagskey_handle_pointerres key_handlebufr<r<r=_advapi32_create_handles,s        r]c Csd}tjtjtjtjtjtjd|}zt|}tj }t t d}t |}tj |_tj|_t||_t||}|dkrtt dt|d}t |tj|dd} t| tt d } t |t|| td|t|d } t| t | WS|rt|XdS) ao Creates a BCRYPT_KEY_HANDLE for symmetric encryption/decryption. The handle must be released by bcrypt.BCryptDestroyKey() when done. :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: A byte string of the symmetric key :return: A BCRYPT_KEY_HANDLE N)r3rMrIrHrFrBZBCRYPT_KEY_DATA_BLOB_HEADERrFrOrDrzBCRYPT_KEY_HANDLE *)rZBCRYPT_AES_ALGORITHMZBCRYPT_DES_ALGORITHMZBCRYPT_3DES_112_ALGORITHMZBCRYPT_3DES_ALGORITHMZBCRYPT_RC2_ALGORITHMZBCRYPT_RC4_ALGORITHMr rZBCRYPT_KEY_DATA_BLOBrrrZBCRYPT_KEY_DATA_BLOB_MAGICZdwMagicZBCRYPT_KEY_DATA_BLOB_VERSION1Z dwVersionr5Z cbKeyDatarr ZBCryptSetPropertyZBCRYPT_EFFECTIVE_KEY_LENGTHrZBCryptImportKeyr ) rKr9Z alg_handleZ alg_constantZ blob_typerUrVrWr\rZrYr<r<r=_bcrypt_create_key_handlesZ       r_cCst|tsttdt|t|ts8ttdt||dkr\t|ts\ttdt||dkr|s|dkrt|ddkstdtd krt|||||St |||||S) a Encrypts plaintext :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - a byte string - unused for RC4 :param padding: Boolean, if padding should be used - unused for RC4 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext ; key must be a byte string, not %s < data must be a byte string, not %s rB: iv must be a byte string, not %s r3r.rpadding must be specifiedr) isinstancer TypeErrorrrr5r6_backend_advapi32_encrypt_bcrypt_encryptrKr9r:r;paddingr<r<r=r7s*   r7c Csd}d}zt|||\}}ttdt|}t|tddt|d}t|t |} t | } t | |t |t|t|tdd| || }t|t | t |} |dkr|st| t|dkr| dd} | WS|rt||rt|XdS)a Encrypts plaintext via CryptoAPI :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - a byte string - unused for RC4 :param padding: Boolean, if padding should be used - unused for RC4 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext NrOTrr3r.i)rCryptDestroyKeyrr]r r5Z CryptEncryptr rr rrr r ) rKr9r:r;rjrSr[out_lenrZ buffer_lenbufferoutputr<r<r=rg"sJ      rgc Csd}zt||}|dkrd}nt|}d}|dkr8tj}ttd}t||t|ttdtd|| } t | t |} t | } |rt |nt} t||t|t| || | || } t | t | t |WS|rt|XdS)a Encrypts plaintext via CNG :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: The plaintext - a byte string :param iv: The initialization vector - a byte string - unused for RC4 :param padding: Boolean, if padding should be used - unused for RC4 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the ciphertext NrTULONG *) rBCryptDestroyKeyr_r5rBCRYPT_BLOCK_PADDINGr Z BCryptEncryptr rr rr rKr9r:r;rjr[Ziv_lenrXrlrZrmrnZ iv_bufferr<r<r=rhqsT    rhcCst|tsttdt|t|ts8ttdt||dkr\t|ts\ttdt||tddgkrx|sxtdtdkrt|||||St |||||S)a Decrypts AES/RC4/RC2/3DES/DES ciphertext :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector - a byte string - unused for RC4 :param padding: Boolean, if padding should be used - unused for RC4 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext r`rarBrbr3rcr) rdrrerrrRr6rf_advapi32_decrypt_bcrypt_decryptrir<r<r=r?s(  r?c Csd}d}zt|||\}}|dkr>|s>t|ddkr>tdt|}ttdt|}t|t |dkrp|spdndd||} t | t |t |WS|rt||rt|XdS) a Decrypts AES/RC4/RC2/3DES/DES ciphertext via CryptoAPI :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector - a byte string - unused for RC4 :param padding: Boolean, if padding should be used - unused for RC4 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext Nr3r.rz9Invalid data - ciphertext length must be a multiple of 16rOFT) rrkrr]r5r6rr Z CryptDecryptr rr r ) rKr9r:r;rjrSr[rnrlrZr<r<r=rts,  rtc Csd}zt||}|dkrd}nt|}d}|dkr8tj}ttd}t||t|ttdtd|| } t | t |} t | } |rt |nt} t||t|t| || | || } t | t | t |WS|rt|XdS)a Decrypts AES/RC4/RC2/3DES/DES ciphertext via CNG :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: The ciphertext - a byte string :param iv: The initialization vector - a byte string - unused for RC4 :param padding: Boolean, if padding should be used - unused for RC4 :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the plaintext NrTrp) rrqr_r5rrrr Z BCryptDecryptr rr rr rsr<r<r=ru>sT    ruN): __future__rrrr_errorsrZ_ffirr r r r r rrrrutilrr_typesrrrfZ _advapi32rrrrrZ_cngrrrr __all__r"r!r$r#r*r)r(r'r,r+r&r%r]r_r7rgrhr?rtrur<r<r<r=sT 0  7+.*,)0--*oG@OS==PK!}sff__pycache__/tls.cpython-38.pycnu[U af@sddlmZmZmZmZddlZddlZddlZddl Z ddl Z ddl m Z ddlmZddlmZmZmZmZmZmZmZmZmZmZmZmZmZmZddlm Z m!Z!m"Z"dd l#m$Z$m%Z%m"Z&dd l'm(Z(dd l)m*Z*m+Z+m,Z,m-Z-dd l.m/Z/m0Z0m1Z1m2Z2dd l3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;mZ>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFddlGmHZHm Z ddlImJZJejKdkreLZMejNZOnePZOejKdkrejQZRnejRZRddgZSeTdZUeVZWeWdeWdfZXGddde0ZYGddde/ZZGddde[Z\Gddde[Z]dS))unicode_literalsdivisionabsolute_importprint_functionN) Certificate)pretty_message)buffer_from_bytesbuffer_from_unicodebytes_from_buffercastderefis_nullnativenewnullrefsizeofstructunwrapwrite_to_buffer)secur32 Secur32Const handle_error)crypt32 Crypt32Constr)kernel32) type_namestr_clsbyte_cls int_types)TLSErrorTLSVerificationErrorTLSDisconnectErrorTLSGracefulDisconnectError)detect_client_auth_requestdetect_other_protocol extract_chainget_dh_params_length parse_alertparse_session_inforaise_client_authraise_dh_paramsraise_disconnectionraise_expired_not_yet_validraise_handshakeraise_hostnameraise_no_issuerraise_protocol_errorraise_protocol_version raise_revokedraise_self_signedraise_verificationraise_weak_signature)load_certificater)parse_certificate))r; TLSSession TLSSockets( | | )c@s eZdZdS)_TLSDowngradeErrorN)__name__ __module__ __qualname__rCrCB/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/tls.pyr?Qsr?c@seZdZdZdS)_TLSRetryErrorz TLSv1.2 on Windows 7 and 8 seems to have isuses with some DHE_RSA ServerKeyExchange messages due to variable length integer encoding. This exception is used to trigger a reconnection to attempt the handshake again. N)r@rArB__doc__rCrCrCrDrEVsrEc@s>eZdZdZdZdZdZdZdZd ddZ ddZ dd Z dS) r=zj A TLS session object that multiple TLSSocket objects can share for the sake of session reuse NFc Cs<t|tsttdt|||_|dkr8tdddg}t|trNt|g}nt|tsjttdt||tddddg}|rttdt |||_ g|_ |r0|D]}t|t r|j }nbt|trt|}nNt|trt|d }t|}W5QRXnt|ts"ttd t||j |q|dS) a] :param protocol: A unicode string or set of unicode strings representing allowable protocols to negotiate with the server: - "TLSv1.2" - "TLSv1.1" - "TLSv1" - "SSLv3" Default is: {"TLSv1", "TLSv1.1", "TLSv1.2"} :param manual_validation: If certificate and certificate path validation should be skipped and left to the developer to implement :param extra_trust_roots: A list containing one or more certificates to be treated as trust roots, in one of the following formats: - A byte string of the DER encoded certificate - A unicode string of the certificate filename - An asn1crypto.x509.Certificate object - An oscrypto.asymmetric.Certificate object :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library zM manual_validation must be a boolean, not %s NTLSv1TLSv1.1TLSv1.2zu protocol must be a unicode string or set of unicode strings, not %s SSLv3z protocol must contain only the unicode strings "SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2", not %s rbz extra_trust_roots must be a list of byte strings, unicode strings, asn1crypto.x509.Certificate objects or oscrypto.asymmetric.Certificate objects, not %s ) isinstancebool TypeErrorrr_manual_validationsetr ValueErrorrepr _protocols_extra_trust_rootsrZasn1r r:openreadAsn1Certificateappend_obtain_credentials)selfprotocolZmanual_validationZextra_trust_rootsZunsupported_protocolsZextra_trust_rootfrCrCrD__init__msN          zTLSSession.__init__c Cstjtjtjtjd}d}|D]\}}||jkr"||O}q"tjtjtj tj tj tj tj tjtjtjg }d|jkr|tjtjtjgttdt|}t|D]\}}|||<qtjtjB} |js|js| tjO} n | tjO} ttd} t | } tj!| _"d| _#t$| _%t$| _&d| _'t$| _(t|| _)|| _*|| _+d| _,d| _-d| _.| | _/d| _0ttd} t1t$tj2tj3t$| t$t$| t$ } t4| | |_5dS)zU Obtains a credentials handle from secur32.dll for use with SChannel )rJrGrHrIrrIz ALG_ID[%s]Z SCHANNEL_CREDz CredHandle *N)6rSP_PROT_SSL3_CLIENTSP_PROT_TLS1_CLIENTSP_PROT_TLS1_1_CLIENTSP_PROT_TLS1_2_CLIENTitemsrSZ CALG_AES_128Z CALG_AES_256Z CALG_3DESZ CALG_SHA1Z CALG_ECDHEZ CALG_DH_EPHEMZ CALG_RSA_KEYXZ CALG_RSA_SIGNZ CALG_ECDSAZ CALG_DSS_SIGNextendZ CALG_SHA512Z CALG_SHA384Z CALG_SHA256rrlen enumerateZSCH_USE_STRONG_CRYPTOZSCH_CRED_NO_DEFAULT_CREDSrOrTZSCH_CRED_AUTO_CRED_VALIDATIONZSCH_CRED_MANUAL_CRED_VALIDATIONrrZSCHANNEL_CRED_VERSIONZ dwVersionZcCredsrZpaCredZ hRootStoreZcMappersZ aphMappersZcSupportedAlgsZpalgSupportedAlgsZgrbitEnabledProtocolsZdwMinimumCipherStrengthZdwMaximumCipherStrengthZdwSessionLifespandwFlagsZ dwCredFormatZAcquireCredentialsHandleWZ UNISP_NAMEZSECPKG_CRED_OUTBOUNDr_credentials_handle)rZZprotocol_valuesZprotocol_bit_maskkeyvalueZalgsZ alg_arrayindexalgflagsZschannel_cred_pointerZ schannel_credZcred_handle_pointerresultrCrCrDrYs~            zTLSSession._obtain_credentialscCs$|jr t|j}t|d|_dSN)rgrZFreeCredentialsHandler)rZrmrCrCrD__del__s zTLSSession.__del__)NFN) r@rArBrFrSZ_ciphersrOrTrgr]rYrorCrCrCrDr=as ZQc@seZdZdZdZdZdZdZdZdZ dZ dZ dZ dZ dZdZdZdZdZdZdZdZdZdZdZdZdZdZed=ddZd>ddZd d Zd d Z d?d dZ!ddZ"d@ddZ#ddZ$ddZ%ddZ&ddZ'dAddZ(ddZ)dd Z*d!d"Z+d#d$Z,e-d%d&Z.e-d'd(Z/e-d)d*Z0e-d+d,Z1e-d-d.Z2e-d/d0Z3e-d1d2Z4e-d3d4Z5e-d5d6Z6e-d7d8Z7e-d9d:Z8d;d<Z9dS)Br>z8 A wrapper around a socket.socket that adds TLS NFc Cst|tjsttdt|t|ts:ttdt||dk r^t|ts^ttdt||dd|d}||_||_ z | Wnbt k r}zt |j |j}|W5d}~XYn0tk r}zt|j }|W5d}~XYnX|S)az Takes an existing socket and adds TLS :param socket: A socket.socket object to wrap with TLS :param hostname: A unicode string of the hostname or IP the socket is connected to :param session: An existing TLSSession object to allow for session reuse, specific protocol or manual certificate validation :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library zU socket must be an instance of socket.socket, not %s zK hostname must be a unicode string, not %s N` session must be an instance of oscrypto.tls.TLSSession, not %s )session)rLsocket_socketrNrrrr=_socket _hostname _handshaker?r#message certificaterEr")clsrshostnamerqZ new_socketeZnew_erCrCrDwrapEs6    zTLSSocket.wrap cCsd|_d|_|dkr$|dkr$d|_n|t|ts@ttdt|t|ts\ttdt||dk rt|t j sttdt|t ||f||_|j ||dkrt}nt|tsttdt|||_|jr||_z |Wntk r`|t|jtdg|j|j}|d|_||_t ||f||_|j ||YnBtk rd|_t ||f||_|j ||YnXdS)a :param address: A unicode string of the domain name or IP address to connect to :param port: An integer of the port number to connect to :param timeout: An integer timeout to use for the socket :param session: An oscrypto.tls.TLSSession object to allow for session reuse and controlling the protocols and validation performed NzR address must be a unicode string, not %s zI port must be an integer, not %s zJ timeout must be a number, not %s rprI)_received_bytes_decrypted_bytesrtrLrrNrrr!numbersNumberrrcreate_connection settimeoutr=_sessionrurvr?closerSrPrOrTrorE)rZaddressporttimeoutrqZ new_sessionrCrCrDr]sf        zTLSSocket.__init__cCsnttd|}td|D]&}d||_tj||_t||_qt td}t |}tj |_ ||_ ||_||fS)z Creates a SecBufferDesc struct and contained SecBuffer structs :param number: The number of contains SecBuffer objects to create :return: A tuple of (SecBufferDesc pointer, SecBuffer array) z SecBuffer[%d]r SecBufferDesc)rrrangecbBufferrSECBUFFER_EMPTY BufferTyperpvBufferrrSECBUFFER_VERSION ulVersioncBufferspBuffers)rZnumberbuffersrjsec_buffer_desc_pointersec_buffer_descrCrCrD_create_bufferss    zTLSSocket._create_buffersc( Csd}d}zttjtjtdt}t|r6t dt }|j j D]B}| }t|tj|t|tjt}|szt d||jqDttd}t|jtj|}t|t|}ttd|}ttd} t| ttd| } ttd} ttdtj| d<ttdtj| d<ttdtj | d <t!td } t| } d | _"ttd | | _#t!td }t|}tj$|_%| |_&t!td}t|}||_'t(t|}||_)ttd}t*t|| ||tj+tj,Bt|}t |tj-}t|}t|}t.t/|j0}|dkrbt|j1}t|}t.t/|j2}|j3|d}t|}t|j4}t5|j6t.t/|j7}t89|}|j|krb|tj:O}t!td}t|} t(t| | _)tj;| _|j?| _@t!td}!t|!}"t(t|"|"_)||"_Attd||"_Bt!td}#t|#}$t(t|$|$_)tCtjD||!|#}t |t|}%t5|%j6t.t/|%j7}t89|}|$jE}&|&r|&tjFkrRtG||&tjHkrtI|}'|'jJrxtK|ntL||&tjMkrtN||j?|&tjOkrtP||&tjQkrtR|tS||jTt ddgkrtP|W5|rt|d|r t|XdS)z Manually invoked windows certificate chain builder and verification step when there are extra trust roots to include in the search process NrzPCERT_CONTEXT *Z PCERT_CONTEXTz FILETIME *z char *[3]zchar *rrZCERT_ENHKEY_USAGEr;zchar **ZCERT_USAGE_MATCHZCERT_CHAIN_PARAzPCERT_CHAIN_CONTEXT *Z SSL_EXTRA_CERT_CHAIN_POLICY_PARAz wchar_t *ZCERT_CHAIN_POLICY_PARAzvoid *ZCERT_CHAIN_POLICY_STATUSmd5Zmd2)UrCertCloseStoreZCertFreeCertificateChainZ CertOpenStorerZCERT_STORE_PROV_MEMORYZX509_ASN_ENCODINGrrhandle_crypt32_errorrPrrTdumpZ CertAddEncodedCertificateToStorerdZCERT_STORE_ADD_USE_EXISTINGaddsha256rrQueryContextAttributesW_context_handle_pointerrSECPKG_ATTR_REMOTE_CERT_CONTEXTrrr rZGetSystemTimeAsFileTimeZPKIX_KP_SERVER_AUTHZSERVER_GATED_CRYPTOZ SGC_NETSCAPErZcUsageIdentifierZrgpszUsageIdentifierZUSAGE_MATCH_TYPE_ORZdwTypeUsageZRequestedUsagerZcbSizeZCertGetCertificateChainZCERT_CHAIN_CACHE_END_CERTZ&CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLYZ.CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGSrintZcChainZrgpChainZcElementZ rgpElementZ pCertContextr pbCertEncoded cbCertEncodedrWloadZ'CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAGZAUTHTYPE_SERVERZ dwAuthTypeZ fdwChecksr ruZpwszServerNamerfZpvExtraPolicyParaZ CertVerifyCertificateChainPolicyZCERT_CHAIN_POLICY_SSLZdwErrorZCERT_E_EXPIREDr/ZCERT_E_UNTRUSTEDROOTr9 self_signedr6r2ZCERT_E_CN_NO_MATCHr1TRUST_E_CERT_SIGNATUREr8ZCRYPT_E_REVOKEDr5r7Z hash_algo)(rZstoreZcert_chain_context_pointerZ cert_hashescert cert_datarmcert_context_pointer_pointercert_context_pointerZorig_now_pointerZ now_pointerZusage_identifiersZcert_enhkey_usage_pointerZcert_enhkey_usageZcert_usage_match_pointerZcert_usage_matchZcert_chain_para_pointerZcert_chain_paraZcert_chain_para_sizeZ"cert_chain_context_pointer_pointerZcert_chain_policy_para_flagsZcert_chain_contextZ num_chainsZfirst_simple_chain_pointerZfirst_simple_chainZ num_elementsZlast_element_pointerZ last_elementZlast_element_certZlast_element_cert_dataZ last_certZ(ssl_extra_cert_chain_policy_para_pointerZ ssl_extra_cert_chain_policy_paraZcert_chain_policy_para_pointerZcert_chain_policy_paraZ cert_chain_policy_status_pointerZcert_chain_policy_status cert_contexterror oscrypto_certrCrCrD_extra_trust_root_validations                                       z&TLSSocket._extra_trust_root_validationc!Csd}d}d}zzd|r |j}nttd}|}tjdtj dtj dtj dtj d tj d tjd i}d|_|D]}|j|O_qf|d \}}tj|d_|d \} }tj|d_tj|d_ttd } |r|} t} n t} |} t|jj| |j|jddtd| | | t } | ttjtjgkr*t| t|s6| }n| }d}d}|djdkrt|dj|dj}||7}|j !|d|d_t|djt|d_t"d}t#td||d_d}| tjkrz$d}|j $d}|dkrt%Wnt&k r d}YnX||7}|j'|7_'t(|j'|d_t)||j't|jj||j|jdd|dt| | t } | tj*krtj|d_|djtj+krtj+|d_d|d_t|djst|djt|d_|rt%q| tj,kr&t-|rt.t/|}|r |dkr t0t1| tj2krJt3|}t4|d|j| tj5krjt3|}t6|d| tj7krt3|}|d}t8|}|j9st:|t;|| tj| tj?krt.| t@jAkrtB|| tjCkr|djdkr|t|dj|dj}||7}|dd}|dksF|dkr|d|jjDkr|t(|jjDdkr|t3|}tEd|dt-|rt.tF|rtG|t1| tjHks| tjIkrd|jjDkrtJd|rt%| tjKkrt=|dkrt>| ttjtjgkrt| t|djdkr~t|dj|dj}||7}|j !|d|d_t|djt|d_|djtjLkr|dj}|j'| d|_'tj+|d_d|d_t|djt|d_| tjkr|| d}nd|_'qtMtd}tN|tjO|} t| ttP|}tjQdtjRdtjSd tjTd!tjUdiVtWtX|jYtZ|jY|_[|j[tdd d!dgkrt\||}|d"|_]|d#|_^|d$|__|d%|_`ta| }|D]&}||Bdkrtbtcd&||q|sb||_d}tMtd'}tN|jtjd|} t| tP|} tWtX| je|_ftWtX| jg|_htWtX| ji|_j|jf|jh|jj|_k|jjlrt|mWn&tbtnjofk r|pYnXW5|rt|djst|djt|djst|dj|rt|XdS)(z Perform an initial TLS handshake, or a renegotiation :param renegotiate: If the handshake is for a renegotiation Nrrz CtxtHandle *zreplay detectionzsequence detectionZconfidentialityzmemory allocationZ integrityzstream orientationzdisable automatic client authrULONG *r~iBYTE *F T)rFir<(+rIzMServer certificate verification failed - weak certificate signature algorithmzTLS handshake failedZSecPkgContext_ConnectionInfoZSSLv2rJrGrH cipher_suite compression session_idsession_ticketzl Unable to obtain a credential context with the property %s ZSecPkgContext_StreamSizes)qrrrFreeContextBufferDeleteSecurityContextrrrZISC_REQ_REPLAY_DETECTZISC_REQ_SEQUENCE_DETECTZISC_REQ_CONFIDENTIALITYZISC_REQ_ALLOCATE_MEMORYZISC_REQ_INTEGRITYZISC_REQ_STREAMZISC_REQ_USE_SUPPLIED_CREDS_context_flagsrSECBUFFER_TOKENrSECBUFFER_ALERTrInitializeSecurityContextWrrgrurPSEC_E_OKSEC_I_CONTINUE_NEEDEDrr"rr rtsendr r recvr.socket_error_clsrrdrSEC_E_INCOMPLETE_MESSAGErZSEC_E_ILLEGAL_MESSAGEr&r,r*r4r0ZSEC_E_WRONG_PRINCIPALr(r1ZSEC_E_CERT_EXPIREDr/ZSEC_E_UNTRUSTED_ROOTr9rr2r6ZSEC_E_INTERNAL_ERRORr)r-ZSEC_I_INCOMPLETE_CREDENTIALSrrr8ZSEC_E_INVALID_TOKENrSr?r'r3ZSEC_E_BUFFER_TOO_SMALLZSEC_E_MESSAGE_ALTEREDrEZSEC_E_INVALID_PARAMETERSECBUFFER_EXTRArrZSECPKG_ATTR_CONNECTION_INFOrZSP_PROT_SSL2_CLIENTr^r_r`ragetrrZ dwProtocolr _protocolr+ _cipher_suite _compression _session_id_session_ticketr OSErrorrZSECPKG_ATTR_STREAM_SIZESZcbHeader _header_sizeZcbMaximumMessage _message_sizeZ cbTrailer _trailer_size _buffer_sizerTrrrrr)!rZ renegotiateZ in_buffers out_buffersZnew_context_handle_pointerZtemp_context_handle_pointerZrequested_flagsflagZin_sec_buffer_desc_pointerout_sec_buffer_desc_pointeroutput_context_flags_pointerZ first_handleZ second_handlermZhandshake_server_bytesZhandshake_client_bytestokenZin_data_buffer bytes_readZ fail_lateZ alert_infochainrrZ alert_bytesZ alert_number extra_amountZconnection_info_pointerZconnection_infoZ session_infoZoutput_context_flagsZstream_sizes_pointerZ stream_sizesrCrCrDrvs                                                           zTLSSocket._handshakec sXt|tsttdt|jdkrZjdkrRjd|}j|d_|Sjst j _ d\_ _ tjj d_ttdjj d_t|j }tj dj dj dj d fd d }j}t|}d_|dkr&ds&d_|Stjdk}||kr,|rpjj|7_tjdkrptttjj }|dkrq,|j d_tjjd|tjj dt}d }|tj kr|d }q4nX|tj!krd _"#q,n8|tj$kr*j%d d&|S|tj'kr@t(|t)t*tj+tj,tj-g} d} fD]f} | j} | tjkr|t.| j| j7}t|}n2| tj/krt0t1| j} n| | krdt2td| qd| rj|| d_nj|d_|drd }|s4tjdkr4q,q4t||krT||d_|d|}|S)a0 Reads data from the TLS-wrapped socket :param max_length: The number of bytes to read :raises: socket.socket - when a non-TLS socket error occurs oscrypto.errors.TLSError - when a TLS-related error occurs ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: A byte string of the data read zG max_length must be an integer, not %s Nr~rrrrr;cs^tj_ttdj_d_tj__d_tj__d_tj__d_dS)Nrr) rSECBUFFER_DATArr r_decrypt_data_bufferrrrrCZbuf0Zbuf1buf2Zbuf3Z null_valuerZrCrD_reset_bufferssz&TLSSocket.read.._reset_buffersFT)rz] Unexpected decrypt output buffer of type %s )3rLr!rNrrrr _raise_closedrr rr _decrypt_desc_decrypt_buffersrrrr rrmaxrrd select_readrrtrr.minrrZDecryptMessagerZSEC_I_CONTEXT_EXPIRED_remote_closedshutdownZSEC_I_RENEGOTIATErvrVrrr"rPrSECBUFFER_STREAM_HEADERSECBUFFER_STREAM_TRAILERr rrrr) rZ max_lengthoutputZto_recvrZ output_lenZdo_readdata_lenrmZvalid_buffer_typesrbufZ buffer_typerCrrDrVs                          zTLSSocket.readcCs8t|jdkrdSt|jggg|\}}}t|dkS)aZ Blocks until the socket is ready to be read from, or the timeout is hit :param timeout: A float - the period of time to wait for data to be read. None for no time limit. :return: A boolean - if data is ready to be read. Will only be False if timeout is not None. rT)rdrselectrt)rZrZ read_ready_rCrCrDrszTLSSocket.select_readc Cst|ts&t|ts&ttdt|d}t|t}t|jdkrP|j}d|_n |d}t|}||7}|r| |}|dk r| }qq4t d|t|d}| ||}|dkr4|t|}qq4||d|j|_|d|S)a Reads data from the socket until a marker is found. Data read may include data beyond the marker. :param marker: A byte string or regex object from re.compile(). Used to determine when to stop reading. Regex objects are more inefficient since they must scan the entire byte string of read data each time data is read off the socket. :return: A byte string of the data read z_ marker must be a byte string or compiled regex object, not %s r~rrNr) rLr PatternrNrrrdrrVsearchendrfind) rZmarkerris_regexchunkoffsetmatchrstartrCrCrD read_untils2     zTLSSocket.read_untilcCs |tS)z Reads a line from the socket, including the line ending of "\r\n", "\r", or "\n" :return: A byte string of the next line from the socket )r _line_regexrZrCrCrD read_lines zTLSSocket.read_linecCs0d}|}|dkr,|||7}|t|}q|S)z Reads exactly the specified number of bytes from the socket :param num_bytes: An integer - the exact number of bytes to read :return: A byte string of the data that was read r~r)rVrd)rZ num_bytesr remainingrCrCrD read_exactlys zTLSSocket.read_exactlyc Cs|jdkr||jst|j|j|j|_|d\|_|_ t j |j d_ |j|j d_ ttd|j|j d_t j|j d_ t|j|j|j d_t j|j d_ |j|j d_ t|j|j|j|j d_t|dkrtt||j}t|j|d||j||j d_ t|j|j||j d_t|jd|jd}|t jkrVt|ttt|j dj }|tt|j dj 7}|tt|j dj 7}z|jt|j|Wn:t j!k r}z|j"dkrt#W5d}~XYnX||d}qdS)a Writes data to the TLS-wrapped socket :param data: A byte string to write to the socket :raises: socket.socket - when a non-TLS socket error occurs oscrypto.errors.TLSError - when a TLS-related error occurs ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library NrrrrriE')$rr_encrypt_data_bufferr rrrr _encrypt_desc_encrypt_buffersrrrrr rrrrrrdrrZEncryptMessagerrr"rrrtrr rrrerrnor.)rZdataZto_writermto_sendr{rCrCrDwritesH     zTLSSocket.writecCs&tg|jgg|\}}}t|dkS)aw Blocks until the socket is ready to be written to, or the timeout is hit :param timeout: A float - the period of time to wait for the socket to be ready to written to. None for no time limit. :return: A boolean - if the socket is ready for writing. Will only be False if timeout is not None. r)rrtrd)rZrrZ write_readyrCrCrD select_write's zTLSSocket.select_writec Cs|jdkrdSd}zHt dkrt td}d|d_ tj|d_ttdtd|d_ttd }t|}tj|_d|_||_t|j|}t|t|d \}}tj|d_tj|d_t td }t|jj |j|j!|j"ddt#dt#||t# }t$tj%tj&tj'g}||krt|tt(|dj|dj } z|j)| Wntj k rXYnXW5|rt|djst|djt|djst|djt|jd|_z|jtj Wntj k rYnXXdS) z Shuts down the TLS session and then shuts down the underlying socket :raises: OSError - when an error is returned by the OS crypto library Nrr)rrz SecBuffer[1]rrsrrr)*rrrrrrrtrrr SHUT_RDWRr_win_version_inforrrrrr r rrrrrrZApplyControlTokenrr"rrrrrgrurrrPrZSEC_E_CONTEXT_EXPIREDrr r) rZrrrrrmrrZacceptable_resultsrrCrCrDr7sr             zTLSSocket.shutdowncCsFz |W5|jr@z|jWntjk r8YnXd|_XdS)zN Shuts down the TLS session and socket and forcibly closes it N)rtrrrrrrrCrCrDrs zTLSSocket.closec Csttd}t|jtj|}t|tt |}t td|}t |}t |j t t|j}t||_g|_d}zd|j}t|t}t|st |}t |j t t|j} | |kr|jt| t||}qW5|rt|dXdS)zh Reads end-entity and intermediate certificate information from the TLS session zCERT_CONTEXT **zCERT_CONTEXT *Nr)rrrrrrrrr"rr r rrrrrWr _certificate_intermediatesrZ hCertStoreZCertEnumCertificatesInStorerrrX) rZrrmrrrZ store_handleZcontext_pointercontextr rCrCrD_read_certificatess2    zTLSSocket._read_certificatescCs|jrtdntddS)zi Raises an exception describing if the local or remote end closed the connection z$The remote end closed the connectionz!The connection was already closedN)rr%r$rrCrCrDrs zTLSSocket._raise_closedcCs*|jdkr||jdkr$||jS)zu An asn1crypto.x509.Certificate object of the end-entity certificate presented by the server N)rrrrrrCrCrDrxs   zTLSSocket.certificatecCs*|jdkr||jdkr$||jS)zz A list of asn1crypto.x509.Certificate objects that were presented as intermediates by the server N)rrrrrrrCrCrD intermediatess   zTLSSocket.intermediatescCs|jS)zg A unicode string of the IANA cipher suite name of the negotiated cipher suite )rrrCrCrDrszTLSSocket.cipher_suitecCs|jS)zM A unicode string of: "TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3" )rrrCrCrDr[szTLSSocket.protocolcCs|jS)z5 A boolean if compression is enabled )rrrCrCrDrszTLSSocket.compressioncCs|jSzM A unicode string of "new" or "reused" or None for no ticket )rrrCrCrDrszTLSSocket.session_idcCs|jSr)rrrCrCrDr szTLSSocket.session_ticketcCs|jS)zM The oscrypto.tls.TLSSession object used for this connection )rrrCrCrDrqszTLSSocket.sessioncCs|jS)zN A unicode string of the TLS server domain name or IP address )rurrCrCrDrzszTLSSocket.hostnamecCs|jdS)zJ An integer of the port number the socket is connected to r)rs getpeernamerrCrCrDr%szTLSSocket.portcCs|jdkr||jS)z9 The underlying socket.socket connection N)rrrtrrCrCrDrs-s zTLSSocket.socketcCs |dSrn)rrrCrCrDro8szTLSSocket.__del__)N)r}N)F)N)N):r@rArBrFrtrrrrurrrrrrrrrrrrrrrrrrr classmethodr|r]rrrvrVrrrrr r rrrrpropertyrxrrr[rrrrqrzrrsrorCrCrCrDr>s > W3 0+ 7 > T(            )^ __future__rrrrsysrersrrrrZ_asn1rrW_errorsrZ_ffir r r r r rrrrrrrrrZ_secur32rrrZ_crypt32rrrZ _kernel32r_typesrrr r!errorsr"r#r$r%_tlsr&r'r(r)r*r+r,r-r.r/r0r1r2r3r4r5r6r7r8Z asymmetricr9keysr: version_infoxrangerrrZ WindowsErrorZ _pattern_typer__all__compilergetwindowsversionZ_gwvrr?rEobjectr=r>rCrCrCrDsD  @ T     ?PK!OW=%__pycache__/trust_list.cpython-38.pycnu[U af@sddlmZmZmZmZddlZddlZddlZddlm Z ddl m Z m Z m Z mZmZmZmZmZmZmZddlmZmZmZmZddlmZd d gZd d Zdd d ZddZdS))unicode_literalsdivisionabsolute_importprint_functionN) Certificate) array_from_pointerbuffer_from_bytesbytes_from_buffercastderefis_nullnewnullstruct_from_bufferunwrap)crypt32 Crypt32Const get_error handle_error)str_clsextract_from_system system_pathcCsdS)NrrrI/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/trust_list.pyrsFc! Cs:i}i}tj}dD]}tt|}t|t}t||}t|rPqt|}d} d} d} |j t j krrq8t |j t|j} t| } | |krq8d|| <t|j} t| j} z0tj| }||kr|r|t| dWq8Wnttfk rYnXt| j}z4tj|}||kr@|r<|t| dWq8Wnbttfk r}z>|dkr|jddt|}|f|jd d|_|W5d}~XYnXt}t}ttd d}t |t j!t|}t"\}}|s|t j#krt||t j#krd} nt$t%|}t |t j!t&td ||}t|t'td |}t|}|j(dkrl|r8|t| d q8t)td|j*|j(}|D]}|+|,dqd}| st| }|j-r|j-D] }|j.}||kr|+|q|r|s|dkrt| }||d| ||f|| <q8t/|d} t| d}q|0S)a Extracts trusted CA certificates from the Windows certificate store :param cert_callback: A callback that is called once for each certificate in the trust store. It should accept two parameters: an asn1crypto.x509.Certificate object, and a reason. The reason will be None if the certificate is being exported, otherwise it will be a unicode string of the reason it won't. :param callback_only_on_failure: A boolean - if the callback should only be called when a certificate is not exported. :raises: OSError - when an error is returned by the OS crypto library :return: A list of 3-element tuples: - 0: a byte string of a DER-encoded certificate - 1: a set of unicode strings that are OIDs of purposes to trust the certificate for - 2: a set of unicode strings that are OIDs of purposes to reject the certificate for )ROOTCAFNTz not yet validzno longer validrz - rzDWORD *zCERT_ENHKEY_USAGE *ZCERT_ENHKEY_USAGEzexplicitly distrustedZLPCSTRascii)1datetimeutcnowrZCertOpenSystemStoreWrrZCertEnumCertificatesInStorer rZdwCertEncodingTyperZX509_ASN_ENCODINGr Z pbCertEncodedintZ cbCertEncodedhashlibsha1digestZ pCertInfo_convert_filetime_to_timestampZ NotBefore fromtimestamprload ValueErrorOSErrorZNotAfterargsrsetrZCertGetEnhancedKeyUsageZ%CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAGrZCRYPT_E_NOT_FOUNDr r r rZcUsageIdentifierrZrgpszUsageIdentifieradddecodeZextended_key_usage_valueZdottedZCertCloseStorevalues)!Z cert_callbackZcallback_only_on_failureZ certificates processednowstoreZ store_handleZcontext_pointercontextZ trust_alldatar$Z cert_infoZnot_before_secondsZ not_beforeZnot_after_secondsZ not_afteremessageZ trust_oidsZ reject_oidsZto_readresZ error_code_Z usage_bufferZkey_usage_pointerZ key_usageZoidsoidcertZcert_oidresultrrrr#s                          cCs.tdtd|j|jd}|d}|dS)a Windows returns times as 64-bit unsigned longs that are the number of hundreds of nanoseconds since Jan 1 1601. This converts it to a datetime object. :param filetime: A FILETIME struct object :return: An integer unix timestamp s>Qs>LLril!l )structunpackpackZdwHighDateTimeZ dwLowDateTime)ZfiletimeZhundreds_nano_secondsZseconds_since_1601rrrr%s r%)NF) __future__rrrrrr"r;Z_asn1rZ_ffirr r r r r rrrrZ_crypt32rrrr_typesr__all__rrr%rrrrs 0   *PK!1__pycache__/util.cpython-38.pycnu[U afr@sddlmZmZmZmZddlmZddlmZddl m Z m Z ddl m Z ddlmZmZmZdd d gZeZed krd d lmZmZmZmZmZddZde_dd ZnddlmZddlmZdS))unicode_literalsdivisionabsolute_importprint_function)backend)pretty_message)buffer_from_bytesbytes_from_buffer) pkcs12_kdf) type_namebyte_cls int_typespbkdf2r rand_byteswin)bcrypt BcryptConst handle_erroropen_alg_handleclose_alg_handlec Cs4t|tsttdt|t|ts8ttdt|t|tsTttdt||dkrdtdt|tsttdt||dkrtd|tdd d d gkrttd t|t j t j t j t j d |}d}zJt|t j}t|}t||t||t||||d }t|t|WS|r.t|XdS)a% PBKDF2 from PKCS#5 :param hash_algorithm: The string name of the hash algorithm to use: "sha1", "sha256", "sha384", "sha512" :param password: A byte string of the password to use an input to the KDF :param salt: A cryptographic random byte string :param iterations: The numbers of iterations to use when deriving the key :param key_length: The length of the desired key in bytes :raises: ValueError - when any of the parameters contain an invalid value TypeError - when any of the parameters are of the wrong type OSError - when an error is returned by the OS crypto library :return: The derived key as a byte string zH password must be a byte string, not %s zD salt must be a byte string, not %s zG iterations must be an integer, not %s rz!iterations must be greater than 0zG key_length must be an integer, not %s z!key_length must be greater than 0sha1sha256sha384sha512z| hash_algorithm must be one of "sha1", "sha256", "sha384", "sha512", not %s )rrrrNr) isinstancer TypeErrorrr r ValueErrorsetreprrZBCRYPT_SHA1_ALGORITHMZBCRYPT_SHA256_ALGORITHMZBCRYPT_SHA384_ALGORITHMZBCRYPT_SHA512_ALGORITHMrrZBCRYPT_ALG_HANDLE_HMAC_FLAGr rZBCryptDeriveKeyPBKDF2lenrr ) Zhash_algorithmpasswordZsaltZ iterationsZ key_lengthZ alg_constant alg_handleZ output_bufferresr%C/opt/nydus/tmp/pip-target-53d1vnqk/lib/python/oscrypto/_win/util.pyrsn        FcCst|tsttdt||dkr,td|dkrs"   j / PK! __init__.pynu[PK!nQ ;_advapi32.pynu[PK!u_advapi32_cffi.pynu[PK!Cz>>#_advapi32_ctypes.pynu[PK!;N/A_cng.pynu[PK!pv~~ R_cng_cffi.pynu[PK!  d_cng_ctypes.pynu[PK!*ii }_crypt32.pynu[PK!Ί  _crypt32_cffi.pynu[PK!3H&  _crypt32_ctypes.pynu[PK!m? b_decode.pynu[PK!F8&& -_kernel32.pynu[PK!Ԇ_kernel32_cffi.pynu[PK!t_kernel32_ctypes.pynu[PK!H _secur32.pynu[PK!˗h_secur32_cffi.pynu[PK!U]'_secur32_ctypes.pynu[PK!tƸ "asymmetric.pynu[PK!xx *symmetric.pynu[PK!}Xtls.pynu[PK!U >trust_list.pynu[PK!Lrr^util.pynu[PK!o9T#s__pycache__/__init__.cpython-38.pycnu[PK!ǁ $t__pycache__/_advapi32.cpython-38.pycnu[PK!B#)__pycache__/_advapi32_cffi.cpython-38.pycnu[PK!̠+__pycache__/_advapi32_ctypes.cpython-38.pycnu[PK!J gg4__pycache__/_cng.cpython-38.pycnu[PK!=FF$__pycache__/_cng_cffi.cpython-38.pycnu[PK!.+22&__pycache__/_cng_ctypes.cpython-38.pycnu[PK!5Saa# __pycache__/_crypt32.cpython-38.pycnu[PK!**(__pycache__/_crypt32_cffi.cpython-38.pycnu[PK!|!!*B__pycache__/_crypt32_ctypes.cpython-38.pycnu[PK!Yzz"__pycache__/_decode.cpython-38.pycnu[PK!׺@$ __pycache__/_kernel32.cpython-38.pycnu[PK!̵)$__pycache__/_kernel32_cffi.cpython-38.pycnu[PK!\+)__pycache__/_kernel32_ctypes.cpython-38.pycnu[PK!=w#/__pycache__/_secur32.cpython-38.pycnu[PK!LJ(>__pycache__/_secur32_cffi.cpython-38.pycnu[PK!C*O__pycache__/_secur32_ctypes.cpython-38.pycnu[PK!HiHi%`__pycache__/asymmetric.cpython-38.pycnu[PK!ΘYY$__pycache__/symmetric.cpython-38.pycnu[PK!}sff#__pycache__/tls.cpython-38.pycnu[PK!OW=%__pycache__/trust_list.cpython-38.pycnu[PK!1__pycache__/util.cpython-38.pycnu[PK,,V