OpenSC/OpenSC — pull request #296 by philipWendland (2014-10-11 18:23:17+00:00)
Title: pkcs15-lib: prkey_bits - use private key field length

sc_pkcs15init_keybits can behave erroneously with certain EC keys. It basically strips leading most significant zero-bits. It seems that EC keys (privateD), however, can have valid zeros at the beginning which legitimately count to the field length.
So, one can NOT calculate reliable key lengths only by looking at the privateD component of the private key. You have to look at the field length specified in the parameters.

---
I did some tests on the current (to be fixed) version using prime256v1. Different private keys of the same curve behave differently, depending on the privateD component. While some did produce correct lengths (the ones which had exactly one leading zero), others did not (calculated key lengths of 257, or even <256).
The fixed version works with all keys, also the ones that failed before.

Where does prkey_bits() get called from?
Only when trying to store private keys:
```
[*@* src] $ grep --include="*.c" -r -n "prkey_bits"
pkcs15init/pkcs15-lib.c:115:static int	prkey_bits(struct sc_pkcs15_card *, struct sc_pkcs15_prkey *);
pkcs15init/pkcs15-lib.c:1400:	keybits = prkey_bits(p15card, &key);
pkcs15init/pkcs15-lib.c:2138:prkey_bits(struct sc_pkcs15_card *p15card, struct sc_pkcs15_prkey *key)
```