diff --git a/docs/api-reference/overview/examples/retrieve-secrets.mdx b/docs/api-reference/overview/examples/retrieve-secrets.mdx index 1ac4edb0c..813aae9e7 100644 --- a/docs/api-reference/overview/examples/retrieve-secrets.mdx +++ b/docs/api-reference/overview/examples/retrieve-secrets.mdx @@ -108,6 +108,90 @@ getSecrets(); ``` + + +```Python +import requests +import base64 +from Cryptodome.Cipher import AES + +BASE_URL = "http://app.infisical.com" + + +def decrypt(ciphertext, iv, tag, secret): + secret = bytes(secret, "utf-8") + iv = base64.standard_b64decode(iv) + tag = base64.standard_b64decode(tag) + ciphertext = base64.standard_b64decode(ciphertext) + + cipher = AES.new(secret, AES.MODE_GCM, iv) + cipher.update(tag) + cleartext = cipher.decrypt(ciphertext).decode('utf-8') + return cleartext + + +def get_secrets(): + service_token = "" + service_token_secret = service_token[service_token.rindex(".") + 1:] + + # 1. Get your Infisical Token data + service_token_data = requests.get( + f"{BASE_URL}/api/v2/service-token", + headers={ + "Authorization": f"Bearer {service_token}" + } + ).json() + + # 2. Get secrets for your project and environment + data = requests.get( + f"{BASE_URL}/api/v2/secrets", + params={ + "environment": service_token_data["environment"], + "workspaceId": service_token_data["workspace"] + }, + headers={ + "Authorization": f"Bearer {service_token}" + } + ).json() + + encrypted_secrets = data.get("secrets") + + # 3. Decrypt the (encrypted) project key with the key from your Infisical Token + project_key = decrypt( + ciphertext=service_token_data.get("encryptedKey"), + iv=service_token_data.get("iv"), + tag=service_token_data.get("tag"), + secret=service_token_secret + ) + + # 4. Decrypt the (encrypted) secrets + secrets = [] + for secret in encrypted_secrets: + secret_key = decrypt( + ciphertext=secret["secretKeyCiphertext"], + iv=secret["secretKeyIV"], + tag=secret["secretKeyTag"], + secret=project_key + ) + + secret_value = decrypt( + ciphertext=secret["secretValueCiphertext"], + iv=secret["secretValueIV"], + tag=secret["secretValueTag"], + secret=project_key + ) + + secrets.append({ + "secret_key": secret_key, + "secret_value": secret_value, + }) + + print("secrets:", secrets) + + +get_secrets() +``` +