def __init__(self, ctx, value, opts): """Abstracts libmongocrypt's mongocrypt_ctx_t type. :Parameters: - `ctx`: A mongocrypt_ctx_t. This MongoCryptContext takes ownership of the underlying mongocrypt_ctx_t. - `value`: The encoded document to encrypt, which must be in the form { "v" : BSON value to encrypt }}. - `opts`: A :class:`ExplicitEncryptOpts`. """ super(ExplicitEncryptionContext, self).__init__(ctx) try: algorithm = str_to_bytes(opts.algorithm) if not lib.mongocrypt_ctx_setopt_algorithm(ctx, algorithm, -1): self._raise_from_status() if opts.key_id is not None: with MongoCryptBinaryIn(opts.key_id) as binary: if not lib.mongocrypt_ctx_setopt_key_id(ctx, binary.bin): self._raise_from_status() if opts.key_alt_name is not None: with MongoCryptBinaryIn(opts.key_alt_name) as binary: if not lib.mongocrypt_ctx_setopt_key_alt_name( ctx, binary.bin): self._raise_from_status() with MongoCryptBinaryIn(value) as binary: if not lib.mongocrypt_ctx_explicit_encrypt_init( ctx, binary.bin): self._raise_from_status() except Exception: # Destroy the context on error. self._close() raise
def __init(self): """Internal init helper.""" kms_providers = self.__opts.kms_providers if 'aws' in kms_providers: access_key_id = str_to_bytes(kms_providers['aws']['accessKeyId']) secret_access_key = str_to_bytes( kms_providers['aws']['secretAccessKey']) if not lib.mongocrypt_setopt_kms_provider_aws( self.__crypt, access_key_id, len(access_key_id), secret_access_key, len(secret_access_key)): self.__raise_from_status() if 'local' in kms_providers: key = kms_providers['local']['key'] with MongoCryptBinaryIn(key) as binary_key: if not lib.mongocrypt_setopt_kms_provider_local( self.__crypt, binary_key.bin): self.__raise_from_status() schema_map = self.__opts.schema_map if schema_map is not None: with MongoCryptBinaryIn(schema_map) as binary_schema_map: if not lib.mongocrypt_setopt_schema_map( self.__crypt, binary_schema_map.bin): self.__raise_from_status() if not lib.mongocrypt_setopt_crypto_hooks( self.__crypt, aes_256_cbc_encrypt, aes_256_cbc_decrypt, secure_random, hmac_sha_512, hmac_sha_256, sha_256, ffi.NULL): self.__raise_from_status() if not lib.mongocrypt_init(self.__crypt): self.__raise_from_status()
def test_sign_rsaes_pkcs1_v1_5(self): key_b64 = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC4JOyv5z05cL18ztpknRC7CFY2gYol4DAKerdVUoDJxCTmFMf39dVUEqD0WDiw/qcRtSO1/FRut08PlSPmvbyKetsLoxlpS8lukSzEFpFK7+L+R4miFOl6HvECyg7lbC1H/WGAhIz9yZRlXhRo9qmO/fB6PV9IeYtU+1xYuXicjCDPp36uuxBAnCz7JfvxJ3mdVc0vpSkbSb141nWuKNYR1mgyvvL6KzxO6mYsCo4hRAdhuizD9C4jDHk0V2gDCFBk0h8SLEdzStX8L0jG90/Og4y7J1b/cPo/kbYokkYisxe8cPlsvGBf+rZex7XPxc1yWaP080qeABJb+S88O//LAgMBAAECggEBAKVxP1m3FzHBUe2NZ3fYCc0Qa2zjK7xl1KPFp2u4CU+9sy0oZJUqQHUdm5CMprqWwIHPTftWboFenmCwrSXFOFzujljBO7Z3yc1WD3NJl1ZNepLcsRJ3WWFH5V+NLJ8Bdxlj1DMEZCwr7PC5+vpnCuYWzvT0qOPTl9RNVaW9VVjHouJ9Fg+s2DrShXDegFabl1iZEDdI4xScHoYBob06A5lw0WOCTayzw0Naf37lM8Y4psRAmI46XLiF/Vbuorna4hcChxDePlNLEfMipICcuxTcei1RBSlBa2t1tcnvoTy6cuYDqqImRYjp1KnMKlKQBnQ1NjS2TsRGm+F0FbreVCECgYEA4IDJlm8q/hVyNcPe4OzIcL1rsdYN3bNm2Y2O/YtRPIkQ446ItyxD06d9VuXsQpFp9jNACAPfCMSyHpPApqlxdc8z/xATlgHkcGezEOd1r4E7NdTpGg8y6Rj9b8kVlED6v4grbRhKcU6moyKUQT3+1B6ENZTOKyxuyDEgTwZHtFECgYEA0fqdv9h9s77d6eWmIioP7FSymq93pC4umxf6TVicpjpMErdD2ZfJGulN37dq8FOsOFnSmFYJdICj/PbJm6p1i8O21lsFCltEqVoVabJ7/0alPfdG2U76OeBqI8ZubL4BMnWXAB/VVEYbyWCNpQSDTjHQYs54qa2I0dJB7OgJt1sCgYEArctFQ02/7H5Rscl1yo3DBXO94SeiCFSPdC8f2Kt3MfOxvVdkAtkjkMACSbkoUsgbTVqTYSEOEc2jTgR3iQ13JgpHaFbbsq64V0QP3TAxbLIQUjYGVgQaF1UfLOBv8hrzgj45z/ST/G80lOl595+0nCUbmBcgG1AEWrmdF0/3RmECgYAKvIzKXXB3+19vcT2ga5Qq2l3TiPtOGsppRb2XrNs9qKdxIYvHmXo/9QP1V3SRW0XoD7ez8FpFabp42cmPOxUNk3FK3paQZABLxH5pzCWI9PzIAVfPDrm+sdnbgG7vAnwfL2IMMJSA3aDYGCbF9EgefG+STcpfqq7fQ6f5TBgLFwKBgCd7gn1xYL696SaKVSm7VngpXlczHVEpz3kStWR5gfzriPBxXgMVcWmcbajRser7ARpCEfbxM1UJyv6oAYZWVSNErNzNVb4POqLYcCNySuC6xKhs9FrEQnyKjyk8wI4VnrEMGrQ8e+qYSwYk9Gh6dKGoRMAPYVXQAO0fIsHF/T0a' ciphertext_b64 = "VocBRhpMmQ2XCzVehWSqheQLnU889gf3dhU4AnVnQTJjsKx/CM23qKDPkZDd2A/BnQsp99SN7ksIX5Raj0TPwyN5OCN/YrNFNGoOFlTsGhgP/hyE8X3Duiq6sNO0SMvRYNPFFGlJFsp1Fw3Z94eYMg4/Wpw5s4+Jo5Zm/qY7aTJIqDKDQ3CNHLeJgcMUOc9sz01/GzoUYKDVODHSxrYEk5ireFJFz9vP8P7Ha+VDUZuQIQdXer9NBbGFtYmWprY3nn4D3Dw93Sn0V0dIqYeIo91oKyslvMebmUM95S2PyIJdEpPb2DJDxjvX/0LLwSWlSXRWy9gapWoBkb4ynqZBsg==" value = b'data to sign' with MongoCryptBinaryIn(b'1' * 256) as output, \ MongoCryptBinaryIn(base64.b64decode(key_b64)) as key,\ MongoCryptBinaryIn(value) as value: retval = sign_rsaes_pkcs1_v1_5( ffi.NULL, key.bin, value.bin, output.bin, lib.mongocrypt_status_new()) self.assertTrue(retval) self.assertEqual( output.to_bytes(), base64.b64decode(ciphertext_b64))
def add_mongo_operation_result(self, document): """Adds the mongo operation's command response. :Parameters: - `document`: A raw BSON command response document. """ with MongoCryptBinaryIn(document) as binary: if not lib.mongocrypt_ctx_mongo_feed(self.__ctx, binary.bin): self._raise_from_status()
def feed(self, data): """Feed bytes from the HTTP response. :Parameters: - `data`: The bytes of the HTTP response. Must not exceed :attr:`bytes_needed`. """ with MongoCryptBinaryIn(data) as binary: if not lib.mongocrypt_kms_ctx_feed(self.__ctx, binary.bin): self.__raise_from_status()
def __init(self): """Internal init helper.""" kms_providers = self.__opts.kms_providers # Make fields that can be passed as binary or string safe to # encode to BSON. base64_or_bytes_fields = [("local", "key"), ("gcp", "privateKey")] for f1, f2 in base64_or_bytes_fields: value = kms_providers.get(f1, {}).get(f2, None) if value is not None: safe_value = safe_bytearray_or_base64(value) if value != safe_value: kms_providers = copy.deepcopy(kms_providers) kms_providers[f1][f2] = safe_value with MongoCryptBinaryIn( self.__callback.bson_encode(kms_providers)) as kmsopt: if not lib.mongocrypt_setopt_kms_providers(self.__crypt, kmsopt.bin): self.__raise_from_status() schema_map = self.__opts.schema_map if schema_map is not None: with MongoCryptBinaryIn(schema_map) as binary_schema_map: if not lib.mongocrypt_setopt_schema_map( self.__crypt, binary_schema_map.bin): self.__raise_from_status() if not lib.mongocrypt_setopt_crypto_hooks( self.__crypt, aes_256_cbc_encrypt, aes_256_cbc_decrypt, secure_random, hmac_sha_512, hmac_sha_256, sha_256, ffi.NULL): self.__raise_from_status() if not lib.mongocrypt_setopt_crypto_hook_sign_rsaes_pkcs1_v1_5( self.__crypt, sign_rsaes_pkcs1_v1_5, ffi.NULL): self.__raise_from_status() if not lib.mongocrypt_init(self.__crypt): self.__raise_from_status()
def __init__(self, ctx, kms_provider, opts): """Abstracts libmongocrypt's mongocrypt_ctx_t type. :Parameters: - `ctx`: A mongocrypt_ctx_t. This MongoCryptContext takes ownership of the underlying mongocrypt_ctx_t. - `kms_provider`: The KMS provider. - `opts`: An optional class:`DataKeyOpts`. """ super(DataKeyContext, self).__init__(ctx) try: if kms_provider == 'aws': if opts is None or opts.master_key is None: raise ValueError( 'master_key is required for kms_provider: "aws"') if ('region' not in opts.master_key or 'key' not in opts.master_key): raise ValueError( 'master_key must include "region" and "key" for ' 'kms_provider: "aws"') region = str_to_bytes(opts.master_key['region']) key = str_to_bytes(opts.master_key['key']) if not lib.mongocrypt_ctx_setopt_masterkey_aws( ctx, region, len(region), key, len(key)): self._raise_from_status() if 'endpoint' in opts.master_key: endpoint = str_to_bytes(opts.master_key['endpoint']) if not lib.mongocrypt_ctx_setopt_masterkey_aws_endpoint( ctx, endpoint, len(endpoint)): self._raise_from_status() elif kms_provider == 'local': if not lib.mongocrypt_ctx_setopt_masterkey_local(ctx): self._raise_from_status() else: raise ValueError('unknown kms_provider: %s' % (kms_provider, )) if opts.key_alt_names: for key_alt_name in opts.key_alt_names: with MongoCryptBinaryIn(key_alt_name) as binary: if not lib.mongocrypt_ctx_setopt_key_alt_name( ctx, binary.bin): self._raise_from_status() if not lib.mongocrypt_ctx_datakey_init(ctx): self._raise_from_status() except Exception: # Destroy the context on error. self._close() raise
def __init__(self, ctx, command): """Abstracts libmongocrypt's mongocrypt_ctx_t type. :Parameters: - `ctx`: A mongocrypt_ctx_t. This MongoCryptContext takes ownership of the underlying mongocrypt_ctx_t. - `command`: The encoded BSON command to decrypt. """ super(DecryptionContext, self).__init__(ctx) try: with MongoCryptBinaryIn(command) as binary: if not lib.mongocrypt_ctx_decrypt_init(ctx, binary.bin): self._raise_from_status() except Exception: # Destroy the context on error. self._close() raise
def __init__(self, ctx, database, command): """Abstracts libmongocrypt's mongocrypt_ctx_t type. :Parameters: - `ctx`: A mongocrypt_ctx_t. This MongoCryptContext takes ownership of the underlying mongocrypt_ctx_t. - `database`: Optional, the name of the database. - `command`: The BSON command to encrypt. """ super(EncryptionContext, self).__init__(ctx) self.database = database try: with MongoCryptBinaryIn(command) as binary: database = str_to_bytes(database) if not lib.mongocrypt_ctx_encrypt_init( ctx, database, len(database), binary.bin): self._raise_from_status() except Exception: # Destroy the context on error. self._close() raise
def __init__(self, ctx, kms_provider, opts, callback): """Abstracts libmongocrypt's mongocrypt_ctx_t type. :Parameters: - `ctx`: A mongocrypt_ctx_t. This MongoCryptContext takes ownership of the underlying mongocrypt_ctx_t. - `kms_provider`: The KMS provider. - `opts`: An optional class:`DataKeyOpts`. - `callback`: A :class:`MongoCryptCallback`. """ super(DataKeyContext, self).__init__(ctx) try: if kms_provider not in ['aws', 'gcp', 'azure', 'local']: raise ValueError('unknown kms_provider: %s' % (kms_provider, )) if opts is None or opts.master_key is None: if kms_provider == 'local': master_key = {} else: raise ValueError( 'master_key is required for kms_provider: "%s"' % (kms_provider, )) else: master_key = opts.master_key.copy() if kms_provider == 'aws': if ('region' not in opts.master_key or 'key' not in opts.master_key): raise ValueError( 'master_key must include "region" and "key" for ' 'kms_provider: "aws"') elif kms_provider == 'azure': if ('keyName' not in opts.master_key or 'keyVaultEndpoint' not in opts.master_key): raise ValueError( 'master key must include "keyName" and ' '"keyVaultEndpoint" for kms_provider: "azure"') elif kms_provider == 'gcp': if ('projectId' not in opts.master_key or 'location' not in opts.master_key or 'keyRing' not in opts.master_key or 'keyName' not in opts.master_key): raise ValueError( 'master key must include "projectId", "location",' '"keyRing", and "keyName" for kms_provider: "gcp"') master_key['provider'] = kms_provider with MongoCryptBinaryIn(callback.bson_encode(master_key)) as mkey: if not lib.mongocrypt_ctx_setopt_key_encryption_key( ctx, mkey.bin): self._raise_from_status() if opts.key_alt_names: for key_alt_name in opts.key_alt_names: with MongoCryptBinaryIn(key_alt_name) as binary: if not lib.mongocrypt_ctx_setopt_key_alt_name( ctx, binary.bin): self._raise_from_status() if not lib.mongocrypt_ctx_datakey_init(ctx): self._raise_from_status() except Exception: # Destroy the context on error. self._close() raise