Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

softHSM2 AES Key Type Issue #191

Open
blueaxions opened this issue Jan 19, 2025 · 0 comments
Open

softHSM2 AES Key Type Issue #191

blueaxions opened this issue Jan 19, 2025 · 0 comments

Comments

@blueaxions
Copy link

Hello,

I'm testing a softHSM2 setup with the following code on rhel 9.4 system running in FIPS mode:

import pkcs11
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

# Initialize PKCS#11 library and connect to SoftHSM
lib = pkcs11.lib("/usr/local/lib/softhsm/libsofthsm2.so") # Adjust path if necessary
token = lib.get_token(token_label='MyToken') # Replace with your token label

with token.open(rw=True, user_pin="your_pin") as session:
    # Generate a symmetric key
    key = session.generate_key(pkcs11.KeyType.AES, 256, label="MySymmetricKey", template={Attribute.SENSITIVE: False, Attribute.EXTRACTABLE: True,}, store=True)

    # Encrypt some data
    data = b"Hello, world!"
    iv = os.urandom(16)
    cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
    encryptor = cipher.encryptor()
    ciphertext = encryptor.update(data) + encryptor.finalize()

    # Decrypt the data
    decryptor = cipher.decryptor()
    plaintext = decryptor.update(ciphertext) + decryptor.finalize()

    print("Plaintext:", plaintext)

When I run the above code, I get the following key type error:

TypeError: memoryview: a bytes-like object is required, not 'SecretKey'

While I understand that the AES Cipher() method doesn't like the key format, I don't know how to convert the key from session.generate_key() method to a format that's acceptable.

Thanks in advance!

Best,
PE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant