commit 90b21e8be012cb1a782e9e7043f53ba9f54ca1d5
parent b4dc18ee7bbaf281f182715d7003c5240e12bd4e
Author: Shivakumar <[email protected]>
Date: Sat, 16 May 2026 16:25:33 +0530
feat(crypto): initialize modules and core cryptographic premitives
Signed-off-by: Shivakumar <[email protected]>
Diffstat:
| A | go.mod | | | 25 | +++++++++++++++++++++++++ |
| A | go.sum | | | 45 | +++++++++++++++++++++++++++++++++++++++++++++ |
| A | internal/crypto/did.go | | | 82 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | internal/crypto/hash.go | | | 78 | ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| A | internal/crypto/keys.go | | | 161 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
5 files changed, 391 insertions(+), 0 deletions(-)
diff --git a/go.mod b/go.mod
@@ -0,0 +1,25 @@
+module certichain
+
+go 1.26.2
+
+require (
+ github.com/dgraph-io/badger/v4 v4.9.1
+ golang.org/x/sync v0.20.0
+)
+
+require (
+ github.com/cespare/xxhash/v2 v2.3.0 // indirect
+ github.com/dgraph-io/ristretto/v2 v2.2.0 // indirect
+ github.com/dustin/go-humanize v1.0.1 // indirect
+ github.com/go-logr/logr v1.4.3 // indirect
+ github.com/go-logr/stdr v1.2.2 // indirect
+ github.com/google/flatbuffers v25.2.10+incompatible // indirect
+ github.com/klauspost/compress v1.18.0 // indirect
+ go.opentelemetry.io/auto/sdk v1.1.0 // indirect
+ go.opentelemetry.io/otel v1.37.0 // indirect
+ go.opentelemetry.io/otel/metric v1.37.0 // indirect
+ go.opentelemetry.io/otel/trace v1.37.0 // indirect
+ golang.org/x/net v0.43.0 // indirect
+ golang.org/x/sys v0.35.0 // indirect
+ google.golang.org/protobuf v1.36.7 // indirect
+)
diff --git a/go.sum b/go.sum
@@ -0,0 +1,45 @@
+github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
+github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/dgraph-io/badger/v4 v4.9.1 h1:DocZXZkg5JJHJPtUErA0ibyHxOVUDVoXLSCV6t8NC8w=
+github.com/dgraph-io/badger/v4 v4.9.1/go.mod h1:5/MEx97uzdPUHR4KtkNt8asfI2T4JiEiQlV7kWUo8c0=
+github.com/dgraph-io/ristretto/v2 v2.2.0 h1:bkY3XzJcXoMuELV8F+vS8kzNgicwQFAaGINAEJdWGOM=
+github.com/dgraph-io/ristretto/v2 v2.2.0/go.mod h1:RZrm63UmcBAaYWC1DotLYBmTvgkrs0+XhBd7Npn7/zI=
+github.com/dgryski/go-farm v0.0.0-20240924180020-3414d57e47da h1:aIftn67I1fkbMa512G+w+Pxci9hJPB8oMnkcP3iZF38=
+github.com/dgryski/go-farm v0.0.0-20240924180020-3414d57e47da/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw=
+github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
+github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
+github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
+github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
+github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
+github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
+github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
+github.com/google/flatbuffers v25.2.10+incompatible h1:F3vclr7C3HpB1k9mxCGRMXq6FdUalZ6H/pNX4FP1v0Q=
+github.com/google/flatbuffers v25.2.10+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8=
+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
+github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
+github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
+go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
+go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
+go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ=
+go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I=
+go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE=
+go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E=
+go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4=
+go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0=
+golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
+golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
+golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
+golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
+golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
+golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
+google.golang.org/protobuf v1.36.7 h1:IgrO7UwFQGJdRNXH/sQux4R1Dj1WAKcLElzeeRaXV2A=
+google.golang.org/protobuf v1.36.7/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/internal/crypto/did.go b/internal/crypto/did.go
@@ -0,0 +1,82 @@
+// Copyright 2026 Shivakumar (Certichain)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package crypto
+
+import (
+ "crypto/ed25519"
+ "encoding/hex"
+ "errors"
+ "strings"
+)
+
+const (
+ DIDPrefix = "did:certchain:0x"
+ DIDHashLength = 64 // SHA-256 hex length
+)
+
+// NewDID derives a deterministic DID from an Ed25519 public key.
+//
+// Format:
+//
+// did:certchain:0x<sha256(public-key)>
+func NewDID(publicKey ed25519.PublicKey) (string, error) {
+ if len(publicKey) != ed25519.PublicKeySize {
+ return "", errors.New("invalid Ed25519 public key")
+ }
+
+ hash := HashBytes(publicKey)
+
+ return DIDPrefix + hex.EncodeToString(hash[:]), nil
+}
+
+// ParseDID validates and parses a certchain DID.
+//
+// Expected format:
+//
+// did:certchain:0x<64 lowercase hex chars>
+func ParseDID(did string) (string, error) {
+ if strings.TrimSpace(did) != did {
+ return "", errors.New("invalid DID")
+ }
+
+ if !strings.HasPrefix(did, DIDPrefix) {
+ return "", errors.New("invalid DID prefix")
+ }
+
+ identifier := strings.TrimPrefix(did, DIDPrefix)
+ if len(identifier) != DIDHashLength {
+ return "", errors.New("invalid DID length")
+ }
+
+ if _, err := hex.DecodeString(identifier); err != nil {
+ return "", errors.New("invalid DID hex encoding")
+ }
+
+ if identifier != strings.ToLower(identifier) {
+ return "", errors.New("invalid DID hex encoding")
+ }
+
+ return identifier, nil
+}
+
+// IsDID reports whether the given string is a valid certchain DID.
+//
+// Expected format:
+//
+// did:certchain:0x<64 lowercase hex chars>
+func IsDID(did string) bool {
+ _, err := ParseDID(did)
+ return err == nil
+}
diff --git a/internal/crypto/hash.go b/internal/crypto/hash.go
@@ -0,0 +1,78 @@
+// Copyright 2026 Shivakumar (Certichain)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package crypto
+
+import (
+ "crypto/sha256"
+ "encoding/binary"
+ "errors"
+)
+
+const (
+ MaxFieldSize = 16 * 1024 * 1024 // 16 MB
+ lengthPrefixSize = 8 // 8 bytes for uint64
+ HashSize = 32 // sha256 digest
+)
+
+type Hash [HashSize]byte
+
+// CanonicalBytes function encodes the fields into a determinstic
+// byte sequence:
+//
+// |[len(field_1)][field_1][len(field_2)][field_2]...|
+//
+// Each lenght is encoded as an uint64 BigEndian.
+func CanonicalBytes(fields ...[]byte) ([]byte, error) {
+ bufSize := 0
+ for _, field := range fields {
+ if len(field) > MaxFieldSize {
+ return nil, errors.New("canonicalbytes: field too large")
+ }
+ bufSize += lengthPrefixSize + len(field)
+ }
+
+ byteArr := make([]byte, bufSize)
+ offset := 0
+ for _, field := range fields {
+ binary.BigEndian.PutUint64(
+ byteArr[offset:offset+8],
+ uint64(len(field)),
+ )
+
+ offset += lengthPrefixSize
+
+ copy(byteArr[offset:offset+len(field)], field)
+
+ offset += len(field)
+ }
+
+ return byteArr, nil
+}
+
+// HashBytes computes the SHA-256 hash of the data.
+func HashBytes(data []byte) Hash {
+ return sha256.Sum256(data)
+}
+
+// HashCanonical function canonicalises the fields and hashes them
+// to get a SHA-256 32 byte digest.
+func HashCanonical(fields ...[]byte) (Hash, error) {
+ canonical, err := CanonicalBytes(fields...)
+ if err != nil {
+ return Hash{}, err
+ }
+
+ return HashBytes(canonical), nil
+}
diff --git a/internal/crypto/keys.go b/internal/crypto/keys.go
@@ -0,0 +1,161 @@
+// Copyright 2026 Shivakumar (Certichain)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package crypto
+
+import (
+ "crypto/ed25519"
+ "crypto/rand"
+ "crypto/x509"
+ "encoding/pem"
+ "errors"
+ "fmt"
+)
+
+// GenerateKeyPair generates a new Ed25519 keypair (public, private)
+// using cryptographically secure random source.
+func GenerateKeyPair() (ed25519.PublicKey, ed25519.PrivateKey, error) {
+ return ed25519.GenerateKey(rand.Reader)
+}
+
+// PrivateKeyToPEM serilizes a Ed25519 private key into PEM-encoded
+// PKCS#8 format.
+//
+// Output format:
+//
+// -----BEGIN PRIVATE KEY-----
+// (base64 PKCS#8 DER bytes)
+// -----END PRIVATE KEY-----
+func PrivateKeyToPEM(key ed25519.PrivateKey) ([]byte, error) {
+ if len(key) != ed25519.PrivateKeySize {
+ return nil, errors.New("invalid Ed25519 private key size")
+ }
+
+ der, err := x509.MarshalPKCS8PrivateKey(key)
+ if err != nil {
+ return nil, fmt.Errorf("marshalling private key: %w", err)
+ }
+
+ block := &pem.Block{
+ Type: "PRIVATE KEY",
+ Bytes: der,
+ }
+
+ return pem.EncodeToMemory(block), nil
+}
+
+// PublicKeyToPEM serilizes a Ed25519 public key into PEM-encoded
+// PKIS format.
+//
+// Output format:
+//
+// -----BEGIN PUBLIC KEY-----
+// (base64 PKIX DER bytes)
+// -----END PUBLIC KEY-----
+func PublicKeyToPEM(key ed25519.PublicKey) ([]byte, error) {
+ if len(key) != ed25519.PublicKeySize {
+ return nil, errors.New("invalid Ed25519 public key size")
+ }
+
+ der, err := x509.MarshalPKIXPublicKey(key)
+ if err != nil {
+ return nil, fmt.Errorf("marshalling public key: %w", err)
+ }
+
+ block := &pem.Block{
+ Type: "PUBLIC KEY",
+ Bytes: der,
+ }
+
+ return pem.EncodeToMemory(block), nil
+}
+
+// PrivateKeyFromPEM parses a PEM-encoded PKCS#8 Ed25519 private key
+// and validates its structure and size.
+//
+// Expected PEM type:
+//
+// PRIVATE KEY
+func PrivateKeyFromPEM(pemBytes []byte) (ed25519.PrivateKey, error) {
+ block, rest := pem.Decode(pemBytes)
+ if block == nil {
+ return nil, errors.New("invalid PEM data")
+ }
+
+ if len(rest) != 0 {
+ return nil, errors.New("extra trailing data after PEM block")
+ }
+
+ if block.Type != "PRIVATE KEY" {
+ return nil, errors.New("PEM does not contain a private key")
+ }
+
+ key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
+ if err != nil {
+ return nil, fmt.Errorf("parseing private key: %w", err)
+ }
+
+ privateKey, ok := key.(ed25519.PrivateKey)
+ if !ok {
+ return nil, errors.New("not an Ed25519 key type")
+ }
+
+ if len(privateKey) != ed25519.PrivateKeySize {
+ return nil, errors.New("invalid private key")
+ }
+
+ return privateKey, nil
+}
+
+// PublicKeyFromPEM parses a PEM-encoded PKIS Ed25519 public key
+// and validates its structure and size.
+//
+// Expected PEM type:
+//
+// PUBLIC KEY
+func PublicKeyFromPEM(pemBytes []byte) (ed25519.PublicKey, error) {
+ block, rest := pem.Decode(pemBytes)
+ if block == nil {
+ return nil, errors.New("invalid PEM data")
+ }
+
+ if len(rest) != 0 {
+ return nil, errors.New("extra trailing data after pem block")
+ }
+
+ if block.Type != "PUBLIC KEY" {
+ return nil, errors.New("PEM does not contain public key")
+ }
+
+ key, err := x509.ParsePKIXPublicKey(block.Bytes)
+ if err != nil {
+ return nil, fmt.Errorf("parseing private key: %w", err)
+ }
+
+ publicKey, ok := key.(ed25519.PublicKey)
+ if !ok {
+ return nil, errors.New("not an Ed25519 public key type")
+ }
+
+ if len(publicKey) != ed25519.PublicKeySize {
+ return nil, errors.New("invalid Ed25519 public key size")
+ }
+
+ return publicKey, nil
+}
+
+// PublicKeyFromPrivate derives the Ed25519 public key from the private key
+func PublicKeyFromPrivate(key ed25519.PrivateKey) ed25519.PublicKey {
+ return key.Public().(ed25519.PublicKey)
+}