github.com/hyperledger/aries-framework-go@v0.3.2/pkg/didcomm/packer/legacy/anoncrypt/anoncrypt.go (about) 1 /* 2 Copyright Avast Software. All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package anoncryt 8 9 import ( 10 "crypto/rand" 11 "io" 12 13 "github.com/hyperledger/aries-framework-go/pkg/didcomm/packer" 14 "github.com/hyperledger/aries-framework-go/pkg/kms" 15 "github.com/hyperledger/aries-framework-go/pkg/kms/localkms" 16 "github.com/hyperledger/aries-framework-go/pkg/kms/webkms" 17 ) 18 19 // Packer represents an Anoncrypt Pack/Unpacker that outputs/reads legacy Aries envelopes. 20 type Packer struct { 21 randSource io.Reader 22 kms kms.KeyManager 23 } 24 25 // encodingType is the `typ` string identifier in a message that identifies the format as being legacy. 26 const encodingType string = "JWM/1.0" 27 28 // Anoncrypt type. 29 const anonCrypt string = "Anoncrypt" 30 31 // Anoncrypt encryption type format. 32 const anonCryptEncType string = "chacha20poly1305_ietf" 33 34 // New will create a Packer that encrypts messages using the legacy Aries format. 35 // Note: legacy Packer does not support XChacha20Poly1035 (XC20P), only Chacha20Poly1035 (C20P). 36 func New(ctx packer.Provider) *Packer { 37 k := ctx.KMS() 38 39 return &Packer{ 40 randSource: rand.Reader, 41 kms: k, 42 } 43 } 44 45 // legacyEnvelope is the full payload envelope for the JSON message. 46 type legacyEnvelope struct { 47 Protected string `json:"protected,omitempty"` 48 IV string `json:"iv,omitempty"` 49 CipherText string `json:"ciphertext,omitempty"` 50 Tag string `json:"tag,omitempty"` 51 } 52 53 // protected is the protected header of the JSON envelope. 54 type protected struct { 55 Enc string `json:"enc,omitempty"` 56 Typ string `json:"typ,omitempty"` 57 Alg string `json:"alg,omitempty"` 58 Recipients []recipient `json:"recipients,omitempty"` 59 } 60 61 // recipient holds the data for a recipient in the envelope header. 62 type recipient struct { 63 EncryptedKey string `json:"encrypted_key,omitempty"` 64 Header recipientHeader `json:"header,omitempty"` 65 } 66 67 // recipientHeader holds the header data for a recipient. 68 type recipientHeader struct { 69 KID string `json:"kid,omitempty"` 70 } 71 72 // EncodingType returns the type of the encoding, as in the `Typ` field of the envelope header. 73 func (p *Packer) EncodingType() string { 74 return encodingType 75 } 76 77 func newCryptoBox(manager kms.KeyManager) (kms.CryptoBox, error) { 78 switch manager.(type) { 79 case *localkms.LocalKMS: 80 return localkms.NewCryptoBox(manager) 81 case *webkms.RemoteKMS: 82 return webkms.NewCryptoBox(manager) 83 default: 84 return localkms.NewCryptoBox(manager) 85 } 86 }