Skip to content

Instantly share code, notes, and snippets.

@williamcroberts
Created September 26, 2022 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save williamcroberts/b5639b844973d6200527166bce1f69d2 to your computer and use it in GitHub Desktop.
Save williamcroberts/b5639b844973d6200527166bce1f69d2 to your computer and use it in GitHub Desktop.
import aes key with tpm2-pytss
#!/usr/bin/env python3
import os
from tpm2_pytss import *
from tpm2_pytss.utils import wrap
esapi = ESAPI()
parent, parent_public = esapi.create_primary(None)[0:2]
secret = bytes(esapi.get_random(16))
print(f"Got Secret {secret}")
sensitive, public = TPM2B_SENSITIVE.symcipher_from_secret(secret)
sensitive.sensitiveArea.authValue = "password"
private = TPM2B_PRIVATE(sensitive.marshal())
# Importing WITHOUT any protections across bus interface
duplicate = esapi.import_(parent, TPM2B_DATA(), public, private, TPM2B_ENCRYPTED_SECRET(), TPMT_SYM_DEF_OBJECT(algorithm=TPM2_ALG.NULL))
# A Better way is to use the wrap functionality AND ENCRYPTED VERIFIED SESSIONS, this way
# nothing is visible on the bus, if your threat model requires it.
# symdef = TPMT_SYM_DEF_OBJECT(algorithm=TPM2_ALG.AES)
# symdef.mode.sym = TPM2_ALG.CFB
# symdef.keyBits.sym = 128
# enckey, duplicate, outsymseed = wrap(parent_public.publicArea, public, private, b"", symdef)
# duplicate = esapi.import_(parent, enckey, public, duplicate, outsymseed, symdef)
# This is failing tpm2_pytss.TSS2_Exception.TSS2_Exception: tpm:parameter(3):the type of the value is not appropriate for the use
# TODO Debug
key_handle = esapi.load(parent, duplicate, public)
iv = os.urandom(16)
try:
# Should not work without a password
cipher_text = esapi.encrypt_decrypt(key_handle, False, TPM2_ALG.CFB, iv, "my secret")[0]
except TSS2_Exception:
pass
esapi.tr_set_auth(key_handle, "password")
cipher_text = esapi.encrypt_decrypt(key_handle, False, TPM2_ALG.CFB, iv, "my secret")[0]
print(f"Got CipherText: {cipher_text}")
plain_text = esapi.encrypt_decrypt(key_handle, True, TPM2_ALG.CFB, iv, cipher_text)[0]
print(f"Got PlainText: {bytes(plain_text).decode()}")
print("PlainText expected: my secret")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment