edhoc

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 2, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

README

edhoc

A Go implementation of EDHOC, the Ephemeral Diffie-Hellman Over COSE key exchange defined in RFC 9528.

EDHOC is a lightweight authenticated key exchange for constrained devices. It is most often used to set up an OSCORE security context, but the library does not depend on CoAP or OSCORE. It takes EDHOC messages as bytes and returns bytes to send.

Status

Early. Methods 0–3 with cipher suites 0 to 6 and 24 work, and both RFC 9529 traces are reproduced byte for byte; the rest of the RFC is still to come. Expect breaking changes until v1.0.

Goals

  • Pure Go. No cgo, no unsafe, no assembly.
  • Dependencies limited to the standard library and golang.org/x/crypto.
  • Byte-for-byte agreement with the RFC 9529 traces, and interoperability with other EDHOC implementations.
  • Code that can be read next to the RFC: names, files and comments follow RFC 9528.

Supported

Status
Cipher suite 0 (AES-CCM-16-64-128, SHA-256, X25519, EdDSA) yes
Cipher suite 1 (AES-CCM-16-128-128, SHA-256, X25519, EdDSA) yes
Cipher suite 2 (AES-CCM-16-64-128, SHA-256, P-256, ES256) yes
Cipher suite 3 (AES-CCM-16-128-128, SHA-256, P-256, ES256) yes
Cipher suite 4 (ChaCha20/Poly1305, SHA-256, X25519, EdDSA) yes
Cipher suite 5 (ChaCha20/Poly1305, SHA-256, P-256, ES256) yes
Cipher suite 6 (A128GCM, SHA-256, X25519, ES256) yes
Cipher suite 24 (A256GCM, SHA-384, P-384, ES384) yes
Cipher suite 25 (X448, SHAKE256) not planned until Go has X448 and Ed448
Methods 0–3 (signature and static DH keys, in any combination) yes
message_4, EAD, error messages, cipher suite negotiation yes
EDHOC_Exporter, EDHOC_KeyUpdate, OSCORE parameters yes
Raw public keys (CCS) identified by kid yes
X.509 certificates identified by x5t yes
Credentials sent by value in x5chain or kccs yes
Other ID_CRED forms through ParseIDCred

Example

See example_test.go for a complete handshake. In short:

initiator, err := edhoc.NewInitiator(&edhoc.Config{
	Method:         edhoc.MethodStaticStatic,
	Suites:         []edhoc.Suite{edhoc.Suite2},
	ConnID:         []byte{0x37},
	Credential:     myCredential,
	Key:            myKey,
	PeerCredential: lookUpPeer,
})
msg1, err := initiator.WriteMessage1()
// send msg1, receive msg2
err = initiator.ReadMessage2(msg2)
msg3, err := initiator.WriteMessage3()
// send msg3
session, err := initiator.Session()
oscore, err := session.OSCORE()

Go versions

The two most recent Go releases, the same ones the Go team supports.

Security

See SECURITY.md for how to report a vulnerability.

License

Copyright 2026 Last Lock Inc. Licensed under the Apache License, Version 2.0; see LICENSE and NOTICE. You may use, modify and redistribute it, including in commercial and closed-source products.

Documentation

Overview

Package edhoc implements EDHOC, the Ephemeral Diffie-Hellman Over COSE key exchange defined in RFC 9528.

EDHOC runs between an Initiator and a Responder:

Initiator                         Responder
WriteMessage1  --- message_1 -->  ReadMessage1
ReadMessage2   <-- message_2 ---  WriteMessage2
WriteMessage3  --- message_3 -->  ReadMessage3
ReadMessage4   <-- message_4 ---  WriteMessage4   (optional)

The package only turns messages into bytes and back; carrying them, for example over CoAP as in RFC 9528, Appendix A.2, is up to the application. When a Read method fails, send the peer the bytes from ErrorMessage, if any, and drop the session.

After message_3, both sides have a Session, from which application keys are derived with Session.Exporter, or a whole OSCORE context with Session.OSCORE.

Credentials

