did

package
v0.0.0-...-1aa08c1 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2024 License: BSD-3-Clause Imports: 23 Imported by: 18

README

Decentralized Identifiers

Decentralized Identifiers (DIDs) are a new type of identifier for verifiable, "self-sovereign" digital identity. DIDs are fully under the control of the DID subject, independent from any centralized registry, identity provider, or certificate authority. DIDs are URLs that relate a DID subject to means for trustworthy interactions with that subject. DIDs resolve to DID Documents — simple documents that describe how to use that specific DID. Each DID Document may contain at least three things: proof purposes, verification methods, and service endpoints. Proof purposes are combined with verification methods to provide mechanisms for proving things. For example, a DID Document can specify that a particular verification method, such as a cryptographic public key, can be used to verify a proof that was created for the purpose of authentication. Service endpoints enable trusted interactions with the DID controller.

A DID instance has the following format.

 did:METHOD:SPECIFIC_ID

For example.

 did:bryk:4d81bd52-2edb-4703-b8fc-b26d514a9c56

Once resolved, the DID must provide it's corresponding DID Document.

{
  "@context": [
    "https://www.w3.org/ns/did/v1",
    "https://w3id.org/security/v1"
  ],
  "id": "did:bryk:4d81bd52-2edb-4703-b8fc-b26d514a9c56",
  "created": "2019-03-11T01:42:34+08:00",
  "updated": "2019-06-12T05:09:44Z",
  "publicKey": [
    {
      "id": "did:bryk:4d81bd52-2edb-4703-b8fc-b26d514a9c56#master",
      "type": "Ed25519VerificationKey2018",
      "controller": "did:bryk:4d81bd52-2edb-4703-b8fc-b26d514a9c56",
      "publicKeyHex": "be4db03c2f809aa79ea3055a2da8ddfd807fecd073356e337561cd0640251d9f"
    },
    {
      "id": "did:bryk:4d81bd52-2edb-4703-b8fc-b26d514a9c56#code-sign",
      "type": "Ed25519VerificationKey2018",
      "controller": "did:bryk:4d81bd52-2edb-4703-b8fc-b26d514a9c56",
      "publicKeyHex": "e7cc93d399e467a39fca74e32795b1ab1110a7dc94e8623830cd069c1cac72b8"
    }
  ],
  "authentication": [
    "did:bryk:4d81bd52-2edb-4703-b8fc-b26d514a9c56#master"
  ],
  "proof": {
    "@context": [
      "https://w3id.org/security/v1"
    ],
    "type": "Ed25519Signature2018",
    "creator": "did:bryk:4d81bd52-2edb-4703-b8fc-b26d514a9c56#master",
    "created": "2019-06-12T05:09:47Z",
    "domain": "did.bryk.io",
    "nonce": "57d8c5c54022c1e3635eb95b4dae7524",
    "proofValue": "rmK26r4PFXcOkYLG99rDu8o0wx3i5Gys/Ti6AmiUmd01NvWrW2oo9g/6SPScN2m9Z0u2p+kWMw70rqXBgM8LCQ=="
  }
}

Usage

A new identifier instance can be created either randomly from scratch or by parsing an existing DID Document. Once created, a DID instance can be used to perform management tasks using the available functions on the instance's interface. The resulting (updated) DID Document can be easily obtained from the instance for storage or publish.

// Create a new identifier instance
id, err := NewIdentifierWithMode("bryk", "c137", ModeUUID)
if err != nil {
  panic(err)
}

// Add a new key and enable it as authentication mechanism
_= id.AddNewKey("master", KeyTypeEd, EncodingBase58)
_ = id.AddAuthenticationMethod("master")

// Obtain the DID document of the instance and encode it in JSON format
doc := id.Document(true)
js, _ := json.MarshalIndent(doc, "", "  ")
fmt.Printf("%s", js)

Sign and Verify

A DID instance can be used to produce and verify digitally signed messages. The signature can be produced as either a JSON-LD document or a raw binary value.

// Get master key
masterKey := id.Key("master")
msg := []byte("original message to sign")

// Get binary message signature
signatureBin, _  := masterKey.Sign(msg)
if !masterKey.Verify(msg, signatureBin) {
  panic("failed to verify binary signature")
}

// Get a JSON-LD message signature
signatureJSON, _ := masterKey.ProduceSignatureLD(msg, "example.com")
if !masterKey.VerifySignatureLD(msg, signatureJSON) {
  panic("failed to verify JSON-LD signature")
}

JSON-LD signatures produce a document similar to the following.

 {
   "@context": [
     "https://w3id.org/security/v1"
   ],
   "type": "Ed25519Signature2018",
   "creator": "did:bryk:e4a79533-7466-48a7-b5d4-19caa4679ada#master",
   "created": "2019-08-04T19:20:30Z",
   "domain": "example.com",
   "nonce": "6aa89eea31100f0b6e635fb856c98336",
   "signatureValue": "9coFFyo3Vgq+HJg5yj+QRyub9/5A2sGUfc8ermPV9LEgmV+/Q79jX84ktKo8ZPo0T9MT5TCb/STNGeKBXqbZCw=="
 }

