Skip to content
Portada » Blog » AES Encryption and Decryption with Pico HSM

AES Encryption and Decryption with Pico HSM

Pico HSM can generate AES secret keys and encrypt or decrypt data with CBC. OpenSC does not expose AES support through the sc-hsm driver, so this guide uses the sc-hsm-embedded module.

First, set up the tool:

alias sc-tool=pkcs11-tool --module /path/to/libsc-hsm-pkcs11.so

Secret Key Generation

Pico HSM supports 128-, 192-, and 256-bit AES keys. To generate a 256-bit key:

$ sc-tool -l --pin 648219 --keygen --key-type AES:32 --id 12 --label "AES32"
Using slot 0 with a present token (0x1)
Key generated:
Secret Key Object; AES length 32
	label:		AES32
	ID:			12
	Usage:	encrypt, decrypt
	Access:	sensitive, always sensitive, never extractable, local

For 128 bits, use --key-type aes:16; for 192 bits, use aes:24; for 256 bits, use aes:32.

Because the sc-hsm driver does not expose AES keys, pkcs15-tool -D does not list them. Use this command instead:

$ sc-tool -l --pin 648219 --list-object --type secrkey
Using slot 0 with a present token (0x1)
Secret Key Object; AES length 32
  label:		AES32
  ID:			12
  Usage:		encrypt, decrypt
  Access:		sensitive, always sensitive, never extractable, local

Encryption and Decryption

After generating an AES key, use it to encrypt or decrypt data:

$ echo "This is a text." | sc-tool -l --pin 648219 --encrypt --id 12 --mechanism aes-cbc > crypted.aes

The file crypted.aes contains the ciphertext produced with the generated key.

To decrypt the message, run the inverse operation:

$ cat crypted.aes | sc-tool -l --pin 648219 --decrypt --id 12 --mechanism aes-cbc
Using slot 0 with a present token (0x1)
Using decrypt algorithm AES-CBC

This is a text.

AES-CBC processes data in 16-byte blocks, so the input length must be a multiple of 16 bytes. Pad shorter input before encryption.