did.go (2077B)
1 // Copyright 2026 Shivakumar (Certichain) 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package crypto 16 17 import ( 18 "crypto/ed25519" 19 "encoding/hex" 20 "errors" 21 "strings" 22 ) 23 24 const ( 25 DIDPrefix = "did:certchain:0x" 26 DIDHashLength = 64 // SHA-256 hex length 27 ) 28 29 // NewDID derives a deterministic DID from an Ed25519 public key. 30 // 31 // Format: 32 // 33 // did:certchain:0x<sha256(public-key)> 34 func NewDID(publicKey ed25519.PublicKey) (string, error) { 35 if len(publicKey) != ed25519.PublicKeySize { 36 return "", errors.New("invalid Ed25519 public key") 37 } 38 39 hash := HashBytes(publicKey) 40 41 return DIDPrefix + hex.EncodeToString(hash[:]), nil 42 } 43 44 // ParseDID validates and parses a certchain DID. 45 // 46 // Expected format: 47 // 48 // did:certchain:0x<64 lowercase hex chars> 49 func ParseDID(did string) (string, error) { 50 if strings.TrimSpace(did) != did { 51 return "", errors.New("invalid DID") 52 } 53 54 if !strings.HasPrefix(did, DIDPrefix) { 55 return "", errors.New("invalid DID prefix") 56 } 57 58 identifier := strings.TrimPrefix(did, DIDPrefix) 59 if len(identifier) != DIDHashLength { 60 return "", errors.New("invalid DID length") 61 } 62 63 if _, err := hex.DecodeString(identifier); err != nil { 64 return "", errors.New("invalid DID hex encoding") 65 } 66 67 if identifier != strings.ToLower(identifier) { 68 return "", errors.New("invalid DID hex encoding") 69 } 70 71 return identifier, nil 72 } 73 74 // IsDID reports whether the given string is a valid certchain DID. 75 // 76 // Expected format: 77 // 78 // did:certchain:0x<64 lowercase hex chars> 79 func IsDID(did string) bool { 80 _, err := ParseDID(did) 81 return err == nil 82 }