Each side has a Credential (CRED_I or CRED_R), identified on the wire by an IDCred (ID_CRED_I or ID_CRED_R). The library calls Config.PeerCredential to turn the peer's IDCred into its Credential, then checks that the peer holds the private key. Deciding whether that credential is one the application trusts for this connection is up to the application (RFC 9528, Appendix D). That matters most when the peer sends its credential by value, in an x5chain (IDCred.X5Chain) or kccs (IDCred.KCCS): anyone can send a credential, so PeerCredential must check it against a trust anchor or a list of known keys before returning it.

Status

The package implements all four authentication methods with cipher suites 0 to 6 and 24. Credentials can be raw public keys in a CWT Claims Set (NewCCS, ParseCCS) or X.509 certificates (NewX509); any other form can be used by filling in a Credential directly. The API may change before v1.0.

Example
package main

import (
	"bytes"
	"crypto/ecdh"
	"crypto/rand"
	"fmt"
	"log"

	"github.com/aquilliam/edhoc"
)

// rawPublicKey returns a static DH key and a raw public key credential for
// it, identified by kid.
func rawPublicKey(kid byte) (*ecdh.PrivateKey, edhoc.Credential) {
	key, err := ecdh.P256().GenerateKey(rand.Reader)
	if err != nil {
		log.Fatal(err)
	}
	cred, err := edhoc.NewCCS("", []byte{kid}, key.PublicKey())
	if err != nil {
		log.Fatal(err)
	}
	return key, cred
}

func main() {
	keyI, credI := rawPublicKey(0x01)
	keyR, credR := rawPublicKey(0x02)

	// Each side knows the other's credential in advance and looks it up by
	// the kid it is sent.
	knows := func(c edhoc.Credential) func(edhoc.IDCred) (edhoc.Credential, error) {
		return func(id edhoc.IDCred) (edhoc.Credential, error) {
			if !id.Equal(c.ID) {
				return edhoc.Credential{}, edhoc.ErrUnknownCredential
			}
			return c, nil
		}
	}

	initiator, err := edhoc.NewInitiator(&edhoc.Config{
		Method:         edhoc.MethodStaticStatic,
		Suites:         []edhoc.Suite{edhoc.Suite2},
		ConnID:         []byte{0x37},
		Credential:     credI,
		Key:            keyI,
		PeerCredential: knows(credR),
	})
	if err != nil {
		log.Fatal(err)
	}
	responder, err := edhoc.NewResponder(&edhoc.Config{
		Method:         edhoc.MethodStaticStatic,
		Suites:         []edhoc.Suite{edhoc.Suite2},
		ConnID:         []byte{0x27},
		Credential:     credR,
		Key:            keyR,
		PeerCredential: knows(credI),
	})
	if err != nil {
		log.Fatal(err)
	}

	// In a real application each message travels over the network, and a
	// failure on either side is answered with edhoc.ErrorMessage(err).
	msg1, err := initiator.WriteMessage1()
	if err != nil {
		log.Fatal(err)
	}
	if err := responder.ReadMessage1(msg1); err != nil {
		log.Fatal(err)
	}
	msg2, err := responder.WriteMessage2()
	if err != nil {
		log.Fatal(err)
	}
	if err := initiator.ReadMessage2(msg2); err != nil {
		log.Fatal(err)
	}
	msg3, err := initiator.WriteMessage3()
	if err != nil {
		log.Fatal(err)
	}
	if err := responder.ReadMessage3(msg3); err != nil {
		log.Fatal(err)
	}

	si, _ := initiator.Session()
	sr, _ := responder.Session()
	client, _ := si.OSCORE()
	server, _ := sr.OSCORE()
	fmt.Println("same master secret:", bytes.Equal(client.MasterSecret, server.MasterSecret))
	fmt.Printf("client sender ID %x, server sender ID %x\n", client.SenderID, server.SenderID)
}
Output:
same master secret: true
client sender ID 27, server sender ID 37

Index

Examples

Constants

View Source
const (
	ErrCodeUnspecified        = 1
	ErrCodeWrongSelectedSuite = 2
	ErrCodeUnknownCredential  = 3
)

ERR_CODE values (RFC 9528, Section 6).

Variables

View Source
var ErrUnknownCredential = errors.New("edhoc: unknown credential")

