cloudflare / circl

CIRCL: Cloudflare Interoperable Reusable Cryptographic Library
http://blog.cloudflare.com/introducing-circl
Other
1.22k stars 136 forks source link

panic: unmarshalling 0 first byte private keys #439

Closed krissully closed 1 year ago

krissully commented 1 year ago

UnmarshalBinary always results in a panic when running for a private key where the first byte is 0.

Private key hex generated using the following commands:

openssl ecparam -name secp384r1 -genkey -out private-key.pem openssl ec -in private-key.pem -text -noout

Example code:

b, err := hex.DecodeString("00856367ab1d115e98552abf9b3f75662fa42dbc5120229d399fec512e4f1e0cbd170032adf8bf045535850edded2ac6d6") if err != nil { log.Fatalln("error decoding private key hex") }

suite := oprf.SuiteP384
privateKey := oprf.PrivateKey{}
err = privateKey.UnmarshalBinary(suite, b)
if err != nil {
    log.Fatalln("error unmarshalling private key")
}
armfazh commented 1 year ago

The issue is that the size of P384 keys must be 48 bytes.

The zero byte at the beginning is due to the ANS1 encoding of octet strings. Look at this link

To get the right value, use the asn1 parser:

$ openssl ec -in key.pem | openssl asn1parse 
read EC key
writing EC key
    0:d=0  hl=3 l= 164 cons: SEQUENCE          
    3:d=1  hl=2 l=   1 prim: INTEGER           :01
    6:d=1  hl=2 l=  48 prim: OCTET STRING      [HEX DUMP]:E3247D99980FEB85A041DFAFF11DA95081F1FD9DF9CBCBD21237BD9131B79EB084FF24A5E2BA462677E234998F69483F
   56:d=1  hl=2 l=   7 cons: cont [ 0 ]        
   58:d=2  hl=2 l=   5 prim: OBJECT            :secp384r1
   65:d=1  hl=2 l= 100 cons: cont [ 1 ]        
   67:d=2  hl=2 l=  98 prim: BIT STRING      

More specifically:

$ openssl ec -in key.pem | openssl asn1parse -offset 6 -item ASN1_OCTET_STRING 
read EC key
writing EC key
ASN1_OCTET_STRING: 
  0000 - e3 24 7d 99 98 0f eb 85-a0 41 df af f1 1d a9 50   .$}......A.....P
  0010 - 81 f1 fd 9d f9 cb cb d2-12 37 bd 91 31 b7 9e b0   .........7..1...
  0020 - 84 ff 24 a5 e2 ba 46 26-77 e2 34 99 8f 69 48 3f   ..$...F&w.4..iH?