github.com/cloudflare/circl@v1.5.0/hpke/marshal_test.go (about) 1 package hpke 2 3 import ( 4 "bytes" 5 "crypto/rand" 6 "testing" 7 ) 8 9 func contextEqual(a, b *encdecContext) bool { 10 an := make([]byte, a.NonceSize()) 11 bn := make([]byte, b.NonceSize()) 12 ac := a.AEAD.Seal(nil, an, nil, nil) 13 bc := b.AEAD.Seal(nil, bn, nil, nil) 14 return a.suite == b.suite && 15 bytes.Equal(a.exporterSecret, b.exporterSecret) && 16 bytes.Equal(a.key, b.key) && 17 bytes.Equal(a.baseNonce, b.baseNonce) && 18 bytes.Equal(a.sequenceNumber, b.sequenceNumber) && 19 bytes.Equal(ac, bc) && 20 len(a.nonce) == len(b.nonce) && 21 len(a.nonce) == len(a.baseNonce) 22 } 23 24 func TestContextSerialization(t *testing.T) { 25 s := NewSuite(KEM_P384_HKDF_SHA384, KDF_HKDF_SHA384, AEAD_AES256GCM) 26 info := []byte("some info string") 27 28 pk, sk, err := s.kemID.Scheme().GenerateKeyPair() 29 if err != nil { 30 t.Fatal(err) 31 } 32 receiver, err := s.NewReceiver(sk, info) 33 if err != nil { 34 t.Fatal(err) 35 } 36 sender, err := s.NewSender(pk, info) 37 if err != nil { 38 t.Fatal(err) 39 } 40 enc, sealer, err := sender.Setup(rand.Reader) 41 if err != nil { 42 t.Fatal(err) 43 } 44 opener, err := receiver.Setup(enc) 45 if err != nil { 46 t.Fatal(err) 47 } 48 49 rawSealer, err := sealer.MarshalBinary() 50 if err != nil { 51 t.Fatal(err) 52 } 53 parsedSealer, err := UnmarshalSealer(rawSealer) 54 if err != nil { 55 t.Fatal(err) 56 } 57 if !contextEqual( 58 sealer.(*sealContext).encdecContext, 59 parsedSealer.(*sealContext).encdecContext) { 60 t.Error("parsed sealer does not match original") 61 } 62 _, err = UnmarshalOpener(rawSealer) 63 if err == nil { 64 t.Error("parsing a sealer as an opener succeeded; want failure") 65 } 66 67 rawOpener, err := opener.MarshalBinary() 68 if err != nil { 69 t.Fatal(err) 70 } 71 parsedOpener, err := UnmarshalOpener(rawOpener) 72 if err != nil { 73 t.Fatal(err) 74 } 75 if !contextEqual( 76 opener.(*openContext).encdecContext, 77 parsedOpener.(*openContext).encdecContext) { 78 t.Error("parsed opener does not match original") 79 } 80 _, err = UnmarshalSealer(rawOpener) 81 if err == nil { 82 t.Error("parsing an opener as a sealer succeeded; want failure") 83 } 84 }