Python generate data key

12 Python code examples are found related to " generate data key". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: helpers.py    From Telethon with MIT License 6 votes vote down vote up
def generate_key_data_from_nonce(server_nonce, new_nonce):
    """Generates the key data corresponding to the given nonce"""
    server_nonce = server_nonce.to_bytes(16, 'little', signed=True)
    new_nonce = new_nonce.to_bytes(32, 'little', signed=True)
    hash1 = sha1(new_nonce + server_nonce).digest()
    hash2 = sha1(server_nonce + new_nonce).digest()
    hash3 = sha1(new_nonce + new_nonce).digest()

    key = hash1 + hash2[:12]
    iv = hash2[12:20] + hash3 + new_nonce[:4]
    return key, iv


# endregion

# region Custom Classes 
Example 2
Source File: kms.py    From jdcloud-cli with Apache License 2.0 6 votes vote down vote up
def generate_data_key(self):
        client_factory = ClientFactory('kms')
        client = client_factory.get(self.app)
        if client is None:
            return

        try:
            from jdcloud_sdk.services.kms.apis.GenerateDataKeyRequest import GenerateDataKeyRequest
            params_dict = collect_user_args(self.app)
            headers = collect_user_headers(self.app)
            req = GenerateDataKeyRequest(params_dict, headers)
            resp = client.send(req)
            Printer.print_result(resp)
        except ImportError:
            print('{"error":"This api is not supported, please use the newer version"}')
        except Exception as e:
            print(e) 
Example 3
Source File: credstash.py    From credstash with Apache License 2.0 5 votes vote down vote up
def generate_key_data(self, number_of_bytes):
        try:
            kms_response = self.kms.generate_data_key(
                KeyId=self.key_id, EncryptionContext=self.encryption_context, NumberOfBytes=number_of_bytes
            )
        except Exception as e:
            raise KmsError("Could not generate key using KMS key %s (Details: %s)" % (self.key_id, str(e)))
        return kms_response['Plaintext'], kms_response['CiphertextBlob'] 
Example 4
Source File: base.py    From aws-encryption-sdk-python with Apache License 2.0 5 votes vote down vote up
def generate_data_key(self, algorithm, encryption_context):
        """Generates and returns data key for use encrypting message.

        :param algorithm: Algorithm on which to base data key
        :type algorithm: aws_encryption_sdk.identifiers.Algorithm
        :param dict encryption_context: Encryption context to use in encryption
        :returns: Generated data key
        :rtype: aws_encryption_sdk.structures.DataKey
        """
        _LOGGER.info("generating data key with encryption context: %s", encryption_context)
        generated_data_key = self._generate_data_key(algorithm=algorithm, encryption_context=encryption_context)
        aws_encryption_sdk.internal.utils.source_data_key_length_check(
            source_data_key=generated_data_key, algorithm=algorithm
        )
        return generated_data_key 
Example 5
Source File: id_generator.py    From RAFCON with Eclipse Public License 1.0 5 votes vote down vote up
def generate_semantic_data_key(used_semantic_keys):
    """ Create a new and unique semantic data key

    :param list used_semantic_keys: Handed list of keys already in use
    :rtype: str
    :return: semantic_data_id
    """
    semantic_data_id_counter = -1
    while True:
        semantic_data_id_counter += 1
        if "semantic data key " + str(semantic_data_id_counter) not in used_semantic_keys:
            break
    return "semantic data key " + str(semantic_data_id_counter) 
