Exemple #1
0
def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_url=VAULT_URL, credential=credential)
    try:
        # Let's create keys with RSA and EC type. If the key
        # already exists in the Key Vault, then a new version of the key is created.
        print("\n1. Create Key")
        rsa_key = client.create_rsa_key("rsaKeyName", hsm=False)
        ec_key = client.create_ec_key("ecKeyName", hsm=False)
        print("Key with name '{0}' was created of type '{1}'.".format(rsa_key.name, rsa_key.key_material.kty))
        print("Key with name '{0}' was created of type '{1}'.".format(ec_key.name, ec_key.key_material.kty))

        # The ec key is no longer needed. Need to delete it from the Key Vault.
        print("\n2. Delete a Key")
        key = client.delete_key(rsa_key.name)
        time.sleep(20)
        print("Key with name '{0}' was deleted on date {1}.".format(key.name, key.deleted_date))

        # We accidentally deleted the rsa key. Let's recover it.
        # A deleted key can only be recovered if the Key Vault is soft-delete enabled.
        print("\n3. Recover Deleted  Key")
        recovered_key = client.recover_deleted_key(rsa_key.name)
        print("Recovered Key with name '{0}'.".format(recovered_key.name))

        # Let's delete ec key now.
        # If the keyvault is soft-delete enabled, then for permanent deletion deleted key needs to be purged.
        client.delete_key(ec_key.name)

        # To ensure key is deleted on the server side.
        print("\nDeleting EC Key...")
        time.sleep(20)

        # To ensure permanent deletion, we might need to purge the key.
        print("\n4. Purge Deleted Key")
        client.purge_deleted_key(ec_key.name)
        print("EC Key has been permanently deleted.")

    except HttpResponseError as e:
        if "(NotSupported)" in e.message:
            print("\n{0} Please enable soft delete on Key Vault to perform this operation.".format(e.message))
        else:
            print("\nrun_sample has caught an error. {0}".format(e.message))

    finally:
        print("\nrun_sample done")
def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_url=VAULT_URL, credential=credential)
    try:
        # Let's create a Key of type RSA.
        # if the key already exists in the Key Vault, then a new version of the key is created.
        print("\n1. Create Key")
        key = client.create_key("keyName", "RSA")
        print("Key with name '{0}' created with key type '{1}'".format(
            key.name, key.key_material.kty))

        # Backups are good to have, if in case keys gets deleted accidentally.
        # For long term storage, it is ideal to write the backup to a file.
        print("\n1. Create a backup for an existing Key")
        key_backup = client.backup_key(key.name)
        print("Backup created for key with name '{0}'.".format(key.name))

        # The rsa key is no longer in use, so you delete it.
        client.delete_key(key.name)

        # To ensure key is deleted on the server side.
        print("\nDeleting key...")
        time.sleep(20)
        print("Deleted Key with name '{0}'".format(key.name))

        # In future, if the key is required again, we can use the backup value to restore it in the Key Vault.
        print("\n2. Restore the key using the backed up key bytes")
        key = client.restore_key(key_backup)
        print("Restored Key with name '{0}'".format(key.name))

    except HttpResponseError as e:
        print("\nrun_sample has caught an error. {0}".format(e.message))

    finally:
        print("\nrun_sample done")
class KeyVaultKeys:
    def __init__(self):
        # DefaultAzureCredential() expects the following environment variables:
        # * AZURE_CLIENT_ID
        # * AZURE_CLIENT_SECRET
        # * AZURE_TENANT_ID
        credential = DefaultAzureCredential()
        self.key_client = KeyClient(vault_url=os.environ["AZURE_PROJECT_URL"],
                                    credential=credential)

        self.key_name = "key-name-" + uuid.uuid1().hex

    def create_rsa_key(self):
        print("Creating an RSA key...")
        self.key_client.create_rsa_key(name=self.key_name,
                                       size=2048,
                                       hsm=False)
        print("\tdone")

    def get_key(self):
        print("Getting a key...")
        key = self.key_client.get_key(name=self.key_name)
        print("\tdone, key: %s." % key.name)

    def delete_key(self):
        print("Deleting a key...")
        deleted_key = self.key_client.delete_key(name=self.key_name)
        print("\tdone: " + deleted_key.name)

    def run(self):
        print("")
        print("------------------------")
        print("Key Vault - Keys\nIdentity - Credential")
        print("------------------------")
        print("1) Create a key")
        print("2) Get that key")
        print("3) Delete that key (Clean up the resource)")
        print("")

        try:
            self.create_rsa_key()
            self.get_key()
        finally:
            self.delete_key()
