github.com/hyperledger/aries-framework-go@v0.3.2/pkg/didcomm/protocol/legacyconnection/keys.go (about) 1 /* 2 Copyright Avast Software. All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package legacyconnection 8 9 import ( 10 "encoding/json" 11 "fmt" 12 13 "github.com/hyperledger/aries-framework-go/pkg/crypto" 14 "github.com/hyperledger/aries-framework-go/pkg/doc/did" 15 "github.com/hyperledger/aries-framework-go/pkg/kms" 16 ) 17 18 func (ctx *context) createNewKeyAndVM(didDoc *did.Doc) error { 19 vm, err := ctx.createSigningVM() 20 if err != nil { 21 return err 22 } 23 24 kaVM, err := ctx.createEncryptionVM() 25 if err != nil { 26 return err 27 } 28 29 didDoc.VerificationMethod = append(didDoc.VerificationMethod, *vm) 30 didDoc.Authentication = append(didDoc.Authentication, *did.NewReferencedVerification(vm, did.Authentication)) 31 didDoc.KeyAgreement = append(didDoc.KeyAgreement, *did.NewReferencedVerification(kaVM, did.KeyAgreement)) 32 33 return nil 34 } 35 36 func (ctx *context) createSigningVM() (*did.VerificationMethod, error) { 37 vmType := getVerMethodType(ctx.keyType) 38 39 _, pubKeyBytes, err := ctx.kms.CreateAndExportPubKeyBytes(ctx.keyType) 40 if err != nil { 41 return nil, fmt.Errorf("createSigningVM: %w", err) 42 } 43 44 vmID := "#key-1" 45 46 switch vmType { 47 case ed25519VerificationKey2018: 48 return did.NewVerificationMethodFromBytes(vmID, vmType, "", pubKeyBytes), nil 49 default: 50 return nil, fmt.Errorf("createSigningVM: unsupported verification method: '%s'", vmType) 51 } 52 } 53 54 func (ctx *context) createEncryptionVM() (*did.VerificationMethod, error) { 55 encKeyType := ctx.keyAgreementType 56 57 vmType := getVerMethodType(encKeyType) 58 59 _, kaPubKeyBytes, err := ctx.kms.CreateAndExportPubKeyBytes(encKeyType) 60 if err != nil { 61 return nil, fmt.Errorf("createEncryptionVM: %w", err) 62 } 63 64 vmID := "#key-2" 65 66 switch vmType { 67 case x25519KeyAgreementKey2019: 68 key := &crypto.PublicKey{} 69 70 err = json.Unmarshal(kaPubKeyBytes, key) 71 if err != nil { 72 return nil, fmt.Errorf("createEncryptionVM: unable to unmarshal X25519 key: %w", err) 73 } 74 75 return did.NewVerificationMethodFromBytes(vmID, vmType, "", key.X), nil 76 default: 77 return nil, fmt.Errorf("unsupported verification method for KeyAgreement: '%s'", vmType) 78 } 79 } 80 81 // nolint:gochecknoglobals 82 var vmType = map[kms.KeyType]string{ 83 kms.ED25519Type: ed25519VerificationKey2018, 84 kms.X25519ECDHKWType: x25519KeyAgreementKey2019, 85 } 86 87 func getVerMethodType(kt kms.KeyType) string { 88 return vmType[kt] 89 }