More information: https://w3c-ccg.github.io/did-spec/

Documentation

Overview

Package did provides a reference implementation for the "Decentralized Identifiers" W3C community standard.

Decentralized Identifiers (DIDs) are a new type of identifier for verifiable, "self-sovereign" digital identity. DIDs are fully under the control of the DID subject, independent from any centralized registry, identity provider, or certificate authority. DIDs are URLs that relate a DID subject to means for trustworthy interactions with that subject. DIDs resolve to DID Documents — simple documents that describe how to use that specific DID. Each DID Document may contain at least three things: proof purposes, verification methods, and service endpoints. Proof purposes are combined with verification methods to provide mechanisms for proving things. For example, a DID Document can specify that a particular verification method, such as a cryptographic public key, can be used to verify a proof that was created for the purpose of authentication. Service endpoints enable trusted interactions with the DID controller.

A DID instance has the following format.

did:METHOD:SPECIFIC_ID

For example.

did:bryk:4d81bd52-2edb-4703-b8fc-b26d514a9c56

Once resolved, the DID must provide it's corresponding DID Document.

{
  "@context": [
    "https://www.w3.org/ns/did/v1",
    "https://w3id.org/security/v1"
  ],
  "id": "did:bryk:4d81bd52-2edb-4703-b8fc-b26d514a9c56",
  "created": "2019-03-11T01:42:34+08:00",
  "updated": "2019-06-12T05:09:44Z",
  "publicKey": [
    {
      "id": "did:bryk:4d81bd52-2edb-4703-b8fc-b26d514a9c56#master",
      "type": "Ed25519VerificationKey2018",
      "controller": "did:bryk:4d81bd52-2edb-4703-b8fc-b26d514a9c56",
      "publicKeyHex": "be4db03c2f809aa79ea3055a2da8ddfd807fecd073356e337561cd0640251d9f"
    },
    {
      "id": "did:bryk:4d81bd52-2edb-4703-b8fc-b26d514a9c56#code-sign",
      "type": "Ed25519VerificationKey2018",
      "controller": "did:bryk:4d81bd52-2edb-4703-b8fc-b26d514a9c56",
      "publicKeyHex": "e7cc93d399e467a39fca74e32795b1ab1110a7dc94e8623830cd069c1cac72b8"
    }
  ],
  "authentication": [
    "did:bryk:4d81bd52-2edb-4703-b8fc-b26d514a9c56#master"
  ],
  "proof": {
    "@context": [
      "https://w3id.org/security/v1"
    ],
    "type": "Ed25519Signature2018",
    "creator": "did:bryk:4d81bd52-2edb-4703-b8fc-b26d514a9c56#master",
    "created": "2019-06-12T05:09:47Z",
    "domain": "did.bryk.io",
    "nonce": "57d8c5c54022c1e3635eb95b4dae7524",
    "proofValue": "rmK26r4PFXcOkYLG99rDu8o0wx3i5Gys/Ti6AmiUmd01NvWrW2oo9g/6SPScN2m9Z0u2p+kWMw70rqXBgM8LCQ=="
  }
}

Usage

A new identifier instance can be created either randomly from scratch or by parsing an existing DID Document. Once created, a DID instance can be used to perform management tasks using the available functions on the instance's interface. The resulting (updated) DID Document can be easily obtained from the instance for storage or publish.

// Create a new identifier instance
id, err := NewIdentifierWithMode("bryk", "c137", ModeUUID)
if err != nil {
	panic(err)
}

// Add a new key and enable it as authentication mechanism
_ = id.AddNewKey("master", KeyTypeEd, EncodingBase58)
_ = id.AddAuthenticationMethod("master")

// Obtain the DID document of the instance and encode it in JSON format
doc := id.Document(true)
js, _ := json.MarshalIndent(doc, "", "  ")
fmt.Printf("%s", js)

Sign and Verify

A DID instance can be used to produce and verify digitally signed messages. The signature can be produced as either a JSON-LD document or a raw binary value.

// Get master key
masterKey := id.Key("master")
msg := []byte("original message to sign")

// Get binary message signature
signatureBin, _  := masterKey.Sign(msg)
if !masterKey.Verify(msg, signatureBin) {
	panic("failed to verify binary signature")
}

// Get a JSON-LD message signature
signatureJSON, _ := masterKey.ProduceSignatureLD(msg, "example.com")
if !masterKey.VerifySignatureLD(msg, signatureJSON) {
	panic("failed to verify JSON-LD signature")
}

JSON-LD signatures produce a document similar to the following.

{
  "@context": [
    "https://w3id.org/security/v1"
  ],
  "type": "Ed25519Signature2018",
  "creator": "did:bryk:e4a79533-7466-48a7-b5d4-19caa4679ada#master",
  "created": "2019-08-04T19:20:30Z",
  "domain": "example.com",
  "nonce": "6aa89eea31100f0b6e635fb856c98336",
  "signatureValue": "9coFFyo3Vgq+HJg5yj+QRyub9/5A2sGUfc8ermPV9LEgmV+/Q79jX84ktKo8ZPo0T9MT5TCb/STNGeKBXqbZCw=="
}

More information: https://w3c-ccg.github.io/did-spec/