Example 6
Source File: kms_client.py    From tencentcloud-cli with Apache License 2.0 5 votes vote down vote up
def doGenerateDataKey(argv, arglist):
    g_param = parse_global_arg(argv)
    if "help" in argv:
        show_help("GenerateDataKey", g_param[OptionsDefine.Version])
        return

    param = {
        "KeyId": argv.get("--KeyId"),
        "KeySpec": argv.get("--KeySpec"),
        "NumberOfBytes": Utils.try_to_json(argv, "--NumberOfBytes"),
        "EncryptionContext": argv.get("--EncryptionContext"),

    }
    cred = credential.Credential(g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey])
    http_profile = HttpProfile(
        reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
        reqMethod="POST",
        endpoint=g_param[OptionsDefine.Endpoint]
    )
    profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
    mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
    client = mod.KmsClient(cred, g_param[OptionsDefine.Region], profile)
    client._sdkVersion += ("_CLI_" + __version__)
    models = MODELS_MAP[g_param[OptionsDefine.Version]]
    model = models.GenerateDataKeyRequest()
    model.from_json_string(json.dumps(param))
    rsp = client.GenerateDataKey(model)
    result = rsp.to_json_string()
    jsonobj = None
    try:
        jsonobj = json.loads(result)
    except TypeError as e:
        jsonobj = json.loads(result.decode('utf-8')) # python3.3
    FormatOutput.output("action", jsonobj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter]) 
Example 7
Source File: kms_client.py    From tencentcloud-sdk-python with Apache License 2.0 5 votes vote down vote up
def GenerateDataKey(self, request):
        """本接口生成一个数据密钥,您可以用这个密钥进行本地数据的加密。

        :param request: Request instance for GenerateDataKey.
        :type request: :class:`tencentcloud.kms.v20190118.models.GenerateDataKeyRequest`
        :rtype: :class:`tencentcloud.kms.v20190118.models.GenerateDataKeyResponse`

        """
        try:
            params = request._serialize()
            body = self.call("GenerateDataKey", params)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.GenerateDataKeyResponse()
                model._deserialize(response["Response"])
                return model
            else:
                code = response["Response"]["Error"]["Code"]
                message = response["Response"]["Error"]["Message"]
                reqid = response["Response"]["RequestId"]
                raise TencentCloudSDKException(code, message, reqid)
        except Exception as e:
            if isinstance(e, TencentCloudSDKException):
                raise
            else:
                raise TencentCloudSDKException(e.message, e.message) 
Example 8
Source File: kms_20160120.py    From alibabacloud-python-sdk-v2 with Apache License 2.0 5 votes vote down vote up
def generate_data_key(
            self,
            encryption_context=None,
            key_id=None,
            key_spec=None,
            number_of_bytes=None):
        api_request = APIRequest('GenerateDataKey', 'GET', 'https', 'RPC', 'query')
        api_request._params = {
            "EncryptionContext": encryption_context,
            "KeyId": key_id,
            "KeySpec": key_spec,
            "NumberOfBytes": number_of_bytes}
        return self._handle_request(api_request).result 
Example 9
Source File: layer1.py    From aws-extender with MIT License 4 votes vote down vote up
def generate_data_key(self, key_id, encryption_context=None,
                          number_of_bytes=None, key_spec=None,
                          grant_tokens=None):
        """
        Generates a secure data key. Data keys are used to encrypt and
        decrypt data. They are wrapped by customer master keys.

        :type key_id: string
        :param key_id: Unique identifier of the key. This can be an ARN, an
            alias, or a globally unique identifier.

        :type encryption_context: map
        :param encryption_context: Name/value pair that contains additional
            data to be authenticated during the encryption and decryption
            processes that use the key. This value is logged by AWS CloudTrail
            to provide context around the data encrypted by the key.

        :type number_of_bytes: integer
        :param number_of_bytes: Integer that contains the number of bytes to
            generate. Common values are 128, 256, 512, 1024 and so on. 1024 is
            the current limit.

        :type key_spec: string
        :param key_spec: Value that identifies the encryption algorithm and key
            size to generate a data key for. Currently this can be AES_128 or
            AES_256.

        :type grant_tokens: list
        :param grant_tokens: A list of grant tokens that represent grants which
            can be used to provide long term permissions to generate a key.

        """
        params = {'KeyId': key_id, }
        if encryption_context is not None:
            params['EncryptionContext'] = encryption_context
        if number_of_bytes is not None:
            params['NumberOfBytes'] = number_of_bytes
        if key_spec is not None:
            params['KeySpec'] = key_spec
        if grant_tokens is not None:
            params['GrantTokens'] = grant_tokens
        response = self.make_request(action='GenerateDataKey',
                                     body=json.dumps(params))
        if response.get('CiphertextBlob') is not None:
            response['CiphertextBlob'] = base64.b64decode(
                response['CiphertextBlob'].encode('utf-8'))
        if response.get('Plaintext') is not None:
            response['Plaintext'] = base64.b64decode(
                response['Plaintext'].encode('utf-8'))
        return response 
