Python create secret

60 Python code examples are found related to " create secret". 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: kubernetes_tools.py    From paasta with Apache License 2.0 7 votes vote down vote up
def create_secret(
    kube_client: KubeClient,
    secret: str,
    service: str,
    secret_provider: BaseSecretProvider,
) -> None:
    service = sanitise_kubernetes_name(service)
    sanitised_secret = sanitise_kubernetes_name(secret)
    kube_client.core.create_namespaced_secret(
        namespace="paasta",
        body=V1Secret(
            metadata=V1ObjectMeta(
                name=f"paasta-secret-{service}-{sanitised_secret}",
                labels={
                    "yelp.com/paasta_service": service,
                    "paasta.yelp.com/service": service,
                },
            ),
            data={
                secret: base64.b64encode(
                    secret_provider.decrypt_secret_raw(secret)
                ).decode("utf-8")
            },
        ),
    ) 
Example 2
Source File: kubernetes_tools.py    From paasta with Apache License 2.0 7 votes vote down vote up
def create_kubernetes_secret_signature(
    kube_client: KubeClient, secret: str, service: str, secret_signature: str
) -> None:
    service = sanitise_kubernetes_name(service)
    secret = sanitise_kubernetes_name(secret)
    kube_client.core.create_namespaced_config_map(
        namespace="paasta",
        body=V1ConfigMap(
            metadata=V1ObjectMeta(
                name=f"paasta-secret-{service}-{secret}-signature",
                labels={
                    "yelp.com/paasta_service": service,
                    "paasta.yelp.com/service": service,
                },
            ),
            data={"signature": secret_signature},
        ),
    ) 
Example 3
Source File: controller.py    From dask-gateway with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def create_secret_if_not_exists(self, cluster):
        name = cluster["metadata"]["name"]
        namespace = cluster["metadata"]["namespace"]
        secret = self.make_secret(name)
        secret["metadata"]["ownerReferences"] = [
            {
                "apiVersion": cluster["apiVersion"],
                "kind": cluster["kind"],
                "name": cluster["metadata"]["name"],
                "uid": cluster["metadata"]["uid"],
            }
        ]

        self.log.info("Creating new credentials for cluster %s.%s", namespace, name)
        try:
            await self.core_client.create_namespaced_secret(namespace, secret)
        except ApiException as exc:
            if exc.status != 409:
                raise

        return secret["metadata"]["name"] 
Example 4
Source File: container.py    From django-cloud-deploy with Apache License 2.0 6 votes vote down vote up
def create_secret(self,
                      secret_data: kubernetes.client.V1Secret,
                      configuration: (
                          kubernetes.client.configuration.Configuration) = None,
                      namespace: str = 'default'):
        """Create a Kubernetes Secret.

        Kubernetes Secrets are intended to hold sensitive information. They are
        accessible inside Pods.

        Args:
            secret_data: Definition of the secret.
            configuration: A Kubernetes configuration which has access to the
                cluster for the service. If not set, it will use the default
                kubernetes configuration.
            namespace: Namespace of the service.
        """
        api_client = kubernetes.client.ApiClient(configuration)
        api_instance = kubernetes.client.CoreV1Api(api_client)
        api_instance.create_namespaced_secret(namespace=namespace,
                                              body=secret_data) 
Example 5
Source File: kms.py    From jdcloud-cli with Apache License 2.0 6 votes vote down vote up
def create_secret_version(self):
        client_factory = ClientFactory('kms')
        client = client_factory.get(self.app)
        if client is None:
            return

        try:
            from jdcloud_sdk.services.kms.apis.CreateSecretVersionRequest import CreateSecretVersionRequest
            params_dict = collect_user_args(self.app)
            headers = collect_user_headers(self.app)
            req = CreateSecretVersionRequest(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 6
Source File: pod.py    From jdcloud-cli with Apache License 2.0 6 votes vote down vote up
def create_secret(self):
        client_factory = ClientFactory('pod')
        client = client_factory.get(self.app)
        if client is None:
            return

        try:
            from jdcloud_sdk.services.pod.apis.CreateSecretRequest import CreateSecretRequest
            params_dict = collect_user_args(self.app)
            headers = collect_user_headers(self.app)
            req = CreateSecretRequest(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 7
Source File: util.py    From elastic with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_docker_image_secret(args):
    configure_yaml_docker(args.image_name)
    commands = [
        format_command(
            f"""
             kubectl create secret
             docker-registry pet-docker-secret
             --docker-server={args.server}
             --docker-username={args.username}
             --docker-password={args.password}
             --docker-email='test@test.com'"""
        )
    ]
    run_commands(commands)
    logger.info("Docker image registered..")


# Deploy AKS cluster 
Example 8
Source File: install.py    From infrabox with MIT License 6 votes vote down vote up
def create_secret(self, name, namespace, data):
        secrets_dir = os.path.join(self.args.o, 'infrabox', 'templates', 'secrets')

        if not os.path.exists(secrets_dir):
            os.mkdir(secrets_dir)

        d = {}

        for k, v in data.iteritems():
            d[k] = base64.b64encode(v)

        s = {
            "apiVersion": "v1",
            "kind": "Secret",
            "metadata": {
                "name": name,
                "namespace": namespace
            },
            "type": "Opaque",
            "data": d
        }

        o = os.path.join(secrets_dir, namespace + '-' + name + '.yaml')
        with open(o, 'w') as outfile:
            yaml.dump(s, outfile, default_flow_style=False) 
Example 9
Source File: intercom.py    From SempoBlockchain with GNU General Public License v3.0 6 votes vote down vote up
def create_intercom_secret(user_id, device_type):
    """
    Function to generate an intercom secret using HMAC for identity verification for customer support.

    :param user_id: Sempo UserID to generate a unique hash.
    :param device_type: Web, Android or iOS
    :return:
    """
    if device_type is 'WEB':
        secret = current_app.config['INTERCOM_WEB_SECRET']
    elif device_type is 'ANDROID':
        secret = current_app.config['INTERCOM_ANDROID_SECRET']
    else:
        return Exception('No device_type provided')

    secret_bytes = secret.encode('ascii')
    id_bytes = str(user_id).encode('ascii')
    result = hmac.new(secret_bytes, id_bytes, hashlib.sha256).hexdigest()

    return result 
Example 10
Source File: mcg.py    From ocs-ci with MIT License 6 votes vote down vote up
def create_aws_backingstore_secret(self, name):
        """
        Creates a secret for NooBaa's backingstore
        Args:
            name: The name to be given to the secret

        Returns:
            OCS: The secret resource

        """
        bs_secret_data = templating.load_yaml(constants.MCG_BACKINGSTORE_SECRET_YAML)
        bs_secret_data['metadata']['name'] += f'-{name}'
        bs_secret_data['metadata']['namespace'] = self.namespace
        bs_secret_data['data']['AWS_ACCESS_KEY_ID'] = base64.urlsafe_b64encode(
            self.aws_access_key_id.encode('UTF-8')
        ).decode('ascii')
        bs_secret_data['data']['AWS_SECRET_ACCESS_KEY'] = base64.urlsafe_b64encode(
            self.aws_access_key.encode('UTF-8')
        ).decode('ascii')
        return create_resource(**bs_secret_data) 
Example 11
Source File: protocol.py    From huawei-lpv2 with MIT License 6 votes vote down vote up
def create_secret_key(mac_address: str) -> bytes:
    mac_address_key = (mac_address.replace(":", "") + "0000").encode()

    mixed_secret_key = [
        ((key1_byte << 4) ^ key2_byte) & 0xFF
        for key1_byte, key2_byte in zip(bytes.fromhex(SECRET_KEY_1), bytes.fromhex(SECRET_KEY_2))
    ]

    mixed_secret_key_hash = hashlib.sha256(bytes(mixed_secret_key)).digest()

    final_mixed_key = [
        ((mixed_key_hash_byte >> 6) ^ mac_address_byte) & 0xFF
        for mixed_key_hash_byte, mac_address_byte in zip(mixed_secret_key_hash, mac_address_key)
    ]

    return hashlib.sha256(bytes(final_mixed_key)).digest()[:AES_KEY_SIZE] 
Example 12
Source File: scan_engine_api.py    From vm-console-client-python with MIT License 6 votes vote down vote up
def create_shared_secret(self, **kwargs):  # noqa: E501
        """Scan Engine Shared Secret  # noqa: E501

        Returns the current valid shared secret or generates a new shared secret. The endpoint returns an existing shared secret if one was previously generated and it has not yet expired. Conversely, the endpoint will generate and return a new shared secret for either of the following conditions: a shared secret was not previously generated or the previously-generated shared secret has expired. The shared secret is valid for 60 minutes from the moment it is generated.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True
        >>> thread = api.create_shared_secret(async_req=True)
        >>> result = thread.get()

        :param async_req bool
        :return: str
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('async_req'):
            return self.create_shared_secret_with_http_info(**kwargs)  # noqa: E501
        else:
            (data) = self.create_shared_secret_with_http_info(**kwargs)  # noqa: E501
            return data 
Example 13
Source File: secret.py    From resolwe with Apache License 2.0 6 votes vote down vote up
def create_secret(self, value, contributor, metadata=None, expires=None):
        """Create a new secret, returning its handle.

        :param value: Secret value to store
        :param contributor: User owning the secret
        :param metadata: Optional metadata dictionary (must be JSON serializable)
        :param expires: Optional date/time of expiry (defaults to None, which means that
            the secret never expires)
        :return: Secret handle
        """
        if metadata is None:
            metadata = {}

        secret = self.create(
            value=value, contributor=contributor, metadata=metadata, expires=expires,
        )
        return str(secret.handle) 
Example 14
Source File: KubernetesResources.py    From k8s-mongo-operator with GNU Affero General Public License v3.0 6 votes vote down vote up
def createSecret(cls, secret_name: str, namespace: str, secret_data: Dict[str, str],
                     labels: Optional[Dict[str, str]] = None) -> client.V1Secret:
        """
        Creates a secret object.
        :param secret_name: The name of the secret.
        :param namespace: The name space for the secret.
        :param secret_data: The secret data.
        :param labels: Optional labels for this secret, defaults to the default labels (see `cls.createDefaultLabels`).
        :return: The secret model object.
        """
        return client.V1Secret(
            metadata=client.V1ObjectMeta(
                name=secret_name,
                namespace=namespace,
                labels=cls.createDefaultLabels(secret_name) if labels is None else labels
            ),
            string_data=secret_data,
        ) 
Example 15
Source File: manager.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def create_or_update_secret(self, name, body, reraise=False):
        try:
            return self.create_secret(name=name, body=body), True
        except ApiException:
            try:
                return self.update_secret(name=name, body=body), False
            except ApiException as e:
                if reraise:
                    raise PolyaxonK8SError("Connection error: %s" % e) from e
                else:
                    logger.error("K8S error: {}".format(e)) 
Example 16
Source File: ssm_client.py    From tencentcloud-cli with Apache License 2.0 5 votes vote down vote up
def doCreateSecret(argv, arglist):
    g_param = parse_global_arg(argv)
    if "help" in argv:
        show_help("CreateSecret", g_param[OptionsDefine.Version])
        return

    param = {
        "SecretName": argv.get("--SecretName"),
        "VersionId": argv.get("--VersionId"),
        "Description": argv.get("--Description"),
        "KmsKeyId": argv.get("--KmsKeyId"),
        "SecretBinary": argv.get("--SecretBinary"),
        "SecretString": argv.get("--SecretString"),

    }
    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.SsmClient(cred, g_param[OptionsDefine.Region], profile)
    client._sdkVersion += ("_CLI_" + __version__)
    models = MODELS_MAP[g_param[OptionsDefine.Version]]
    model = models.CreateSecretRequest()
    model.from_json_string(json.dumps(param))
    rsp = client.CreateSecret(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 17
Source File: secret_behaviors.py    From barbican with Apache License 2.0 5 votes vote down vote up
def create_secret(self, model, extra_headers=None, omit_headers=None,
                      use_auth=True, user_name=None, admin=None):
        """Create a secret from the data in the model.

        :param model: The metadata used to create the secret
        :param extra_headers: Optional HTTP headers to add to the request
        :param omit_headers: headers to delete before making the request
        :param use_auth: Boolean for whether to send authentication headers
        :param user_name: The user name used to create the secret
        :param admin: The user with permissions to delete the secrets
        :return: A tuple containing the response from the create
        and the href to the newly created secret
        """

        resp = self.client.post('secrets', request_model=model,
                                extra_headers=extra_headers,
                                omit_headers=omit_headers, use_auth=use_auth,
                                user_name=user_name)

        # handle expected JSON parsing errors for unauthenticated requests
        if resp.status_code == 401 and not use_auth:
            return resp, None

        returned_data = self.get_json(resp)
        secret_ref = returned_data.get('secret_ref')
        if secret_ref:
            if admin is None:
                admin = user_name
            self.created_entities.append((secret_ref, admin))
        return resp, secret_ref 
Example 18
Source File: __init__.py    From async-hvac with Apache License 2.0 5 votes vote down vote up
def create_role_secret_id(self, role_name, meta=None, cidr_list=None, wrap_ttl=None, mount_point='approle'):
        """
        POST /auth/<mount_point>/role/<role name>/secret-id
        """

        url = '/v1/auth/{0}/role/{1}/secret-id'.format(mount_point, role_name)
        params = {}
        if meta is not None:
            params['metadata'] = json.dumps(meta)
        if cidr_list is not None:
            params['cidr_list'] = cidr_list
        return await (await self._post(url, json=params, wrap_ttl=wrap_ttl)).json() 
Example 19
Source File: __init__.py    From async-hvac with Apache License 2.0 5 votes vote down vote up
def create_role_custom_secret_id(self, role_name, secret_id, meta=None, mount_point='approle'):
        """
        POST /auth/<mount_point>/role/<role name>/custom-secret-id
        """
        url = '/v1/auth/{0}/role/{1}/custom-secret-id'.format(mount_point, role_name)
        params = {
            'secret_id': secret_id
        }
        if meta is not None:
            params['meta'] = meta
        return await (await self._post(url, json=params)).json() 
Example 20
Source File: pavement.py    From GeoHealthCheck with MIT License 5 votes vote down vote up
def create_secret_key():
    """create secret key for SECRET_KEY in instance/config_site.py"""
    info('Secret key: \'%s\'' % codecs.encode(os.urandom(24), 'hex').decode())
    info('Copy/paste this key to set the SECRET_KEY')
    info('value in instance/config_site.py') 
Example 21
Source File: api.py    From MusicBoxApi with MIT License 5 votes vote down vote up
def createSecretKey(size):
    return binascii.hexlify(os.urandom(size))[:16]


# list去重 
Example 22
Source File: manager.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def create_secret(self, name, body):
        resp = self.k8s_api.create_namespaced_secret(
            namespace=self.namespace, body=body
        )
        logger.debug("Secret `{}` was created".format(name))
        return resp 
Example 23
Source File: concourse.py    From cc-utils with Apache License 2.0 5 votes vote down vote up
def create_image_pull_secret(
    credentials: GcrCredentials,
    image_pull_secret_name: str,
    namespace: str,
):
    """Create an image pull secret in the K8s cluster to allow pods to download images from gcr"""
    not_none(credentials)
    not_empty(image_pull_secret_name)
    not_empty(namespace)

    ctx = kube_ctx
    namespace_helper = ctx.namespace_helper()
    namespace_helper.create_if_absent(namespace)

    secret_helper = ctx.secret_helper()
    if not secret_helper.get_secret(image_pull_secret_name, namespace):
        secret_helper.create_gcr_secret(
            namespace=namespace,
            name=image_pull_secret_name,
            password=credentials.passwd(),
            user_name=credentials.username(),
            email=credentials.email(),
            server_url=credentials.host(),
        )

        service_account_helper = ctx.service_account_helper()
        service_account_helper.patch_image_pull_secret_into_service_account(
            name="default",
            namespace=namespace,
            image_pull_secret_name=image_pull_secret_name
        )


# Constants related to the MitM-Proxy installation.
# The name under which the config map will be stored in K8s 
Example 24
Source File: helper.py    From cc-utils with Apache License 2.0 5 votes vote down vote up
def create_gcr_secret(
        self,
        namespace: str,
        name: str,
        password: str,
        email: str,
        user_name: str='_json_key',
        server_url: str='https://eu.gcr.io'
      ):
        metadata = V1ObjectMeta(name=name, namespace=namespace)
        secret = V1Secret(metadata=metadata)

        auth = '{user}:{gcr_secret}'.format(
          user=user_name,
          gcr_secret=password
        )

        docker_config = {
          server_url: {
            'username': user_name,
            'email': email,
            'password': password,
            'auth': base64.b64encode(auth.encode('utf-8')).decode('utf-8')
          }
        }

        encoded_docker_config = base64.b64encode(
          json.dumps(docker_config).encode('utf-8')
        ).decode('utf-8')

        secret.data = {
          '.dockercfg': encoded_docker_config
        }
        secret.type = 'kubernetes.io/dockercfg'

        self.core_api.create_namespaced_secret(namespace=namespace, body=secret) 
Example 25
Source File: utils.py    From cc-utils with Apache License 2.0 5 votes vote down vote up
def create_basic_auth_secret(
    secret_name: str,
    namespace: str,
    basic_auth_cred: BasicAuthCred=None
):
    """ Creates a secret with the configured TLS certificates in the K8s cluster.
        Optionally adds credentials for Basic Authentication"""
    not_empty(secret_name)
    not_empty(namespace)

    ctx = kube_ctx
    namespace_helper = ctx.namespace_helper()
    namespace_helper.create_if_absent(namespace)

    secret_helper = ctx.secret_helper()
    if not secret_helper.get_secret(secret_name, namespace):
        ht = HtpasswdFile()
        ht.set_password(basic_auth_cred.user, basic_auth_cred.password)
        data = {
            'auth':ht.to_string().decode('utf-8'),
        }
        secret_helper.put_secret(
            name=secret_name,
            data=data,
            namespace=namespace,
        ) 
Example 26
Source File: lambda_function.py    From aws-encryption-workshop with MIT License 5 votes vote down vote up
def create_secret(service_client, arn, token):
    """Generate a new secret

    This method first checks for the existence of a secret for the passed in token. If one does not exist, it will generate a
    new secret and put it with the passed in token.

    Args:
        service_client (client): The secrets manager service client

        arn (string): The secret ARN or other identifier

        token (string): The ClientRequestToken associated with the secret version

    Raises:
        ValueError: If the current secret is not valid JSON

        KeyError: If the secret json does not contain the expected keys

    """
    # Make sure the current secret exists
    current_dict = get_secret_dict(service_client, arn, "AWSCURRENT")

    # Now try to get the secret version, if that fails, put a new secret
    try:
        get_secret_dict(service_client, arn, "AWSPENDING", token)
        logger.info("createSecret: Successfully retrieved secret for %s." % arn)
    except service_client.exceptions.ResourceNotFoundException:
        # Generate a random password
        passwd = service_client.get_random_password(ExcludeCharacters='/@"\'\\')
        current_dict['password'] = passwd['RandomPassword']

        # Put the secret
        service_client.put_secret_value(SecretId=arn, ClientRequestToken=token, SecretString=json.dumps(current_dict), VersionStages=['AWSPENDING'])
        logger.info("createSecret: Successfully put secret for ARN %s and version %s." % (arn, token)) 
Example 27
Source File: __init__.py    From nexmo-python with MIT License 5 votes vote down vote up
def create_secret(self, api_key, secret):
        body = {"secret": secret}
        return self._post_json(
            self.api_host, "/accounts/{api_key}/secrets".format(api_key=api_key), body
        ) 
Example 28
Source File: ssm_client.py    From tencentcloud-sdk-python with Apache License 2.0 5 votes vote down vote up
def CreateSecret(self, request):
        """创建新的凭据信息,通过KMS进行加密保护。每个Region最多可创建存储1000个凭据信息。

        :param request: Request instance for CreateSecret.
        :type request: :class:`tencentcloud.ssm.v20190923.models.CreateSecretRequest`
        :rtype: :class:`tencentcloud.ssm.v20190923.models.CreateSecretResponse`

        """
        try:
            params = request._serialize()
            body = self.call("CreateSecret", params)
            response = json.loads(body)
            if "Error" not in response["Response"]:
                model = models.CreateSecretResponse()
                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 29
Source File: utils.py    From amivapi with GNU Affero General Public License v3.0 5 votes vote down vote up
def create_token_secret_on_startup(app):
    """Create a token secret in the database if it doesn't exist.

    The secret key is stored in the database to ensure consistency.
    The database collection holding this key is called `config`.
    """
    with app.app_context():  # Context for db connection
        config = app.data.driver.db['config']
        result = config.find_one(
            {'TOKEN_SECRET': {'$exists': True, '$nin': [None, '']}})

        if result is None:
            config.insert_one({'TOKEN_SECRET': token_urlsafe()}) 
Example 30
Source File: pps_pb2_grpc.py    From python-pachyderm with Apache License 2.0 5 votes vote down vote up
def CreateSecret(self, request, context):
    # missing associated documentation comment in .proto file
    pass
    context.set_code(grpc.StatusCode.UNIMPLEMENTED)
    context.set_details('Method not implemented!')
    raise NotImplementedError('Method not implemented!') 
Example 31
Source File: pps.py    From python-pachyderm with Apache License 2.0 5 votes vote down vote up
def create_secret(self, secret_name, data, labels=None, annotations=None):
        """
        Creates a new secret.

        Params:

        * `secret_name`: The name of the secret to create.
        * `data`: A dict of string keys -> string or bytestring values to
        store in the secret. Each key must consist of alphanumeric characters,
        `-`, `_` or `.`.
        * `labels`: A dict of string keys -> string values representing the
        kubernetes labels to attach to the secret.
        * `annotations`: A dict representing the kubernetes annotations to
        attach to the secret.
        """

        encoded_data = {}
        for k, v in data.items():
            if isinstance(v, str):
                v = v.encode("utf8")
            encoded_data[k] = base64.b64encode(v).decode("utf8")

        f = json.dumps({
            "kind": "Secret",
            "apiVersion": "v1",
            "metadata": {
                "name": secret_name,
                "labels": labels,
                "annotations": annotations,
            },
            "data": encoded_data,
        }).encode("utf8")

        return self._req(Service.PPS, "CreateSecret", file=f) 
Example 32
Source File: passwords.py    From tripleo-common with Apache License 2.0 5 votes vote down vote up
def create_rndc_key_secret():
    # The rndc key secret is a base64-encoded hmac-sha256 value
    h = hmac.new(
        passlib.pwd.genword(length=_MIN_PASSWORD_SIZE).encode('utf-8'),
        msg=passlib.pwd.genword(length=_MIN_PASSWORD_SIZE).encode('utf-8'),
        digestmod=hashlib.sha256)
    return base64.b64encode(h.digest()).decode('utf-8') 
Example 33
Source File: mastermind.py    From cs101 with GNU General Public License v3.0 5 votes vote down vote up
def create_secret():
  """Create secret: four distinct letters from A-F."""
  c = [ "A", "B", "C", "D", "E", "F" ]
  secret = ""
  for i in range(4):
    letter = random.choice(c)
    c.remove(letter)
    secret = secret + letter
  return secret 
Example 34
Source File: KeyVaultUtil.py    From azure-linux-extensions with Apache License 2.0 5 votes vote down vote up
def create_secret(self, AccessToken, KeyVaultURL, secret_value, KeyEncryptionAlgorithm, DiskEncryptionKeyFileName):
        """
        create secret api https://msdn.microsoft.com/en-us/library/azure/dn903618.aspx
        https://mykeyvault.vault.azure.net/secrets/{secret-name}?api-version={api-version}
        """
        try:
            secret_name = str(uuid.uuid4())
            secret_keyvault_uri = self.urljoin(KeyVaultURL, "secrets", secret_name)
            self.logger.log("secret_keyvault_uri is: {0} and keyvault_uri is:{1}".format(secret_keyvault_uri, KeyVaultURL))
            if KeyEncryptionAlgorithm is None:
                request_content = '{{"value":"{0}","attributes":{{"enabled":"true"}},"tags":{{"DiskEncryptionKeyFileName":"{1}"}}}}'\
                    .format(str(secret_value), DiskEncryptionKeyFileName)
            else:
                request_content = '{{"value":"{0}","attributes":{{"enabled":"true"}},"tags":{{"DiskEncryptionKeyEncryptionAlgorithm":"{1}","DiskEncryptionKeyFileName":"{2}"}}}}'\
                    .format(str(secret_value), KeyEncryptionAlgorithm, DiskEncryptionKeyFileName)
            http_util = HttpUtil(self.logger)
            headers = {}
            headers["Content-Type"] = "application/json"
            headers["Authorization"] = "Bearer " + AccessToken
            result = http_util.Call(method='PUT', http_uri=secret_keyvault_uri + '?api-version=' + self.api_version, data=request_content, headers=headers)

            self.logger.log("{0} {1}".format(result.status, result.getheaders()))
            result_content = result.read()
            # Do NOT log the result_content. It contains the uploaded secret and we don't want that in the logs.
            result_json = json.loads(result_content)
            secret_id = result_json["id"]
            http_util.connection.close()
            if result.status != httplib.OK and result.status != httplib.ACCEPTED:
                self.logger.log("the result status failed.")
                return None
            return secret_id
        except Exception as e:
            self.logger.log("Failed to create_secret with error: {0}, stack trace: {1}".format(e, traceback.format_exc()))
            return None 
Example 35
Source File: app.py    From controller with MIT License 5 votes vote down vote up
def create_object_store_secret(self):
        try:
            self._scheduler.secret.get(self.id, 'objectstorage-keyfile')
        except KubeException:
            secret = self._scheduler.secret.get(
                settings.WORKFLOW_NAMESPACE, 'objectstorage-keyfile').json()
            self._scheduler.secret.create(self.id, 'objectstorage-keyfile', secret['data']) 
Example 36
Source File: cfn_rsakey_provider.py    From cfn-secret-provider with Apache License 2.0 5 votes vote down vote up
def create_or_update_secret(self, overwrite=False, new_secret=True):
        try:
            if new_secret:
                private_key, public_key = self.create_key()
            else:
                private_key, public_key = self.get_key()

            kwargs = {
                "Name": self.get("Name"),
                "KeyId": self.get("KeyAlias"),
                "Type": "SecureString",
                "Overwrite": overwrite,
                "Value": private_key,
            }
            if self.get("Description") != "":
                kwargs["Description"] = self.get("Description")

            response = self.ssm.put_parameter(**kwargs)
            version = response["Version"] if "Version" in response else 1

            self.set_attribute("Arn", self.arn)
            self.set_attribute("PublicKey", public_key)
            self.set_attribute("PublicKeyPEM", self.public_key_to_pem(private_key))
            self.set_attribute(
                "Hash", hashlib.md5(public_key.encode("utf-8")).hexdigest()
            )
            self.set_attribute("Version", version)

            if not ssm_parameter_name.equals(self.physical_resource_id, self.arn):
                # prevent CFN deleting a resource with identical Arns in different formats.
                self.physical_resource_id = self.arn
        except ClientError as e:
            self.physical_resource_id = "could-not-create"
            self.fail(str(e)) 
Example 37
Source File: utils.py    From shhh with MIT License 5 votes vote down vote up
def create_secret(passphrase: str,
                  secret: str,
                  expire: int,
                  tries: int,
                  haveibeenpwned: bool) -> Tuple[Dict, int]:
    """Create a secret.

    Args:
        passphrase (str): Passphrase needed to encrypt the secret.
        secret (str): Secret to encrypt.
        expire (int): Number of days the secret will be stored.
        tries (int): Number of tries to read the secret before it gets deleted.
        haveibeenpwned (bool): Passphrase has been checked with haveibeenpwned.

    """
    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    expiration_date = datetime.strptime(
        now, "%Y-%m-%d %H:%M:%S") + timedelta(days=expire)

    slug = _generate_unique_slug()
    Entries.create(slug_link=slug,
                   encrypted_text=Secret(secret.encode(), passphrase).encrypt(),
                   date_created=now,
                   date_expires=expiration_date,
                   tries=tries,
                   haveibeenpwned=haveibeenpwned)

    app.logger.info(f"{slug} created and expires on {expiration_date}")
    timez = datetime.now(timezone.utc).astimezone().tzname()
    return dict(
        status=Status.CREATED.value,
        details="Secret successfully created.",
        slug=slug,
        link=f"{request.url_root}r/{slug}",
        expires_on=f"{expiration_date.strftime('%Y-%m-%d at %H:%M')} {timez}"), 201 
Example 38
Source File: secrets.py    From calm-dsl with Apache License 2.0 5 votes vote down vote up
def create_secret(name, value):
    """Creates the secret"""

    secrets = get_secrets_names()
    if name in secrets:
        LOG.error("Secret {} already present !!!".format(name))
        return

    LOG.debug("Creating secret {}".format(name))
    Secret.create(name, value)
    LOG.info(highlight_text("Secret {} created".format(name))) 
Example 39
Source File: flash.py    From specter-diy with MIT License 5 votes vote down vote up
def create_new_secret(self, path):
        """Generate new secret and default PIN config"""
        # generate new and save
        secret = get_random_bytes(32)
        # save secret
        with open(path+"/secret","wb") as f:
            f.write(secret)
        # set pin object
        self.pin = None
        self._pin_attempts_max = 10
        self._pin_attempts_left = 10
        self.secret = secret
        self.save_state()
        return secret 
Example 40
Source File: custom.py    From azure-cli-extensions with MIT License 5 votes vote down vote up
def create_plan_secret(cmd, client, plan_name,
                       secret_name, secret_value, secret_note=None,
                       secret_filters=None, resource_group_name=None):
    plan = client.get(resource_group_name=resource_group_name, plan_name=plan_name)
    token = client.write_environments_action(resource_group_name=resource_group_name, plan_name=plan_name)
    data = {}
    data['secretName'] = secret_name
    data['value'] = secret_value
    data['notes'] = secret_note
    data['type'] = cs_api.SecretType.ENVIRONMENT_VARIABLE.value
    data['scope'] = cs_api.SecretScope.USER.value
    data['filters'] = secret_filters
    return cs_api.create_secret(token.access_token, plan.id, data, cli_ctx=cmd.cli_ctx) 
Example 41
Source File: _non_arm_apis.py    From azure-cli-extensions with MIT License 5 votes vote down vote up
def create_secret(access_token, plan_id, data, api_root=None, **_):
    url = f'{api_root}/secrets'
    headers = {'Authorization': f'Bearer {access_token}'}
    params = {'planId': plan_id}
    response = session.post(url, headers=headers, json=data, params=params)
    return response 
Example 42
Source File: netEaseEncode.py    From MusicBox with MIT License 5 votes vote down vote up
def createSecretKey(size):
    # 2中 os.urandom返回是个字符串。3中变成bytes。
    # 不过加密的目的是需要一个字符串。
    # 因为密钥之后会被加密到rsa中一起发送出去。
    # 所以即使是个固定的密钥也是可以的。

    # return (''.join(map(lambda xx: (hex(ord(xx))[2:]), os.urandom(size))))[0:16]
    return bytes(''.join(random.sample('1234567890qwertyuipasdfghjklzxcvbnm', 16)), 'utf-8') 
Example 43
Source File: vault_client.py    From airflow with Apache License 2.0 5 votes vote down vote up
def create_or_update_secret(self,
                                secret_path: str,
                                secret: dict,
                                method: Optional[str] = None,
                                cas: Optional[int] = None) -> Response:
        """
        Creates or updates secret.

        :param secret_path: The path of the secret.
        :type secret_path: str
        :param secret: Secret to create or update for the path specified
        :type secret: dict
        :param method: Optional parameter to explicitly request a POST (create) or PUT (update) request to
            the selected kv secret engine. If no argument is provided for this parameter, hvac attempts to
            intelligently determine which method is appropriate. Only valid for KV engine version 1
        :type method: str
        :param cas: Set the "cas" value to use a Check-And-Set operation. If not set the write will be
            allowed. If set to 0 a write will only be allowed if the key doesn't exist.
            If the index is non-zero the write will only be allowed if the key's current version
            matches the version specified in the cas parameter. Only valid for KV engine version 2.
        :type cas: int
        :rtype: requests.Response
        :return: The response of the create_or_update_secret request.

                 See https://hvac.readthedocs.io/en/stable/usage/secrets_engines/kv_v1.html
                 and https://hvac.readthedocs.io/en/stable/usage/secrets_engines/kv_v2.html for details.

        """
        if self.kv_engine_version == 2 and method:
            raise VaultError("The method parameter is only valid for version 1")
        if self.kv_engine_version == 1 and cas:
            raise VaultError("The cas parameter is only valid for version 2")
        if self.kv_engine_version == 1:
            response = self.client.secrets.kv.v1.create_or_update_secret(
                secret_path=secret_path, secret=secret, mount_point=self.mount_point, method=method)
        else:
            response = self.client.secrets.kv.v2.create_or_update_secret(
                secret_path=secret_path, secret=secret, mount_point=self.mount_point, cas=cas)
        return response 
Example 44
Source File: secret.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def create_secret(self, name, data, labels=None, driver=None):
        """
            Create a secret

            Args:
                name (string): Name of the secret
                data (bytes): Secret data to be stored
                labels (dict): A mapping of labels to assign to the secret
                driver (DriverConfig): A custom driver configuration. If
                    unspecified, the default ``internal`` driver will be used

            Returns (dict): ID of the newly created secret
        """
        if not isinstance(data, bytes):
            data = data.encode('utf-8')

        data = base64.b64encode(data)
        if six.PY3:
            data = data.decode('ascii')
        body = {
            'Data': data,
            'Name': name,
            'Labels': labels
        }

        if driver is not None:
            if utils.version_lt(self._version, '1.31'):
                raise errors.InvalidVersion(
                    'Secret driver is only available for API version > 1.31'
                )

            body['Driver'] = driver

        url = self._url('/secrets/create')
        return self._result(
            self._post_json(url, data=body), True
        ) 
Example 45
Source File: kdc.py    From dcos-kafka-service with Apache License 2.0 5 votes vote down vote up
def create_keytab_secret(args: dict, kerberos=None):

    if not kerberos:
        kerberos = sdk_auth.KerberosEnvironment(persist=True)

    principals = parse_principals(args.principals_file)
    kerberos.add_principals(principals)

    if args.secret_name:
        kerberos.set_keytab_path(args.secret_name, args.binary_secret)

    kerberos.finalize()

    log.info("KDC cluster successfully deployed") 
Example 46
Source File: rhopenshift.py    From wrapanapi with MIT License 5 votes vote down vote up
def create_secret(self, namespace, **kwargs):
        """Creates Secret entity using REST API.

        Args:
            namespace: openshift namespace where entity has to be created
            kwargs: Secret data
        Return: data if entity was created w/o errors
        """
        secret = self.kclient.V1Secret(**kwargs)
        secret_name = secret.to_dict()['metadata']['name']
        self.logger.info("creating secret %s", secret_name)
        output = self.k_api.create_namespaced_secret(namespace=namespace, body=secret)
        self.wait_secret_exist(namespace=namespace, name=secret_name)
        return output 
Example 47
Source File: cce.py    From python-otcclient with MIT License 5 votes vote down vote up
def create_secret():
        if OtcConfig.CLUSTER:
            cce.convertClusterNameToId()            
        
        url = "https://" + OtcConfig.DEFAULT_HOST + "/api/v1/namespaces/" + OtcConfig.NAMESPACE + "/secrets"
        req = utils_templates.create_request("cce_create_secret")
        #print(req)
        ret = utils_http.post(url, req)
        cce.otcOutputHandler().print_output(ret,mainkey="")    
        return ret 
Example 48
Source File: resource_manager.py    From cloudify-manager with Apache License 2.0 5 votes vote down vote up
def create_secret(key, secret, tenant):
    sm = get_storage_manager()
    timestamp = utils.get_formatted_timestamp()
    new_secret = models.Secret(
        id=key,
        value=encrypt(secret['value']),
        created_at=timestamp,
        updated_at=timestamp,
        visibility=secret['visibility'],
        is_hidden_value=secret['is_hidden_value'],
        tenant=tenant
    )
    created_secret = sm.put(new_secret)
    return created_secret 
Example 49
Source File: paasta_deployd_steps.py    From paasta with Apache License 2.0 5 votes vote down vote up
def create_secret_json_file(context, secret_name, service, signature):
    secret = {
        "environments": {
            "devc": {"ciphertext": "ScrambledNonsense", "signature": signature}
        }
    }
    if not os.path.exists(os.path.join(context.soa_dir, service, "secrets")):
        os.makedirs(os.path.join(context.soa_dir, service, "secrets"))

    with open(
        os.path.join(context.soa_dir, service, "secrets", f"{secret_name}.json"), "w"
    ) as secret_file:
        json.dump(secret, secret_file) 
Example 50
Source File: K8sSecret.py    From kubernetes-py with Apache License 2.0 5 votes vote down vote up
def create_image_pull_secret(config=None, prefix=None, name=None, data=None):
        s = Secret()

        if name is not None:
            s.name = "{0}-docker-{1}".format(name, str(uuid.uuid4().hex[:5]))
        elif name is None and prefix is not None:
            s.name = "{0}-docker-{1}".format(prefix, str(uuid.uuid4().hex[:5]))
        else:
            s.name = "docker-{0}".format(str(uuid.uuid4().hex[:5]))

        s.dockerconfigjson = data
        k8s = K8sSecret(config=config, name=s.name)
        k8s.model = s
        k8s.create()
        return k8s 
Example 51
Source File: tenants_utils.py    From inference-model-manager with Apache License 2.0 5 votes vote down vote up
def create_secret(name, cert, id_token):
    cert_secret_metadata = k8s_client.V1ObjectMeta(name=CERT_SECRET_NAME)
    cert_secret_data = {"ca.crt": cert}
    cert_secret = k8s_client.V1Secret(api_version="v1", data=cert_secret_data,
                                      kind="Secret", metadata=cert_secret_metadata,
                                      type="Opaque")
    api_instance = get_k8s_api_client(id_token)
    try:
        response = api_instance.create_namespaced_secret(namespace=name,
                                                         body=cert_secret)
    except ApiException as apiException:
        raise KubernetesCreateException('secret', apiException)

    logger.info('Secret {} created'.format(CERT_SECRET_NAME))
    return response 
Example 52
Source File: create_application_insights.py    From takeoff with GNU General Public License v3.0 5 votes vote down vote up
def create_databricks_secret(self, application_name: str, instrumentation_secret: Secret):
        """Create Databricks secret for Application Insights connectivity

        Args:
            application_name: Name of the application
            instrumentation_secret: Secret to connect to Application Insights
        """
        db = CreateDatabricksSecretFromValue(self.env, self.config)
        db._create_scope(application_name)
        db._add_secrets(application_name, [instrumentation_secret]) 
Example 53
Source File: barbican.py    From rally-openstack with Apache License 2.0 5 votes vote down vote up
def create_secret(self, name=None, payload=None,
                      payload_content_type=None, payload_content_encoding=None,
                      algorithm=None, bit_length=None, secret_type=None,
                      mode=None, expiration=None):
        """Create Secret

        :param name: A friendly name for the secret
        :param payload: The unecrypted secret data
        :param payload_content_type: the format/type of the secret data
        :param payload_content_encoding: the encoding of the secret data
        :param algorithm: the algorithm associated with this secret key
        :param bit_length: The bit length of this secret key
        :param mode: the algorigthm mode used with this secret key
        :param secret_type: The secret type for this secret key
        :param exipration: the expiration time of the secret in ISO8601
           format
        :returns: a new secret object
        """
        name = name or self.generate_random_name()
        val = self._clients.barbican().secrets.create(
            name=name, payload=payload,
            payload_content_type=payload_content_type,
            payload_content_encoding=payload_content_encoding,
            algorithm=algorithm, bit_length=bit_length, mode=mode,
            secret_type=secret_type, expiration=expiration)
        val.store()
        return val 
Example 54
Source File: secrets_client.py    From fandogh-cli with MIT License 5 votes vote down vote up
def create_secret(name, secret_type, fields):
    response = get_session().post(base_secrets_url,
                                  json={
                                      "name": name,
                                      "type": secret_type,
                                      "fields": parse_key_values(fields)
                                  },
                                  )
    if response.status_code != 200:
        raise get_exception(response)
    else:
        return response.json() 
Example 55
Source File: create_secret.py    From python-docs-samples with Apache License 2.0 5 votes vote down vote up
def create_secret(project_id, secret_id):
    """
    Create a new secret with the given name. A secret is a logical wrapper
    around a collection of secret versions. Secret versions hold the actual
    secret material.
    """

    # Import the Secret Manager client library.
    from google.cloud import secretmanager

    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the parent project.
    parent = client.project_path(project_id)

    # Create the secret.
    response = client.create_secret(parent, secret_id, {
        'replication': {
            'automatic': {},
        },
    })

    # Print the new secret name.
    print('Created secret: {}'.format(response.name))
# [END secretmanager_create_secret]

    return response 
Example 56
Source File: twx.py    From twx with MIT License 5 votes vote down vote up
def create_secret_chat(self, user: User, on_success: callable):
        """
        Create a secret chat with the user.
        :param user: User to start secret chat with.
        :param on_success: Will return the chat and meta information.
        """
        pass 
Example 57
Source File: _proxy.py    From openstacksdk with Apache License 2.0 5 votes vote down vote up
def create_secret(self, **attrs):
        """Create a new secret from attributes

        :param dict attrs: Keyword arguments which will be used to create a
                           :class:`~openstack.key_manager.v1.secret.Secret`,
                           comprised of the properties on the Order class.

        :returns: The results of secret creation
        :rtype: :class:`~openstack.key_manager.v1.secret.Secret`
        """
        return self._create(_secret.Secret, **attrs) 
Example 58
Source File: libvirt.py    From avocado-vt with GNU General Public License v2.0 4 votes vote down vote up
def create_secret(params, remote_args=None):
    """
    Create a secret with 'virsh secret-define'

    :param params: Test run params
    :param remote_args: Parameters for remote host
    :return: UUID of the secret
    """
    sec_usage_type = params.get("sec_usage", "volume")
    sec_desc = params.get("sec_desc", "secret_description")
    sec_ephemeral = params.get("sec_ephemeral", "no") == "yes"
    sec_private = params.get("sec_private", "no") == "yes"
    sec_uuid = params.get("sec_uuid", "")
    sec_volume = params.get("sec_volume", "/path/to/volume")
    sec_name = params.get("sec_name", "secret_name")
    sec_target = params.get("sec_target", "secret_target")

    supporting_usage_types = ['volume', 'ceph', 'iscsi', 'tls', 'vtpm']
    if sec_usage_type not in supporting_usage_types:
        raise exceptions.TestError("Supporting secret usage types are: %s" %
                                   supporting_usage_types)

    # prepare secret xml
    sec_xml = secret_xml.SecretXML("no", "yes")
    # set common attributes
    sec_xml.description = sec_desc
    sec_xml.usage = sec_usage_type
    if sec_ephemeral:
        sec_xml.secret_ephmeral = "yes"
    if sec_private:
        sec_xml.secret_private = "yes"
    if sec_uuid:
        sec_xml.uuid = sec_uuid
    sec_xml.usage = sec_usage_type
    # set specific attributes for different usage type
    if sec_usage_type in ['volume']:
        sec_xml.volume = sec_volume
    if sec_usage_type in ['ceph', 'tls', 'vtpm']:
        sec_xml.usage_name = sec_name
    if sec_usage_type in ['iscsi']:
        sec_xml.target = sec_target
    sec_xml.xmltreefile.write()
    logging.debug("The secret xml is: %s" % sec_xml)

    # define the secret and get its uuid
    if remote_args:
        server_ip = remote_args.get("remote_ip", "")
        server_user = remote_args.get("remote_user", "")
        server_pwd = remote_args.get("remote_pwd", "")
        if not all([server_ip, server_user, server_pwd]):
            raise exceptions.TestError("remote_[ip|user|pwd] are necessary!")
        remote_virsh_session = virsh.VirshPersistent(**remote_args)
        remote.scp_to_remote(server_ip, '22', server_user, server_pwd,
                             sec_xml.xml, sec_xml.xml, limit="",
                             log_filename=None, timeout=600, interface=None)
        ret = remote_virsh_session.secret_define(sec_xml.xml)
        remote_virsh_session.close_session()
    else:
        ret = virsh.secret_define(sec_xml.xml)
    check_exit_status(ret)
    try:
        sec_uuid = re.findall(r".+\S+(\ +\S+)\ +.+\S+",
                              ret.stdout_text)[0].lstrip()
    except IndexError:
        raise exceptions.TestError("Fail to get newly created secret uuid")

    return sec_uuid