Index

Examples

Constants

View Source
const (
	// ModeUUID generates a random specific id string based on a valid UUID value.
	ModeUUID idStringMode = iota

	// ModeHash generates a random specific id string based on a valid SHA3-256 value.
	ModeHash
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Document

type Document struct {
	// JSON-LD context statement for the document.
	// https://w3c-ccg.github.io/did-spec/#context
	Context []interface{} `json:"@context" yaml:"-"`

	// DID described by the document.
	// https://w3c.github.io/did-core/#did-subject
	Subject string `json:"id" yaml:"id"`

	// A DID controller is an entity that is authorized to make changes to a DID
	// document.
	//
	// https://w3c.github.io/did-core/#did-controller
	Controller string `json:"controller,omitempty" yaml:"controller,omitempty"`

	// A DID subject can have multiple identifiers for different purposes, or at
	// different times. The assertion that two or more DIDs (or other types of URI)
	// refer to the same DID subject can be made using the `alsoKnownAs` property.
	//
	// https://w3c.github.io/did-core/#also-known-as
	AlsoKnownAs []string `json:"alsoKnownAs,omitempty" yaml:"alsoKnownAs,omitempty"`

	// A DID document can express verification methods, such as cryptographic public
	// keys, which can be used to authenticate or authorize interactions with the DID
	// subject or associated parties.
	//
	// https://w3c.github.io/did-core/#verification-methods
	VerificationMethod []VerificationKey `json:"verificationMethod,omitempty" yaml:"verificationMethod,omitempty"`

	// The authentication verification relationship is used to specify how the DID
	// subject is expected to be authenticated, for purposes such as logging into a
	// website or engaging in any sort of challenge-response protocol.
	//
	// https://w3c.github.io/did-core/#authentication
	Authentication []string `json:"authentication,omitempty" yaml:"authentication,omitempty"`

	// The assertionMethod verification relationship is used to specify how the DID
	// subject is expected to express claims, such as for the purposes of issuing a
	// Verifiable Credential.
	//
	// This property is useful, for example, during the processing of a verifiable
	// credential by a verifier. During verification, a verifier checks to see if
	// a verifiable credential contains a proof created by the DID subject by checking
	// that the verification method used to assert the proof is associated with the
	// assertionMethod property in the corresponding DID document.
	//
	// https://w3c.github.io/did-core/#assertion
	AssertionMethod []string `json:"assertionMethod,omitempty" yaml:"assertionMethod,omitempty"`

	// The keyAgreement verification relationship is used to specify how an
	// entity can generate encryption material in order to transmit confidential
	// information intended for the DID subject, such as for the purposes of
	// establishing a secure communication channel with the recipient.
	//
	// An example of when this property is useful is when encrypting a message
	// intended for the DID subject. In this case, the counterparty uses the
	// cryptographic public key information in the verification method to wrap
	// a decryption key for the recipient.
	//
	// https://w3c.github.io/did-core/#key-agreement
	KeyAgreement []string `json:"keyAgreement,omitempty" yaml:"keyAgreement,omitempty"`

	// The capabilityInvocation verification relationship is used to specify a
	// verification method that might be used by the DID subject to invoke a
	// cryptographic capability, such as the authorization to update the DID
	// Document.
	//
	// An example of when this property is useful is when a DID subject needs to
	// access a protected HTTP API that requires authorization in order to use it.
	// In order to authorize when using the HTTP API, the DID subject uses a capability
	// that is associated with a particular URL that is exposed via the HTTP API.
	// The invocation of the capability could be expressed in a number of ways, e.g.,
	// as a digitally signed message that is placed into the HTTP Headers.
	//
	// The server providing the HTTP API is the verifier of the capability and
	// it would need to verify that the verification method referred to by the
	// invoked capability exists in the `capabilityInvocation` property of the
	// DID document. The verifier would also check to make sure that the action
	// being performed is valid and the capability is appropriate for the resource
	// being accessed. If the verification is successful, the server has
	// cryptographically determined that the invoker is authorized to access the
	// protected resource.
	//
	// https://w3c.github.io/did-core/#capability-invocation
	CapabilityInvocation []string `json:"capabilityInvocation,omitempty" yaml:"capabilityInvocation,omitempty"`

	// The capabilityDelegation verification relationship is used to specify a
	// mechanism that might be used by the DID subject to delegate a cryptographic
	// capability to another party, such as delegating the authority to access a
	// specific HTTP API to a subordinate.
	//
	// An example of when this property is useful is when a DID controller chooses
	// to delegate their capability to access a protected HTTP API to a party other
	// than themselves. In order to delegate the capability, the DID subject would
	// use a verification method associated with the capabilityDelegation verification
	// relationship to cryptographically sign the capability over to another DID
	// subject.
	//
	// https://w3c.github.io/did-core/#capability-delegation
	CapabilityDelegation []string `json:"capabilityDelegation,omitempty" yaml:"capabilityDelegation,omitempty"`

	// Services are used in DID documents to express ways of communicating with
	// the DID subject or associated entities. A service can be any type of service
	// the DID subject wants to advertise, including decentralized identity
	// management services for further discovery, authentication, authorization
	// or interaction.
	//
	// https://w3c.github.io/did-core/#services
	Services []ServiceEndpoint `json:"service,omitempty" yaml:"service,omitempty"`
}

Document represents a valid DID document instance. https://w3c.github.io/did-core/#core-properties

func (*Document) ExpandedLD

func (d *Document) ExpandedLD() ([]byte, error)

ExpandedLD returns an expanded JSON-LD document. http://www.w3.org/TR/json-ld-api/#expansion-algorithm

func (*Document) NormalizedLD

func (d *Document) NormalizedLD() ([]byte, error)

NormalizedLD produces an RDF dataset on the JSON-LD document, the algorithm used is "URDNA2015" and the format "application/n-quads". https://json-ld.github.io/normalization/spec

type DocumentMetadata

type DocumentMetadata struct {
	// Timestamp of the original creation, normalized to UTC 00:00.
	// https://w3c-ccg.github.io/did-spec/#created-optional
	Created string `json:"created,omitempty" yaml:"created,omitempty"`

	// Timestamp of the latest updated registered for the document, normalized to
	// UTC 00:00.
	// https://w3c-ccg.github.io/did-spec/#updated-optional
	Updated string `json:"updated,omitempty" yaml:"updated,omitempty"`

	// Whether the DID should be considered active or not.
	// https://www.w3.org/TR/did-spec-registries/#deactivated
	Deactivated bool `json:"deactivated" yaml:"deactivated"`
}

DocumentMetadata provides information pertaining to the DID document itself, rather than the DID subject. https://www.w3.org/TR/did-core/#metadata-structure

Additional details:

https://github.com/w3c/did-core/issues/65
https://github.com/w3c/did-core/issues/203

type Extension

type Extension struct {
	// Unique identifier for the extension.
	ID string `json:"id" yaml:"id"`

	// Semantic versioning value.
	Version string `json:"version" yaml:"version"`

	// Custom extension parameters.
	Data any `json:"data" yaml:"data,omitempty"`
}

Extension provides a flexible mechanism to add contextual parameters to the standard elements used on a DID document.

type IDStringVerifier

type IDStringVerifier func(string) error

IDStringVerifier allows the user to provide a custom verifier method for the specific id string segment. Successful verifications must return a nil error.

type Identifier

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

Identifier instance based on the DID specification.

func FromDocument

func FromDocument(doc *Document) (*Identifier, error)

FromDocument restores an identifier instance from a previously generated DID Document.

func NewIdentifier

func NewIdentifier(method string, idString string) (*Identifier, error)

NewIdentifier provides a helper factory method to generate a free-form identifier instance using the provided method and id string.

Example

Basic identifier generation.

id, err := NewIdentifier("sample", "foo-bar")
if err != nil {
	panic(err)
}
fmt.Println(id)
Output:

did:sample:foo-bar

func NewIdentifierWithMode

func NewIdentifierWithMode(method string, tag string, mode idStringMode) (*Identifier, error)

NewIdentifierWithMode provides a helper factory method to generate new random identifier instances using one of the modes described in the "bryk" DID Method specification.

Example

Basic identifier generation for specific method, tag and mode.

id, err := NewIdentifierWithMode("bryk", "c137", ModeUUID)
if err != nil {
	panic(err)
}
fmt.Println(id)
Output:

func Parse

func Parse(input string) (*Identifier, error)

Parse a provided input string into a valid identifier instance.

func (*Identifier) AddMetadata

func (d *Identifier) AddMetadata(metadata *DocumentMetadata) error

AddMetadata updates the identifier Created, Updated, and Deactivated properties based on a document metadata input.

func (*Identifier) AddNewVerificationMethod

func (d *Identifier) AddNewVerificationMethod(id string, kt KeyType) error

AddNewVerificationMethod generates and registers a new cryptographic key for the identifier instance.

func (*Identifier) AddService

func (d *Identifier) AddService(se *ServiceEndpoint) error

AddService set a new service endpoint for the identifier instance.

func (*Identifier) AddVerificationMethod

func (d *Identifier) AddVerificationMethod(id string, private []byte, kt KeyType) error

AddVerificationMethod attach an existing cryptographic key to the identifier.

func (*Identifier) AddVerificationRelationship

func (d *Identifier) AddVerificationRelationship(reference string, vm VerificationRelationship) error

AddVerificationRelationship appends reference as a valid verification mechanism for the DID instance. Verification methods can be used to authenticate or authorize interactions with the DID subject or associated parties. https://w3c.github.io/did-core/#verification-methods

func (*Identifier) Controller

func (d *Identifier) Controller() string

Controller returns the DID currently set as controller for the identifier instance.

func (*Identifier) Created

func (d *Identifier) Created() (time.Time, error)

Created returns the creation date for the instance, will return an error if no date is currently set.

func (*Identifier) DID

func (d *Identifier) DID() string

DID returns the DID segment of the identifier instance.

func (*Identifier) Deactivated

func (d *Identifier) Deactivated() bool

Deactivated returns a bool value indicating if the identifier is deactivated.

func (*Identifier) Document

func (d *Identifier) Document(safe bool) *Document

Document returns the DID document for the identifier instance. If 'safe' is true, the returned document remove any private key material present, making the document safe to be published and shared.

Example

Generate DID document from identifier instance.

// Create a new identifier instance
id, err := NewIdentifierWithMode("bryk", "c137", ModeUUID)
if err != nil {
	panic(err)
}

// Add a new key and enable it as authentication mechanism
_ = id.AddNewVerificationMethod("master", KeyTypeEd)
_ = id.AddVerificationRelationship(id.GetReference("master"), AuthenticationVM)

// Get cryptographic proof for the identifier instance
key := id.VerificationMethod("master")
proof, err := id.GetProof(key.ID, "sample.com")
if err != nil {
	panic(err)
}

// The verifier can later check the validity of the proof using the
// public key and normalized version of the DID document.
doc, _ := id.Document(true).NormalizedLD()
if !key.VerifyProof(doc, proof) {
	panic("invalid proof")
}

// Print DID document in JSON format
js, _ := json.MarshalIndent(id.Document(true), "", "  ")
fmt.Printf("%s", js)
Output:

func (*Identifier) Fragment

func (d *Identifier) Fragment() string

Fragment returns the fragment segment of the identifier instance.

func (*Identifier) GetMetadata

func (d *Identifier) GetMetadata() *DocumentMetadata

GetMetadata returns the DocumentMetadata for the identifier instance.

func (*Identifier) GetProof

func (d *Identifier) GetProof(keyID, domain string) (*ProofLD, error)

GetProof generates a cryptographically verifiable proof of integrity for the identifier's document. https://w3c.github.io/did-core//#proof-optional

func (*Identifier) GetReference

func (d *Identifier) GetReference(fragment string) string

GetReference returns a valid DID with the provided fragment appended.

func (*Identifier) GetVerificationRelationship

func (d *Identifier) GetVerificationRelationship(vm VerificationRelationship) []string

GetVerificationRelationship return the references currently enabled as verification methods, of the specified type, for the identifier instance. https://w3c.github.io/did-core/#verification-methods

func (*Identifier) IsURL

func (d *Identifier) IsURL() bool

IsURL returns true if a DID has a Path, a Query or a Fragment https://w3c.github.io/did-core/#did-url-syntax

func (*Identifier) MarshalJSON

func (d *Identifier) MarshalJSON() ([]byte, error)

MarshalJSON provides the custom JSON encoding implementation for an identifier instance.

func (*Identifier) Method

func (d *Identifier) Method() string

Method returns the method segment of the identifier instance.

func (*Identifier) Path

func (d *Identifier) Path() string

Path returns the path segment of the identifier instance.

func (*Identifier) Query

func (d *Identifier) Query() (url.Values, error)

Query returns the URL-decoded contents of the query segment of the identifier instance.

func (*Identifier) RawQuery

func (d *Identifier) RawQuery() string

RawQuery returns the query portion of the identifier instance as a string.

func (*Identifier) RegisterContext

func (d *Identifier) RegisterContext(el interface{})

RegisterContext adds a new context entry to the document. Useful when adding new data entries. https://w3c.github.io/json-ld-syntax/#the-context

func (*Identifier) RemoveService

func (d *Identifier) RemoveService(name string) error

RemoveService will eliminate a previously registered service endpoint for the instance.

func (*Identifier) RemoveVerificationMethod

func (d *Identifier) RemoveVerificationMethod(id string) error

RemoveVerificationMethod will permanently eliminate a registered key from the instance. An error will be produced if the key you're trying to remove is the only enabled authentication key.

func (*Identifier) RemoveVerificationRelationship

func (d *Identifier) RemoveVerificationRelationship(reference string, vm VerificationRelationship) error

RemoveVerificationRelationship updates the DID instance by removing a previously enable verification method reference. https://w3c.github.io/did-core/#verification-methods

func (*Identifier) Service

func (d *Identifier) Service(id string) *ServiceEndpoint

Service retrieve a service endpoint based on it's id, "nil" is returned if the identifier is invalid.

func (*Identifier) Services

func (d *Identifier) Services() []ServiceEndpoint

Services returns the registered service endpoints on the identifier.

func (*Identifier) SetController

func (d *Identifier) SetController(did string) error

SetController updates the DID set as controller for the identifier instance.

func (*Identifier) String

func (d *Identifier) String() string

String encodes a DID instance into a valid DID string.

func (*Identifier) Subject

func (d *Identifier) Subject() string

Subject returns the specific ID segment of the identifier instance.

func (*Identifier) UnmarshalJSON

func (d *Identifier) UnmarshalJSON(b []byte) error

UnmarshalJSON provides custom JSON decoding implementation for an identifier instance.

func (*Identifier) Updated

func (d *Identifier) Updated() (time.Time, error)

Updated returns the date of the last update for the instance, will return an error if no date is currently set.

func (*Identifier) VerificationMethod

func (d *Identifier) VerificationMethod(id string) *VerificationKey

VerificationMethod retrieve a key based on it's id (fragment value), "nil" is returned if the identifier is invalid.

func (*Identifier) VerificationMethods

func (d *Identifier) VerificationMethods() []VerificationKey

VerificationMethods returns the registered verification methods on the identifier instance.

func (*Identifier) Verify

func (d *Identifier) Verify(c IDStringVerifier) error

Verify search for common errors in the identifier structure.

type KeyType

type KeyType int

KeyType provide valid values when specifying a cryptographic verification key.

const (
	// KeyTypeEd specify a Ed25519 keypair.
	// https://w3c-dvcg.github.io/lds-ed25519-2018/
	KeyTypeEd KeyType = iota

	// KeyTypeRSA specify a RSA keypair.
	// https://w3c-dvcg.github.io/lds-rsa2018/
	KeyTypeRSA

	// KeyTypeSecp256k1 specify an ECDSA secp256k1 keypair.
	// https://w3c-dvcg.github.io/lds-ecdsa-secp256k1-2019/
	KeyTypeSecp256k1
)

func (KeyType) DecodePublicKey

func (v KeyType) DecodePublicKey(vk *VerificationKey) ([]byte, error)

DecodePublicKey returns public key byte representation for the provided verification key instance.

func (KeyType) EncodePublicKey

func (v KeyType) EncodePublicKey(vk *VerificationKey, pub []byte)

EncodePublicKey adjust the `vk` verification key to properly encode its public bytes representation.

func (*KeyType) MarshalJSON

func (v *KeyType) MarshalJSON() ([]byte, error)

MarshalJSON provides custom encoding implementation.

func (KeyType) MarshalYAML

func (v KeyType) MarshalYAML() (interface{}, error)

MarshalYAML provides custom YAML encoding.

func (KeyType) SignatureType

func (v KeyType) SignatureType() string

SignatureType returns the value identifier for the kind of signature generated by the key.

func (KeyType) String

func (v KeyType) String() string

String returns the value identifier for a given key type value.

func (*KeyType) UnmarshalJSON

func (v *KeyType) UnmarshalJSON(b []byte) error

UnmarshalJSON provides custom decoding implementation.

func (*KeyType) UnmarshalYAML

func (v *KeyType) UnmarshalYAML(unmarshal func(v interface{}) error) error

UnmarshalYAML provides custom YAML decoding.

type Param

type Param struct {
	// param-name = 1*param-char
	// Name may include a method name and param name separated by a colon
	Name string
	// param-value = *param-char
	Value string
}

Param represents a parsed DID param, which contains a name and value. A generic param is defined as a param name and value separated by a colon:

generic-param-name:param-value

https://w3c.github.io/did-core/#generic-did-parameter-names

A param may also be method specific, which requires the method name to prefix the param name separated by a colon:

method-name:param-name
param = param-name [ "=" param-value ]

https://w3c.github.io/did-core/#method-specific-did-parameter-names

func (*Param) String

func (p *Param) String() string

String encodes a Param struct into a valid Param string. Name is required by the grammar. Value is optional.

type ProofLD

type ProofLD struct {
	// JSON-LD context statement for the document.
	// https://w3c-ccg.github.io/did-spec/#context
	Context []string `json:"@context,omitempty" yaml:"-"`

	// A URI that identifies the digital proof suite that was used to create
	// the proof.
	Type string `json:"type" yaml:"type"`

	// A link to a machine-readable object, such as a DID Document, that contains
	// authorization relations that explicitly permit the use of certain verification
	// methods for specific purposes. For example, a controller object could contain
	// statements that restrict a public key to being used only for signing Verifiable
	// Credentials and no other kinds of documents.
	Controller string `json:"controller,omitempty" yaml:"controller,omitempty"`

	// Creation timestamp in the RFC3339 format.
	Created string `json:"created" yaml:"created"`

	// A string value that specifies the operational domain of a digital proof.
	// This may be an Internet domain name like "example.com", a ad-hoc value such
	// as "corp-level3-access", or a very specific transaction value like "8zF6T$mqP".
	// A signer may include a domain in its digital proof to restrict its use to
	// particular target, identified by the specified domain.
	Domain string `json:"domain,omitempty" yaml:"domain,omitempty"`

	// A random or pseudo-random value used by some authentication protocols to
	// mitigate replay attacks.
	Challenge string `json:"challenge,omitempty" yaml:"challenge,omitempty"`

	// A string value that is included in the digital proof and MUST only be used
	// once for a particular domain and window of time. This value is used to mitigate
	// replay attacks.
	Nonce string `json:"nonce,omitempty" yaml:"nonce,omitempty"`

	// The specific intent for the proof, the reason why an entity created it.
	// Acts as a safeguard to prevent the proof from being misused for a purpose
	// other than the one it was intended for. For example, a proof can be used
	// for purposes of authentication, for asserting control of a Verifiable
	// Credential (assertionMethod), and several others.
	//
	// Common values include: authentication, assertionMethod, keyAgreement,
	// capabilityInvocation, capabilityDelegation.
	// https://w3c-ccg.github.io/ld-proofs/#proof-purpose
	Purpose string `json:"proofPurpose,omitempty" yaml:"proofPurpose,omitempty"`

	// A set of parameters required to independently verify the proof, such as
	// an identifier for a public/private key pair that would be used in the
	// proof.
	VerificationMethod string `json:"verificationMethod,omitempty" yaml:"verificationMethod,omitempty"`

	// Proof value produced.
	Value []byte `json:"proofValue" yaml:"proofValue"`
}

ProofLD provides a common format for Linked Data Proofs. Proofs add authentication and integrity protection to linked data documents through the use of mathematical algorithms. https://w3c-ccg.github.io/ld-proofs/

func (*ProofLD) GetInput

func (p *ProofLD) GetInput(data []byte) ([]byte, error)

GetInput returns a valid proof input value as described by the specification. https://w3c-ccg.github.io/ld-proofs/#proof-algorithm

func (*ProofLD) NormalizedLD

func (p *ProofLD) NormalizedLD() ([]byte, error)

NormalizedLD produces an RDF dataset on the JSON-LD document, the algorithm used is "URDNA2015" and the format "application/n-quads" https://json-ld.github.io/normalization/spec

type ServiceEndpoint

type ServiceEndpoint struct {
	// Unique identifier for the service entry.
	ID string `json:"id" yaml:"id"`

	// Cryptographic suite identifier.
	Type string `json:"type" yaml:"type"`

	// Main URL for interactions.
	Endpoint string `json:"serviceEndpoint" yaml:"serviceEndpoint"`

	// Extensions used on the service endpoint instance.
	Extensions []Extension `json:"extensions,omitempty" yaml:"extensions,omitempty"`
}

ServiceEndpoint represents any type of service the entity wishes to advertise, including decentralized identity management services for further discovery, authentication, authorization, or interaction. https://w3c.github.io/did-core/#service-endpoints

func (*ServiceEndpoint) AddExtension

func (se *ServiceEndpoint) AddExtension(ext Extension)

AddExtension can be used to register additional contextual information in the service instance. If another extension with the same id and version information, the data will be updated.

func (*ServiceEndpoint) GetExtension

func (se *ServiceEndpoint) GetExtension(id string, version string, holder interface{}) error

GetExtension retrieves the information available for a given extension and decode it into the provided holder instance (usually a pointer to a structure type). If no information is available or a decoding problems occurs an error will be returned.

type SignatureLD

type SignatureLD struct {
	// JSON-LD context statement for the document.
	// https://w3c-ccg.github.io/did-spec/#context
	Context []string `json:"@context,omitempty"`

	// Identifier for the digital signature suite that was used to create the signature.
	Type string `json:"type"`

	// A URI that identifies the public/private key pair associated with the signature. The
	// URI SHOULD be a URL that can be dereferenced to obtain a linked data document that
	// contains a link identifying the entity that owns the key pair. Dereferencing the entity
	// link SHOULD result in a Linked Data document that contains a link back to the URL
	// identifier for the public/private key pair, thereby proving ownership.
	Creator string `json:"creator"`

	// Creation timestamp in the RFC3339 format.
	Created string `json:"created"`

	// A string value that specifies the operational domain of a digital signature. This may be
	// an Internet domain name like "example.com", a ad-hoc value such as "corp-level3-access",
	// or a very specific transaction value like "8zF6T$mqP". A signer may include a domain in
	// its digital signature to restrict its use to particular target, identified by the specified
	// domain.
	Domain string `json:"domain,omitempty"`

	// A string value that is included in the digital signature and MUST only be used once for
	// a particular domain and window of time. This value is used to mitigate replay attacks.
	Nonce string `json:"nonce,omitempty"`

	// Signature value produced.
	Value []byte `json:"signatureValue"`
}

SignatureLD provides a common format for Linked Data Signatures including information about the produced signature, parameters required to verify it, and the signature value itself.

https://w3c-dvcg.github.io/ld-signatures/#linked-data-signature-overview

NOTICE: This specification has been removed =/ https://github.com/w3c-ccg/ld-signatures

func (*SignatureLD) GetInput

func (s *SignatureLD) GetInput(data []byte) ([]byte, error)

GetInput returns a valid signature input value as described by the specification. https://w3c-dvcg.github.io/ld-signatures/#create-verify-hash-algorithm

func (*SignatureLD) NormalizedLD

func (s *SignatureLD) NormalizedLD() ([]byte, error)

NormalizedLD produces an RDF dataset on the JSON-LD document, the algorithm used is "URDNA2015" and the format "application/n-quads". https://json-ld.github.io/normalization/spec

type VerificationKey

type VerificationKey struct {
	// Unique identifier for the key reference.
	ID string `json:"id" yaml:"id"`

	// Cryptographic suite identifier.
	Type KeyType `json:"type" yaml:"type"`

	// Subject controlling the corresponding private key.
	Controller string `json:"controller" yaml:"controller"`

	// Extensions used on the key instance.
	Extensions []Extension `json:"extensions,omitempty" yaml:"extensions,omitempty"`

	// Public key material encoded in the MULTIBASE format.
	// https://datatracker.ietf.org/doc/html/draft-multiformats-multibase-03
	Public string `json:"publicKeyMultibase,omitempty" yaml:"publicKeyMultibase,omitempty"`

	// Public key material encoded as base58.
	// https://w3c-ccg.github.io/security-vocab/contexts/security-v1.jsonld
	PublicKeyBase58 string `json:"publicKeyBase58,omitempty" yaml:"publicKeyBase58,omitempty"`

	// Private portion of the cryptographic key.
	Private []byte `json:"private,omitempty" yaml:"private,omitempty"`
}

VerificationKey represents a cryptographic key according to the "Linked Data Cryptographic Suites". https://w3c-ccg.github.io/ld-cryptosuite-registry/

func (*VerificationKey) AddExtension

func (k *VerificationKey) AddExtension(ext Extension)

AddExtension can be used to register additional contextual information in the key instance. If another extension with the same id and version information, the data will be updated.

func (*VerificationKey) Bytes

func (k *VerificationKey) Bytes() ([]byte, error)

Bytes returns the byte representation of the public key.

func (*VerificationKey) GetExtension

func (k *VerificationKey) GetExtension(id string, version string, holder interface{}) error

GetExtension retrieves the information available for a given extension and decode it into the provided holder instance (usually a pointer to a structure type). If no information is available or decoding problems occur, an error will be returned.

func (*VerificationKey) ProduceProof

func (k *VerificationKey) ProduceProof(data []byte, purpose, domain string) (*ProofLD, error)

ProduceProof will generate a valid linked data proof for the provided data, usually a canonicalized version of JSON-LD document. https://w3c-dvcg.github.io/ld-proofs

func (*VerificationKey) ProduceSignatureLD

func (k *VerificationKey) ProduceSignatureLD(data []byte, domain string) (*SignatureLD, error)

ProduceSignatureLD generates a valid linked data signature for the provided data, usually a canonicalized version of JSON-LD document. https://w3c-dvcg.github.io/ld-signatures/#signature-algorithm

func (*VerificationKey) Sign

func (k *VerificationKey) Sign(data []byte) ([]byte, error)

Sign the provided input and return the generated signature value.

Example

Produce and verify singed messages.

id, _ := NewIdentifierWithMode("bryk", "", ModeUUID)
_ = id.AddNewVerificationMethod("master", KeyTypeEd)
_ = id.AddVerificationRelationship(id.GetReference("master"), AuthenticationVM)

// Get master key
masterKey := id.VerificationMethod("master")
msg := []byte("original message to sign")

// Get binary message signature
signatureBin, _ := masterKey.Sign(msg)
if !masterKey.Verify(msg, signatureBin) {
	panic("failed to verify binary signature")
}

// Get a JSON-LD message signature
signatureJSON, _ := masterKey.ProduceSignatureLD(msg, "example.com")
if !masterKey.VerifySignatureLD(msg, signatureJSON) {
	panic("failed to verify JSON-LD signature")
}
Output:

func (*VerificationKey) String

func (k *VerificationKey) String() string

String uses the key ID value as its textual representation.

func (*VerificationKey) Verify

func (k *VerificationKey) Verify(data, signature []byte) bool

Verify the validity of the provided input and signature values.

func (*VerificationKey) VerifyProof

func (k *VerificationKey) VerifyProof(data []byte, proof *ProofLD) bool

VerifyProof will evaluate the authenticity and integrity of a linked data proof using the public key instance. https://w3c-ccg.github.io/ld-proofs/#create-verify-hash-algorithm

func (*VerificationKey) VerifySignatureLD

func (k *VerificationKey) VerifySignatureLD(data []byte, sig *SignatureLD) bool

VerifySignatureLD validates the authenticity and integrity of a linked data signature using the public key instance. https://w3c-dvcg.github.io/ld-signatures/#signature-verification-algorithm

type VerificationRelationship

type VerificationRelationship int

VerificationRelationship specifies the semantics and intended usage of a specific verification mechanism enabled on a DID instance.

const (
	// AuthenticationVM is used to express a verification relationship which
	// an entity can use to prove it is the DID subject or acting on behalf
	// of the DID Subject as a DID Controller.
	// https://w3c.github.io/did-core/#authentication
	AuthenticationVM VerificationRelationship = iota

	// AssertionVM is used to express a verification relationship which indicates
	// that a  verification method can be used to assert a statement on behalf of
	// the DID subject.
	// https://w3c.github.io/did-core/#assertionmethod
	AssertionVM

	// KeyAgreementVM is used to express a verification relationship which an
	// entity can use to engage in key agreement protocols on behalf of the DID
	// subject.
	// https://w3c.github.io/did-core/#keyagreement
	KeyAgreementVM

	// CapabilityInvocationVM is used to express a verification relationship which
	// an entity can use to invoke capabilities as the DID subject or on behalf of
	// the DID subject. A capability is an expression of an action that the DID
	// subject is authorized to take.
	// https://w3c.github.io/did-core/#capabilityinvocation
	CapabilityInvocationVM

	// CapabilityDelegationVM Used to express a verification relationship which an
	// entity can use to grant capabilities as the DID subject or on behalf of the
	// DID subject to other capability invokers.
	// https://w3c.github.io/did-core/#capabilitydelegation
	CapabilityDelegationVM
)

Directories

Path Synopsis
Package resolver provides a "DIF Universal Resolver" handler and driver implementation.
Package resolver provides a "DIF Universal Resolver" handler and driver implementation.

Jump to

Keyboard shortcuts

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