ErrUnknownCredential is returned by a Config.PeerCredential function when the peer refers to a credential this side does not have.

Functions

func ErrorMessage

func ErrorMessage(err error) []byte

ErrorMessage returns the EDHOC error message to send to the peer after err, or nil if no error message should be sent. Only errors of type *Error get a reply; misuse of the API and errors received from the peer do not.

Types

type Config

type Config struct {
	// Method is the authentication method. Both sides must use the same one.
	Method Method

	// Suites lists the supported cipher suites. For the Initiator the order
	// is its order of preference, most preferred first.
	Suites []Suite

	// PeerSuites is SUITES_R from an error message the Responder sent in
	// reply to an earlier message_1. The Initiator then selects its most
	// preferred suite among them. Responders ignore it.
	PeerSuites []Suite

	// ConnID is this side's connection identifier: C_I for the Initiator,
	// C_R for the Responder. It is also this side's OSCORE Recipient ID, so
	// a session fails if both sides pick the same one.
	ConnID []byte

	// Credential is this side's authentication credential, CRED_I or CRED_R.
	Credential Credential

	// Key is the private authentication key matching Credential: a
	// crypto.Signer if this side authenticates with a signature, a DHKey if
	// it uses static DH. Signing keys are ed25519.PrivateKey for EdDSA and
	// *ecdsa.PrivateKey on P-256 for ES256, or anything else that implements
	// crypto.Signer with those public keys, such as a key in a KMS.
	Key any

	// PeerCredential looks up the peer's credential from the ID_CRED field
	// it sent. It is called during ReadMessage2 on the Initiator and
	// ReadMessage3 on the Responder, before the peer has been authenticated,
	// so it must not treat the identifier as proof of anything. Return an
	// error wrapping ErrUnknownCredential if there is no such credential.
	PeerCredential func(id IDCred) (Credential, error)

	// EADLabels lists the absolute values of the EAD labels the application
	// handles. A received critical EAD item with any other label fails the
	// session. Padding (label 0) is always discarded.
	EADLabels []int
}

Config configures one side of an EDHOC session. A Config may be shared by several sessions but must not be changed once it has been passed to NewInitiator or NewResponder.

type Credential

type Credential struct {
	// ID identifies the credential in EDHOC messages.
	ID IDCred

	// Raw is the credential exactly as both sides use it in the transcript,
	// for example the encoded CWT Claims Set of a raw public key.
	Raw []byte

	// PublicKey is the authentication key in the credential. For static DH
	// authentication it is an *ecdh.PublicKey.
	PublicKey crypto.PublicKey
}

A Credential is an authentication credential, CRED_I or CRED_R (RFC 9528, Section 3.5.2).

func NewCCS

func NewCCS(subject string, kid []byte, pub crypto.PublicKey) (Credential, error)

NewCCS returns a credential for a raw public key: a CWT Claims Set with an optional subject claim and a COSE_Key in a 'cnf' claim (RFC 9528, Section 3.5.2). The credential's ID is { 4 : kid }. pub may be a P-256 or P-384 key (*ecdh.PublicKey or *ecdsa.PublicKey), an X25519 key (*ecdh.PublicKey) or an ed25519.PublicKey.

func NewX509

func NewX509(der []byte) (Credential, error)

NewX509 returns the credential for a DER-encoded X.509 certificate, identified by X5T. To send the certificate by value instead, set ID to X5Chain(der, intermediates...). CRED is the certificate as a CBOR byte string (RFC 9528, Section 3.5.2). The certificate is parsed for its public key but not verified; that is up to the application.

func ParseCCS

func ParseCCS(ccs []byte) (Credential, error)

ParseCCS returns the credential for a CWT Claims Set holding a COSE_Key in a 'cnf' claim, the way EDHOC carries raw public keys. If the COSE_Key has a kid, the credential's ID is { 4 : kid }; otherwise the caller sets ID. To send the claims set by value, set ID to KCCS(ccs).

Supported keys are P-256 and P-384 (EC2 with both coordinates), X25519 and Ed25519. P-256, P-384 and X25519 keys come back as *ecdh.PublicKey, Ed25519 keys as ed25519.PublicKey.

