if any key has NULL bytes (or zeros) at the end, how the unwrap knows how many padded bytes are added?
PKCS#11 doesn't unpad unless you indicate PKCS#7 padding using _PAD
. Decryption will just leave all the zero bytes. This is not a problem if you either know the size in advance, or if you've padded it yourself using a scheme that is compatible with the zero padding such as PKCS#7 compatible padding. PKCS#11's zero padding operation doesn't pad if the input is already a multiple of the block size, after all.
Also, I'm the beginner for cryptography so I'm not sure whether any secret key can end up with zeros or not. Please clarify me this also.
It can, but if you unwrap then the key size of any wrapped secret key is generally known in advance, so it shouldn't matter. You will have to provide the key size yourself in the template during unwrapping (if you use ECB or CBC without _PAD
option). To quote the information in the mechanism page of PKCS#11 v2.40, section 2.8.5 AES-CBC:
For wrapping, the mechanism encrypts the value of the CKA_VALUE attribute of the key that is wrapped, padded on the trailing end with up to block size minus one null bytes so that the resulting length is a multiple of the block size. The output data is the same length as the padded input data. It does not wrap the key type, key length, or any other information about the key; the application must convey these separately.
For unwrapping, the mechanism decrypts the wrapped key, and truncates the result according to the CKA_KEY_TYPE attribute of the template and, if it has one, and the key type supports it, the CKA_VALUE_LEN attribute of the template. The mechanism contributes the result as the CKA_VALUE attribute of the new key; other attributes required by the key type must be specified in the template.
(emphasis mine)
Private keys commonly use ASN.1/DER encoding, so if you wrap those you can calculate the size of the key using the first length field of the initial TLV value. Then you - or the token - can remove the spurious zero valued bytes.
Generally I'd avoid wrapping AES-192 keys, they are just a nuisance as the key size is not a multiple of the block size.
Moreover, I'd be extremely cautious when it comes to (asymmetric) private keys. Many tokens will happily use ECB or zero-IV CBC to encrypt private keys, and that may actually leak information about those wrapped private keys.
PKCS#11 is an old standard, and many of the careless decisions made at the beginning are likely to perpetuate far into the future.