Example 10
Source File: layer1.py    From aws-extender with MIT License 4 votes vote down vote up
def generate_data_key_without_plaintext(self, key_id,
                                            encryption_context=None,
                                            key_spec=None,
                                            number_of_bytes=None,
                                            grant_tokens=None):
        """
        Returns a key wrapped by a customer master key without the
        plaintext copy of that key. To retrieve the plaintext, see
        GenerateDataKey.

        :type key_id: string
        :param key_id: Unique identifier of the key. This can be an ARN, an
            alias, or a globally unique identifier.

        :type encryption_context: map
        :param encryption_context: Name:value pair that contains additional
            data to be authenticated during the encryption and decryption
            processes.

        :type key_spec: string
        :param key_spec: Value that identifies the encryption algorithm and key
            size. Currently this can be AES_128 or AES_256.

        :type number_of_bytes: integer
        :param number_of_bytes: Integer that contains the number of bytes to
            generate. Common values are 128, 256, 512, 1024 and so on.

        :type grant_tokens: list
        :param grant_tokens: A list of grant tokens that represent grants which
            can be used to provide long term permissions to generate a key.

        """
        params = {'KeyId': key_id, }
        if encryption_context is not None:
            params['EncryptionContext'] = encryption_context
        if key_spec is not None:
            params['KeySpec'] = key_spec
        if number_of_bytes is not None:
            params['NumberOfBytes'] = number_of_bytes
        if grant_tokens is not None:
            params['GrantTokens'] = grant_tokens
        response = self.make_request(action='GenerateDataKeyWithoutPlaintext',
                                     body=json.dumps(params))
        if response.get('CiphertextBlob') is not None:
            response['CiphertextBlob'] = base64.b64decode(
                response['CiphertextBlob'].encode('utf-8'))
        return response 
Example 11
Source File: client.py    From boto3_type_annotations with MIT License 4 votes vote down vote up
def generate_data_key(self, KeyId: str, EncryptionContext: Dict = None, NumberOfBytes: int = None, KeySpec: str = None, GrantTokens: List = None) -> Dict:
        """
        Returns a data encryption key that you can use in your application to encrypt data locally. 
        You must specify the customer master key (CMK) under which to generate the data key. You must also specify the length of the data key using either the ``KeySpec`` or ``NumberOfBytes`` field. You must specify one field or the other, but not both. For common key lengths (128-bit and 256-bit symmetric keys), we recommend that you use ``KeySpec`` . To perform this operation on a CMK in a different AWS account, specify the key ARN or alias ARN in the value of the KeyId parameter.
        This operation returns a plaintext copy of the data key in the ``Plaintext`` field of the response, and an encrypted copy of the data key in the ``CiphertextBlob`` field. The data key is encrypted under the CMK specified in the ``KeyId`` field of the request. 
        We recommend that you use the following pattern to encrypt data locally in your application:
        * Use this operation (``GenerateDataKey`` ) to get a data encryption key. 
        * Use the plaintext data encryption key (returned in the ``Plaintext`` field of the response) to encrypt data locally, then erase the plaintext data key from memory. 
        * Store the encrypted data key (returned in the ``CiphertextBlob`` field of the response) alongside the locally encrypted data. 
        To decrypt data locally:
        * Use the  Decrypt operation to decrypt the encrypted data key into a plaintext copy of the data key. 
        * Use the plaintext data key to decrypt data locally, then erase the plaintext data key from memory. 
        To return only an encrypted copy of the data key, use  GenerateDataKeyWithoutPlaintext . To return a random byte string that is cryptographically secure, use  GenerateRandom .
        If you use the optional ``EncryptionContext`` field, you must store at least enough information to be able to reconstruct the full encryption context when you later send the ciphertext to the  Decrypt operation. It is a good practice to choose an encryption context that you can reconstruct on the fly to better secure the ciphertext. For more information, see `Encryption Context <http://docs.aws.amazon.com/kms/latest/developerguide/encryption-context.html>`__ in the *AWS Key Management Service Developer Guide* .
        The result of this operation varies with the key state of the CMK. For details, see `How Key State Affects Use of a Customer Master Key <http://docs.aws.amazon.com/kms/latest/developerguide/key-state.html>`__ in the *AWS Key Management Service Developer Guide* .
        See also: `AWS API Documentation <https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/GenerateDataKey>`_
        
        **Request Syntax**
        ::
          response = client.generate_data_key(
              KeyId='string',
              EncryptionContext={
                  'string': 'string'
              },
              NumberOfBytes=123,
              KeySpec='AES_256'|'AES_128',
              GrantTokens=[
                  'string',
              ]
          )
        
        **Response Syntax**
        ::
            {
                'CiphertextBlob': b'bytes',
                'Plaintext': b'bytes',
                'KeyId': 'string'
            }
        
        **Response Structure**
          - *(dict) --* 
            - **CiphertextBlob** *(bytes) --* 
              The encrypted data encryption key. When you use the HTTP API or the AWS CLI, the value is Base64-encdoded. Otherwise, it is not encoded.
            - **Plaintext** *(bytes) --* 
              The data encryption key. When you use the HTTP API or the AWS CLI, the value is Base64-encdoded. Otherwise, it is not encoded. Use this data key for local encryption and decryption, then remove it from memory as soon as possible.
            - **KeyId** *(string) --* 
              The identifier of the CMK under which the data encryption key was generated and encrypted.
        :type KeyId: string
        :param KeyId: **[REQUIRED]**
          The identifier of the CMK under which to generate and encrypt the data encryption key.
          To specify a CMK, use its key ID, Amazon Resource Name (ARN), alias name, or alias ARN. When using an alias name, prefix it with \"alias/\". To specify a CMK in a different AWS account, you must use the key ARN or alias ARN.
          For example:
          * Key ID: ``1234abcd-12ab-34cd-56ef-1234567890ab``
          * Key ARN: ``arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab``
          * Alias name: ``alias/ExampleAlias``
          * Alias ARN: ``arn:aws:kms:us-east-2:111122223333:alias/ExampleAlias``
          To get the key ID and key ARN for a CMK, use  ListKeys or  DescribeKey . To get the alias name and alias ARN, use  ListAliases .
        :type EncryptionContext: dict
        :param EncryptionContext:
          A set of key-value pairs that represents additional authenticated data.
          For more information, see `Encryption Context <http://docs.aws.amazon.com/kms/latest/developerguide/encryption-context.html>`__ in the *AWS Key Management Service Developer Guide* .
          - *(string) --*
            - *(string) --*
        :type NumberOfBytes: integer
        :param NumberOfBytes:
          The length of the data encryption key in bytes. For example, use the value 64 to generate a 512-bit data key (64 bytes is 512 bits). For common key lengths (128-bit and 256-bit symmetric keys), we recommend that you use the ``KeySpec`` field instead of this one.
        :type KeySpec: string
        :param KeySpec:
          The length of the data encryption key. Use ``AES_128`` to generate a 128-bit symmetric key, or ``AES_256`` to generate a 256-bit symmetric key.
        :type GrantTokens: list
        :param GrantTokens:
          A list of grant tokens.
          For more information, see `Grant Tokens <http://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#grant_token>`__ in the *AWS Key Management Service Developer Guide* .
          - *(string) --*
        :rtype: dict
        :returns:
        """
        pass 
Example 12
Source File: client.py    From boto3_type_annotations with MIT License 4 votes vote down vote up
def generate_data_key_without_plaintext(self, KeyId: str, EncryptionContext: Dict = None, KeySpec: str = None, NumberOfBytes: int = None, GrantTokens: List = None) -> Dict:
        """
        Returns a data encryption key encrypted under a customer master key (CMK). This operation is identical to  GenerateDataKey but returns only the encrypted copy of the data key. 
        To perform this operation on a CMK in a different AWS account, specify the key ARN or alias ARN in the value of the KeyId parameter.
        This operation is useful in a system that has multiple components with different degrees of trust. For example, consider a system that stores encrypted data in containers. Each container stores the encrypted data and an encrypted copy of the data key. One component of the system, called the *control plane* , creates new containers. When it creates a new container, it uses this operation (``GenerateDataKeyWithoutPlaintext`` ) to get an encrypted data key and then stores it in the container. Later, a different component of the system, called the *data plane* , puts encrypted data into the containers. To do this, it passes the encrypted data key to the  Decrypt operation, then uses the returned plaintext data key to encrypt data, and finally stores the encrypted data in the container. In this system, the control plane never sees the plaintext data key.
        The result of this operation varies with the key state of the CMK. For details, see `How Key State Affects Use of a Customer Master Key <http://docs.aws.amazon.com/kms/latest/developerguide/key-state.html>`__ in the *AWS Key Management Service Developer Guide* .
        See also: `AWS API Documentation <https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/GenerateDataKeyWithoutPlaintext>`_
        
        **Request Syntax**
        ::
          response = client.generate_data_key_without_plaintext(
              KeyId='string',
              EncryptionContext={
                  'string': 'string'
              },
              KeySpec='AES_256'|'AES_128',
              NumberOfBytes=123,
              GrantTokens=[
                  'string',
              ]
          )
        
        **Response Syntax**
        ::
            {
                'CiphertextBlob': b'bytes',
                'KeyId': 'string'
            }
        
        **Response Structure**
          - *(dict) --* 
            - **CiphertextBlob** *(bytes) --* 
              The encrypted data encryption key. When you use the HTTP API or the AWS CLI, the value is Base64-encdoded. Otherwise, it is not encoded.
            - **KeyId** *(string) --* 
              The identifier of the CMK under which the data encryption key was generated and encrypted.
        :type KeyId: string
        :param KeyId: **[REQUIRED]**
          The identifier of the customer master key (CMK) under which to generate and encrypt the data encryption key.
          To specify a CMK, use its key ID, Amazon Resource Name (ARN), alias name, or alias ARN. When using an alias name, prefix it with \"alias/\". To specify a CMK in a different AWS account, you must use the key ARN or alias ARN.
          For example:
          * Key ID: ``1234abcd-12ab-34cd-56ef-1234567890ab``
          * Key ARN: ``arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab``
          * Alias name: ``alias/ExampleAlias``
          * Alias ARN: ``arn:aws:kms:us-east-2:111122223333:alias/ExampleAlias``
          To get the key ID and key ARN for a CMK, use  ListKeys or  DescribeKey . To get the alias name and alias ARN, use  ListAliases .
        :type EncryptionContext: dict
        :param EncryptionContext:
          A set of key-value pairs that represents additional authenticated data.
          For more information, see `Encryption Context <http://docs.aws.amazon.com/kms/latest/developerguide/encryption-context.html>`__ in the *AWS Key Management Service Developer Guide* .
          - *(string) --*
            - *(string) --*
        :type KeySpec: string
        :param KeySpec:
          The length of the data encryption key. Use ``AES_128`` to generate a 128-bit symmetric key, or ``AES_256`` to generate a 256-bit symmetric key.
        :type NumberOfBytes: integer
        :param NumberOfBytes:
          The length of the data encryption key in bytes. For example, use the value 64 to generate a 512-bit data key (64 bytes is 512 bits). For common key lengths (128-bit and 256-bit symmetric keys), we recommend that you use the ``KeySpec`` field instead of this one.
        :type GrantTokens: list
        :param GrantTokens:
          A list of grant tokens.
          For more information, see `Grant Tokens <http://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#grant_token>`__ in the *AWS Key Management Service Developer Guide* .
          - *(string) --*
        :rtype: dict
        :returns:
        """
        pass