I have just ran into an obscure problem where softhsm2-util --import --aes results in a (seemingly) succesful import of an AES key into SoftHSM v2, but actually has an incorrect AES key length. This results in a corrupted AES key that cannot be used.
The test case was a 32-byte (AES-256) secret key while the import listed by PKCS#11 (pkcs11-tool) resulted in an AES key with a length less than 32 bytes.
For example, the following key will result in an incorrect AES key length of 25 (notice the 0A newline character):
This is incorrect behaviour as the C function fgets is intended for text strings, not binary strings, and stops whenever a newline character is encountered (even though the file is opened with rb attributes) leading to a silent corruption of the key. fread should probably be used instead to properly read the key in all conditions.
Furthermore, strlen is used in a similar manner to determine the AES key length, as if it were a text string while it is actually a binary byte array. As far as I know and have tested, the CKA_VALUE expects a byte array.
I have just ran into an obscure problem where
softhsm2-util --import --aes
results in a (seemingly) succesful import of an AES key into SoftHSM v2, but actually has an incorrect AES key length. This results in a corrupted AES key that cannot be used.The test case was a 32-byte (AES-256) secret key while the import listed by PKCS#11 (
pkcs11-tool
) resulted in an AES key with a length less than 32 bytes.For example, the following key will result in an incorrect AES key length of 25 (notice the
0A
newline character):While looking at the relevant source code, I noticed that
fgets
andstrlen
are used to read out the binary key file:This is incorrect behaviour as the C function
fgets
is intended for text strings, not binary strings, and stops whenever a newline character is encountered (even though the file is opened withrb
attributes) leading to a silent corruption of the key.fread
should probably be used instead to properly read the key in all conditions.Furthermore,
strlen
is used in a similar manner to determine the AES key length, as if it were a text string while it is actually a binary byte array. As far as I know and have tested, theCKA_VALUE
expects a byte array.