type DHKey

type DHKey interface {
	PublicKey() *ecdh.PublicKey
	ECDH(remote *ecdh.PublicKey) ([]byte, error)
}

A DHKey is a static Diffie-Hellman private key. *ecdh.PrivateKey satisfies it; so can a key held in hardware.

type EAD

type EAD struct {
	Label int
	Value []byte
}

An EAD is an external authorization data item (RFC 9528, Section 3.8). A negative Label marks the item as critical. Value is nil when the item has no ead_value.

type Error

type Error struct {
	// Code is the ERR_CODE to send.
	Code int
	// Suites is SUITES_R, sent with ErrCodeWrongSelectedSuite.
	Suites []Suite
	// contains filtered or unexported fields
}

An Error is a failure found while processing an EDHOC message. The session is over; pass the error to ErrorMessage to get the error message to send to the peer.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type IDCred

type IDCred struct {
	// contains filtered or unexported fields
}

An IDCred is an ID_CRED field (RFC 9528, Section 3.5.3): a COSE header map that identifies a credential, such as { 4 : kid }.

func KCCS

func KCCS(ccs []byte) IDCred

KCCS returns the ID_CRED { 14 : ccs } that carries an encoded CWT Claims Set by value (RFC 9528, Section 3.5.3).

func KeyID

func KeyID(kid []byte) IDCred

KeyID returns the ID_CRED { 4 : kid }.

func ParseIDCred

func ParseIDCred(raw []byte) (IDCred, error)

ParseIDCred returns the IDCred for an encoded COSE header map, for ID_CRED forms this package has no constructor for.

func X5Chain

func X5Chain(certs ...[]byte) IDCred

X5Chain returns the ID_CRED { 33 : x5chain } that carries an X.509 certificate chain by value (RFC 9360). certs are DER-encoded, starting with the end-entity certificate. It panics if certs is empty.

func X5T

func X5T(der []byte) IDCred

X5T returns the ID_CRED { 34 : [-15, hash] } that identifies a DER-encoded X.509 certificate by the first 8 bytes of its SHA-256 hash (RFC 9360).

func (IDCred) Bytes

func (id IDCred) Bytes() []byte

Bytes returns the encoded header map.

func (IDCred) Equal

func (id IDCred) Equal(other IDCred) bool

Equal reports whether id and other have the same encoding.

func (IDCred) KCCS

func (id IDCred) KCCS() ([]byte, bool)

KCCS returns the encoded CWT Claims Set if the header map is exactly { 14 : ccs }. The result can be passed to ParseCCS.

func (IDCred) KeyID

func (id IDCred) KeyID() ([]byte, bool)

KeyID returns the kid if the header map is exactly { 4 : kid }.

func (IDCred) X5Chain

func (id IDCred) X5Chain() ([][]byte, bool)

X5Chain returns the DER-encoded certificates if the header map is exactly { 33 : x5chain }. The certificates are not parsed or verified.

type Initiator

type Initiator struct {
	// contains filtered or unexported fields
}

An Initiator runs the Initiator side of one EDHOC session. Call WriteMessage1, ReadMessage2, WriteMessage3 and, if the application uses it, ReadMessage4, in that order. After any error the session is over and every later call fails.

An Initiator is not safe for concurrent use.

func NewInitiator

func NewInitiator(cfg *Config) (*Initiator, error)

NewInitiator returns an Initiator for a new session.

func (*Initiator) PeerCredential

func (i *Initiator) PeerCredential() Credential

PeerCredential returns the Responder's credential once ReadMessage2 has succeeded.

func (*Initiator) PeerEAD

func (i *Initiator) PeerEAD() []EAD

PeerEAD returns the EAD items in the last message read, without padding.

func (*Initiator) ReadMessage2

func (i *Initiator) ReadMessage2(msg []byte) error

ReadMessage2 processes message_2 (RFC 9528, Section 5.3.3). It calls Config.PeerCredential to find the Responder's credential and checks the Responder's proof of possession of the key in it. If the Responder sent an error message instead, the error is a *PeerError.

func (*Initiator) ReadMessage4

func (i *Initiator) ReadMessage4(msg []byte) error