Exemple #4
0
    print("\n.. Get a Key by its name")
    rsa_key = client.get_key(rsa_key.name)
    print("Key with name '{0}' was found.".format(rsa_key.name))

    # Let's say we want to update the expiration time for the EC key and disable the key to be usable
    # for cryptographic operations. The update method allows the user to modify the metadata (key attributes)
    # associated with a key previously stored within Key Vault.
    print("\n.. Update a Key by name")
    expires = datetime.datetime.utcnow() + datetime.timedelta(days=365)
    updated_ec_key = client.update_key_properties(ec_key.name,
                                                  ec_key.properties.version,
                                                  expires=expires,
                                                  enabled=False)
    print("Key with name '{0}' was updated on date '{1}'".format(
        updated_ec_key.name, updated_ec_key.properties.updated))
    print("Key with name '{0}' was updated to expire on '{1}'".format(
        updated_ec_key.name, updated_ec_key.properties.expires))

    # The RSA key is no longer used, need to delete it from the Key Vault.
    print("\n.. Delete Keys")
    deleted_ec_key = client.delete_key(ec_key.name)
    deleted_rsa_key = client.delete_key(rsa_key.name)
    print("Deleted key '{0}'".format(deleted_ec_key.name))
    print("Deleted key '{0}'".format(deleted_rsa_key.name))

except HttpResponseError as e:
    print("\nrun_sample has caught an error. {0}".format(e.message))

finally:
    print("\nrun_sample done")
    # the Key Vault with the new key size.
    new_key = client.create_rsa_key(rsa_key.name, hsm=False, size=3072)
    print(
        "New version was created for Key with name '{0}' with the updated size."
        .format(new_key.name))

    # You should have more than one version of the rsa key at this time. Lets print all the versions of this key.
    print("\n.. List versions of a key using its name")
    key_versions = client.list_key_versions(rsa_key.name)
    for key in key_versions:
        print("Key '{0}' has version: '{1}'".format(key.name, key.version))

    # Both the rsa key and ec key are not needed anymore. Let's delete those keys.
    print("\n.. Delete the created keys...")
    for key_name in (ec_key.name, rsa_key.name):
        client.delete_key(key_name)
    time.sleep(10)

    # You can list all the deleted and non-purged keys, assuming Key Vault is soft-delete enabled.
    print("\n.. List deleted keys from the Key Vault (requires soft-delete)")
    deleted_keys = client.list_deleted_keys()
    for deleted_key in deleted_keys:
        print("Key with name '{0}' has recovery id '{1}'".format(
            deleted_key.name, deleted_key.recovery_id))

except HttpResponseError as e:
    if "(NotSupported)" in e.message:
        print(
            "\n{0} Please enable soft delete on Key Vault to perform this operation."
            .format(e.message))
    else:
def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_url=VAULT_URL, credential=credential)
    try:
        # Let's create keys with RSA and EC type. If the key
        # already exists in the Key Vault, then a new version of the key is created.
        print("\n1. Create Key")
        rsa_key = client.create_rsa_key("rsaKeyName", hsm=False)
        ec_key = client.create_ec_key("ecKeyName", hsm=False)
        print("Key with name '{0}' was created of type '{1}'.".format(
            rsa_key.name, rsa_key.key_material.kty))
        print("Key with name '{0}' was created of type '{1}'.".format(
            ec_key.name, ec_key.key_material.kty))

        # You need to check the type of all the keys in the vault.
        # Let's list the keys and print their key types.
        # List operations don 't return the keys with their type information.
        # So, for each returned key we call get_key to get the key with its type information.
        print("\n2. List keys from the Key Vault")
        keys = client.list_keys()
        for key in keys:
            retrieved_key = client.get_key(key.name)
            print("Key with name '{0}' with type '{1}' was found.".format(
                retrieved_key.name, retrieved_key.key_material.kty))

        # The rsa key size now should now be 3072, default - 2048. So you want to update the key in Key Vault to ensure
        # it reflects the new key size. Calling create_rsa_key on an existing key creates a new version of the key in
        # the Key Vault with the new key size.
        new_key = client.create_rsa_key(rsa_key.name, hsm=False, size=3072)
        print(
            "New version was created for Key with name '{0}' with the updated size."
            .format(new_key.name))

        # You should have more than one version of the rsa key at this time. Lets print all the versions of this key.
        print("\n3. List versions of the key using its name")
        key_versions = client.list_key_versions(rsa_key.name)
        for key in key_versions:
            print("RSA Key with name '{0}' has version: '{1}'".format(
                key.name, key.version))

        # Both the rsa key and ec key are not needed anymore. Let's delete those keys.
        client.delete_key(rsa_key.name)
        client.delete_key(ec_key.name)

        # To ensure key is deleted on the server side.
        print("\nDeleting keys...")
        time.sleep(20)

        # You can list all the deleted and non-purged keys, assuming Key Vault is soft-delete enabled.
        print("\n3. List deleted keys from the Key Vault")
        deleted_keys = client.list_deleted_keys()
        for deleted_key in deleted_keys:
            print("Key with name '{0}' has recovery id '{1}'".format(
                deleted_key.name, deleted_key.recovery_id))

    except HttpResponseError as e:
        if "(NotSupported)" in e.message:
            print(
                "\n{0} Please enable soft delete on Key Vault to perform this operation."
                .format(e.message))
        else:
            print("\nrun_sample has caught an error. {0}".format(e.message))

    finally:
        print("\nrun_sample done")
def run_sample():
    # Instantiate a key client that will be used to call the service.
    # Notice that the client is using default Azure credentials.
    # To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
    # 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
    VAULT_URL = os.environ["VAULT_URL"]
    credential = DefaultAzureCredential()
    client = KeyClient(vault_url=VAULT_URL, credential=credential)
    try:
        # Let's create an RSA key with size 2048, hsm disabled and optional key_operations of encrypt, decrypt.
        # if the key already exists in the Key Vault, then a new version of the key is created.
        print("\n1. Create an RSA Key")
        key_size = 2048
        key_ops = [
            "encrypt", "decrypt", "sign", "verify", "wrapKey", "unwrapKey"
        ]
        key_name = "rsaKeyName"
        rsa_key = client.create_rsa_key(key_name,
                                        size=key_size,
                                        hsm=False,
                                        key_operations=key_ops)
        print("RSA Key with name '{0}' created of type '{1}'.".format(
            rsa_key.name, rsa_key.key_material.kty))

        # Let's create an Elliptic Curve key with algorithm curve type P-256.
        # if the key already exists in the Key Vault, then a new version of the key is created.
        print("\n1. Create an EC Key")
        key_curve = "P-256"
        key_name = "ECKeyName"
        ec_key = client.create_ec_key(key_name, curve=key_curve, hsm=False)
        print("EC Key with name '{0}' created of type '{1}'.".format(
            ec_key.name, ec_key.key_material.kty))

        # Let's get the rsa key details using its name
        print("\n2. Get a Key using it's name")
        rsa_key = client.get_key(rsa_key.name)
        print("Key with name '{0}' was found.".format(rsa_key.name))

        # Let's say we want to update the expiration time for the EC key and disable the key to be useable for cryptographic operations.
        # The update method allows the user to modify the metadata (key attributes) associated with a key previously stored within Key Vault.
        print("\n3. Update a Key by name")
        expires = datetime.datetime.utcnow() + datetime.timedelta(days=365)
        updated_ec_key = client.update_key(ec_key.name,
                                           ec_key.version,
                                           expires=expires,
                                           enabled=False)
        print("Key with name '{0}' was updated on date '{1}'".format(
            updated_ec_key.name, updated_ec_key.updated))
        print("Key with name '{0}' was updated to expire on '{1}'".format(
            updated_ec_key.name, updated_ec_key.expires))

        # The RSA key is no longer used, need to delete it from the Key Vault.
        print("\n4. Delete Key")
        deleted_key = client.delete_key(rsa_key.name)
        print("Deleting Key..")
        print("Key with name '{0}' was deleted.".format(deleted_key.name))

    except HttpResponseError as e:
        print("\nrun_sample has caught an error. {0}".format(e.message))

    finally:
        print("\nrun_sample done")
Exemple #8
0
credential = DefaultAzureCredential()
client = KeyClient(vault_endpoint=VAULT_ENDPOINT, credential=credential)
try:
    # Let's create a Key of type RSA.
    # if the key already exists in the Key Vault, then a new version of the key is created.
    print("\n.. Create Key")
    key = client.create_key("keyName", "RSA")
    print("Key with name '{0}' created with key type '{1}'".format(
        key.name, key.key_type))

    # Backups are good to have, if in case keys gets deleted accidentally.
    # For long term storage, it is ideal to write the backup to a file.
    print("\n.. Create a backup for an existing Key")
    key_backup = client.backup_key(key.name)
    print("Backup created for key with name '{0}'.".format(key.name))

    # The rsa key is no longer in use, so you delete it.
    print("\n.. Delete the key")
    client.delete_key(key.name)

    # In future, if the key is required again, we can use the backup value to restore it in the Key Vault.
    print("\n.. Restore the key using the backed up key bytes")
    key = client.restore_key_backup(key_backup)
    print("Restored Key with name '{0}'".format(key.name))

except HttpResponseError as e:
    print("\nrun_sample has caught an error. {0}".format(e.message))

finally:
    print("\nrun_sample done")
# 'AZURE_CLIENT_SECRET' and 'AZURE_TENANT_ID' are set with the service principal credentials.
VAULT_URL = os.environ["VAULT_URL"]
credential = DefaultAzureCredential()
client = KeyClient(vault_url=VAULT_URL, credential=credential)
try:
    print("\n.. Create keys")
    rsa_key = client.create_rsa_key("rsaKeyName", hsm=False)
    ec_key = client.create_ec_key("ecKeyName", hsm=False)
    print("Created key '{0}' of type '{1}'.".format(rsa_key.name,
                                                    rsa_key.key_material.kty))
    print("Created key '{0}' of type '{1}'.".format(ec_key.name,
                                                    ec_key.key_material.kty))

    print("\n.. Delete the keys")
    for key_name in (ec_key.name, rsa_key.name):
        deleted_key = client.delete_key(key_name)
        print("Deleted key '{0}'".format(deleted_key.name))

    time.sleep(20)

    print("\n.. Recover a deleted key")
    recovered_key = client.recover_deleted_key(rsa_key.name)
    print("Recovered key '{0}'".format(recovered_key.name))

    # deleting the recovered key so it doesn't outlast this script
    time.sleep(20)
    client.delete_key(recovered_key.name)
    time.sleep(20)

    print("\n.. Purge keys")
    for key_name in (ec_key.name, rsa_key.name):