ReadMessage4 processes message_4 (RFC 9528, Section 5.5.3). Once it succeeds, the Initiator knows the Responder has derived the same PRK_out. If the Responder sent an error message instead, the error is a *PeerError.

func (*Initiator) Session

func (i *Initiator) Session() (*Session, error)

Session returns the session once WriteMessage3 has succeeded.

func (*Initiator) WriteMessage1

func (i *Initiator) WriteMessage1(ead ...EAD) ([]byte, error)

WriteMessage1 returns message_1 (RFC 9528, Section 5.2.2), carrying ead as EAD_1.

func (*Initiator) WriteMessage3

func (i *Initiator) WriteMessage3(ead ...EAD) ([]byte, error)

WriteMessage3 returns message_3 (RFC 9528, Section 5.4.2), carrying ead as EAD_3. Once it succeeds, Session returns the session.

type Method

type Method int

A Method is an EDHOC authentication method (RFC 9528, Section 3.2). It says whether each side authenticates with a signature key or a static Diffie-Hellman key.

const (
	MethodSignSign     Method = 0 // Initiator signs, Responder signs
	MethodSignStatic   Method = 1 // Initiator signs, Responder uses static DH
	MethodStaticSign   Method = 2 // Initiator uses static DH, Responder signs
	MethodStaticStatic Method = 3 // both use static DH
)

type OSCOREContext

type OSCOREContext struct {
	MasterSecret []byte
	MasterSalt   []byte
	SenderID     []byte
	RecipientID  []byte
	// AEADAlg is the COSE identifier of the AEAD algorithm, such as 10 for
	// AES-CCM-16-64-128.
	AEADAlg int
	// HashAlg is the COSE identifier of the hash used with HKDF, such as -16
	// for SHA-256.
	HashAlg int
}

An OSCOREContext holds the input parameters for an OSCORE security context (RFC 8613, Section 3.2) derived from an EDHOC session.

type PeerError

type PeerError struct {
	Code int
	// Info is the diagnostic text sent with ErrCodeUnspecified.
	Info string
	// Suites is SUITES_R, sent with ErrCodeWrongSelectedSuite. Use it as
	// Config.PeerSuites when starting the next session.
	Suites []Suite
}

A PeerError is an EDHOC error message received from the peer.

func (*PeerError) Error

func (e *PeerError) Error() string

type Responder

type Responder struct {
	// contains filtered or unexported fields
}

A Responder runs the Responder side of one EDHOC session. Call ReadMessage1, WriteMessage2, ReadMessage3 and, if the application uses it, WriteMessage4, in that order. After any error the session is over and every later call fails.

A Responder keeps state between message_1 and message_3. A server that accepts sessions from untrusted peers should limit how many it keeps (RFC 9528, Section 9.7).

A Responder is not safe for concurrent use.

func NewResponder

func NewResponder(cfg *Config) (*Responder, error)

NewResponder returns a Responder for a new session.

func (*Responder) PeerCredential

func (r *Responder) PeerCredential() Credential

PeerCredential returns the Initiator's credential once ReadMessage3 has succeeded.

func (*Responder) PeerEAD

func (r *Responder) PeerEAD() []EAD

PeerEAD returns the EAD items in the last message read, without padding.

func (*Responder) ReadMessage1

func (r *Responder) ReadMessage1(msg []byte) error

ReadMessage1 processes message_1 (RFC 9528, Section 5.2.3). If the Initiator selected a cipher suite this side will not use, the error is an *Error with code ErrCodeWrongSelectedSuite; send ErrorMessage(err) back so the Initiator can try again.

func (*Responder) ReadMessage3

func (r *Responder) ReadMessage3(msg []byte) error

ReadMessage3 processes message_3 (RFC 9528, Section 5.4.3). It calls Config.PeerCredential to find the Initiator's credential and checks the Initiator's proof of possession of the key in it. Once it succeeds, Session returns the session. If the Initiator sent an error message instead, the error is a *PeerError.

func (*Responder) Session

func (r *Responder) Session() (*Session, error)

Session returns the session once ReadMessage3 has succeeded.

func (*Responder) WriteMessage2

func (r *Responder) WriteMessage2(ead ...EAD) ([]byte, error)

WriteMessage2 returns message_2 (RFC 9528, Section 5.3.2), carrying ead as EAD_2.

func (*Responder) WriteMessage4

func (r *Responder) WriteMessage4(ead ...EAD) ([]byte, error)

WriteMessage4 returns message_4 (RFC 9528, Section 5.5.2), carrying ead as EAD_4. message_4 is optional; send it when the Responder will not send the Initiator any application data protected with the new keys.

type Session

type Session struct {
	// contains filtered or unexported fields
}

A Session is the result of a completed EDHOC handshake. Keys for the application are derived from it with Exporter or OSCORE.

The Initiator should not store the session or its keys, or send protected application data, until it has received message_4 or a message protected with a derived key from the Responder (RFC 9528, Section 5.4.2).

func (*Session) ConnIDs

func (s *Session) ConnIDs() (cI, cR []byte)

ConnIDs returns the connection identifiers C_I and C_R.

func (*Session) Exporter

func (s *Session) Exporter(label int, context []byte, length int) ([]byte, error)

Exporter derives length bytes of keying material for the application (EDHOC_Exporter, RFC 9528, Section 4.2.1). The pair of label and context must not be used for two different purposes.

func (*Session) KeyUpdate

func (s *Session) KeyUpdate(context []byte) error

KeyUpdate replaces PRK_out with one derived from it and context (EDHOC_KeyUpdate, RFC 9528, Appendix H). Both sides must use the same context. Keys exported before the update stay valid until the application deletes them, which it should do as soon as they are no longer needed.

func (*Session) OSCORE

func (s *Session) OSCORE() (*OSCOREContext, error)

OSCORE returns the OSCORE parameters for this session with the default lengths from RFC 9528, Appendix A.1: a Master Secret as long as the application AEAD key and an 8-byte Master Salt. Use Exporter with labels 0 and 1 if the application has agreed on other lengths.

func (*Session) PeerCredential

func (s *Session) PeerCredential() Credential

PeerCredential returns the credential the peer authenticated with.

func (*Session) Suite

func (s *Session) Suite() Suite

Suite returns the selected cipher suite.

type Suite

type Suite int

A Suite is an EDHOC cipher suite (RFC 9528, Section 3.6).

const (
	Suite0  Suite = 0  // AES-CCM-16-64-128, SHA-256, 8, X25519, EdDSA
	Suite1  Suite = 1  // AES-CCM-16-128-128, SHA-256, 16, X25519, EdDSA
	Suite2  Suite = 2  // AES-CCM-16-64-128, SHA-256, 8, P-256, ES256
	Suite3  Suite = 3  // AES-CCM-16-128-128, SHA-256, 16, P-256, ES256
	Suite4  Suite = 4  // ChaCha20/Poly1305, SHA-256, 16, X25519, EdDSA
	Suite5  Suite = 5  // ChaCha20/Poly1305, SHA-256, 16, P-256, ES256
	Suite6  Suite = 6  // A128GCM, SHA-256, 16, X25519, ES256
	Suite24 Suite = 24 // A256GCM, SHA-384, 16, P-384, ES384
)

The cipher suites this package implements, from RFC 9528, Section 10.2. The comment after each lists the EDHOC AEAD and hash algorithms, the MAC length for static DH authentication, and the key exchange and signature algorithms. Suites 0 to 3 use AES-CCM-16-64-128 and SHA-256 for the application; the others use their own EDHOC AEAD and hash.

Directories

Path Synopsis
internal
cbor
Package cbor encodes and decodes the subset of CBOR (RFC 8949) used by EDHOC.
Package cbor encodes and decodes the subset of CBOR (RFC 8949) used by EDHOC.
ccm
Package ccm implements the CCM mode of authenticated encryption defined in NIST SP 800-38C and RFC 3610.
Package ccm implements the CCM mode of authenticated encryption defined in NIST SP 800-38C and RFC 3610.
suites
Package suites holds the EDHOC cipher suites (RFC 9528, Section 3.6) and the algorithms behind them.
Package suites holds the EDHOC cipher suites (RFC 9528, Section 3.6) and the algorithms behind them.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL