Debian Codegraph @

age.go

raw symbols SCIP
1 // Copyright 2019 The age Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package age implements file encryption according to the age-encryption.org/v1
6 // specification.
7 //
8 // For most use cases, use the [Encrypt] and [Decrypt] functions with
9 // [HybridRecipient] and [HybridIdentity]. If passphrase encryption is
10 // required, use [ScryptRecipient] and [ScryptIdentity]. For compatibility with
11 // existing SSH keys use the filippo.io/age/agessh package.
12 //
13 // age encrypted files are binary and not malleable. For encoding them as text,
14 // use the filippo.io/age/armor package.
15 //
16 // # Key management
17 //
18 // age does not have a global keyring. Instead, since age keys are small,
19 // textual, and cheap, you are encouraged to generate dedicated keys for each
20 // task and application.
21 //
22 // Recipient public keys can be passed around as command line flags and in
23 // config files, while secret keys should be stored in dedicated files, through
24 // secret management systems, or as environment variables.
25 //
26 // There is no default path for age keys. Instead, they should be stored at
27 // application-specific paths. The CLI supports files where private keys are
28 // listed one per line, ignoring empty lines and lines starting with "#". These
29 // files can be parsed with [ParseIdentities].
30 //
31 // When integrating age into a new system, it's recommended that you only
32 // support native (X25519 and hybrid) keys, and not SSH keys. The latter are
33 // supported for manual encryption operations. If you need to tie into existing
34 // key management infrastructure, you might want to consider implementing your
35 // own [Recipient] and [Identity].
36 //
37 // # Backwards compatibility
38 //
39 // Files encrypted with a stable version (not alpha, beta, or release candidate)
40 // of age, or with any v1.0.0 beta or release candidate, will decrypt with any
41 // later versions of the v1 API. This might change in v2, in which case v1 will
42 // be maintained with security fixes for compatibility with older files.
43 //
44 // If decrypting an older file poses a security risk, doing so might require an
45 // explicit opt-in in the API.
46 package agescip-go gomod filippo.io/age . `filippo.io/age`/
47
48 import (
49 "bytesscip-go gomod github.com/golang/go/src . bytes/"
50 "crypto/hmacscip-go gomod github.com/golang/go/src . `crypto/hmac`/"
51 "crypto/randscip-go gomod github.com/golang/go/src . `crypto/rand`/"
52 "errorsscip-go gomod github.com/golang/go/src . errors/"
53 "fmtscip-go gomod github.com/golang/go/src . fmt/"
54 "ioscip-go gomod github.com/golang/go/src . io/"
55 "slicesscip-go gomod github.com/golang/go/src . slices/"
56 "sortscip-go gomod github.com/golang/go/src . sort/"
57
58 "filippo.io/age/internal/formatscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/"
59 "filippo.io/age/internal/streamscip-go gomod filippo.io/age . `filippo.io/age/internal/stream`/"
60 )
61
62 // An Identity is passed to [Decrypt] to unwrap an opaque file key from a
63 // recipient stanza. It can be for example a secret key like [HybridIdentity], a
64 // plugin, or a custom implementation.
65 type Identityscip-go gomod filippo.io/age . `filippo.io/age`/Identity# interface {
66 // Unwrap must return an error wrapping [ErrIncorrectIdentity] if none of
67 // the recipient stanzas match the identity, any other error will be
68 // considered fatal.
69 //
70 // Most age API users won't need to interact with this method directly, and
71 // should instead pass [Identity] implementations to [Decrypt].
72 Unwrapscip-go gomod filippo.io/age . `filippo.io/age`/Identity#Unwrap.(stanzas []*Stanzascip-go gomod filippo.io/age . `filippo.io/age`/Stanza#) (fileKey []byte, err error)
73 }
74
75 // ErrIncorrectIdentity is returned by [Identity.Unwrap] if none of the
76 // recipient stanzas match the identity.
77 var ErrIncorrectIdentityscip-go gomod filippo.io/age . `filippo.io/age`/ErrIncorrectIdentity. = errorsscip-go gomod github.com/golang/go/src . errors/.Newscip-go gomod github.com/golang/go/src . errors/New().("incorrect identity for recipient block")
78
79 // A Recipient is passed to [Encrypt] to wrap an opaque file key to one or more
80 // recipient stanza(s). It can be for example a public key like [HybridRecipient],
81 // a plugin, or a custom implementation.
82 type Recipientscip-go gomod filippo.io/age . `filippo.io/age`/Recipient# interface {
83 // Most age API users won't need to interact with this method directly, and
84 // should instead pass [Recipient] implementations to [Encrypt].
85 Wrapscip-go gomod filippo.io/age . `filippo.io/age`/Recipient#Wrap.(fileKey []byte) ([]*Stanzascip-go gomod filippo.io/age . `filippo.io/age`/Stanza#, error)
86 }
87
88 // RecipientWithLabels can be optionally implemented by a [Recipient], in which
89 // case [Encrypt] will use WrapWithLabels instead of [Recipient.Wrap].
90 //
91 // Encrypt will succeed only if the labels returned by all the recipients
92 // (assuming the empty set for those that don't implement RecipientWithLabels)
93 // are the same.
94 //
95 // This can be used to ensure a recipient is only used with other recipients
96 // with equivalent properties (for example by setting a "postquantum" label) or
97 // to ensure a recipient is always used alone (by returning a random label, for
98 // example to preserve its authentication properties).
99 type RecipientWithLabelsscip-go gomod filippo.io/age . `filippo.io/age`/RecipientWithLabels# interface {
100 WrapWithLabelsscip-go gomod filippo.io/age . `filippo.io/age`/RecipientWithLabels#WrapWithLabels.(fileKey []byte) (s []*Stanzascip-go gomod filippo.io/age . `filippo.io/age`/Stanza#, labels []string, err error)
101 }
102
103 // A Stanza is a section of the age header that encapsulates the file key as
104 // encrypted to a specific recipient.
105 //
106 // Most age API users won't need to interact with this type directly, and should
107 // instead pass [Recipient] implementations to [Encrypt] and [Identity]
108 // implementations to [Decrypt].
109 type Stanzascip-go gomod filippo.io/age . `filippo.io/age`/Stanza# struct {
110 Typescip-go gomod filippo.io/age . `filippo.io/age`/Stanza#Type. string
111 Argsscip-go gomod filippo.io/age . `filippo.io/age`/Stanza#Args. []string
112 Bodyscip-go gomod filippo.io/age . `filippo.io/age`/Stanza#Body. []byte
113 }
114
115 const fileKeySizescip-go gomod filippo.io/age . `filippo.io/age`/fileKeySize. = 16
116 const streamNonceSizescip-go gomod filippo.io/age . `filippo.io/age`/streamNonceSize. = 16
117
118 func encryptHdrscip-go gomod filippo.io/age . `filippo.io/age`/encryptHdr().(fileKey []byte, recipients ...Recipientscip-go gomod filippo.io/age . `filippo.io/age`/Recipient#) (*formatscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/.Headerscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/Header#, error) {
119 if len(recipients) == 0 {
120 return nil, errorsscip-go gomod github.com/golang/go/src . errors/.Newscip-go gomod github.com/golang/go/src . errors/New().("no recipients specified")
121 }
122
123 hdr := &formatscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/.Headerscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/Header#{}
124 var labels []string
125 for i, r := range recipients {
126 stanzas, l, err := wrapWithLabelsscip-go gomod filippo.io/age . `filippo.io/age`/wrapWithLabels().(r, fileKey)
127 if err != nil {
128 return nil, fmtscip-go gomod github.com/golang/go/src . fmt/.Errorfscip-go gomod github.com/golang/go/src . fmt/Errorf().("failed to wrap key for recipient #%d: %w", i, err)
129 }
130 sortscip-go gomod github.com/golang/go/src . sort/.Stringsscip-go gomod github.com/golang/go/src . sort/Strings().(l)
131 if i == 0 {
132 labels = l
133 } else if !slicesscip-go gomod github.com/golang/go/src . slices/.Equalscip-go gomod github.com/golang/go/src . slices/Equal().(labels, l) {
134 return nil, incompatibleLabelsErrorscip-go gomod filippo.io/age . `filippo.io/age`/incompatibleLabelsError().(labels, l)
135 }
136 for _, s := range stanzas {
137 hdr.Recipientsscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/Header#Recipients. = append(hdr.Recipientsscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/Header#Recipients., (*formatscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/.Stanzascip-go gomod filippo.io/age . `filippo.io/age/internal/format`/Stanza#)(s))
138 }
139 }
140 if mac, err := headerMACscip-go gomod filippo.io/age . `filippo.io/age`/headerMAC().(fileKey, hdr); err != nil {
141 return nil, fmtscip-go gomod github.com/golang/go/src . fmt/.Errorfscip-go gomod github.com/golang/go/src . fmt/Errorf().("failed to compute header MAC: %v", err)
142 } else {
143 hdr.MACscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/Header#MAC. = mac
144 }
145 return hdr, nil
146 }
147
148 // Encrypt encrypts a file to one or more recipients. Every recipient will be
149 // able to decrypt the file.
150 //
151 // Writes to the returned WriteCloser are encrypted and written to dst as an age
152 // file. The caller must call Close on the WriteCloser when done for the last
153 // chunk to be encrypted and flushed to dst.
154 func Encryptscip-go gomod filippo.io/age . `filippo.io/age`/Encrypt().(dst ioscip-go gomod github.com/golang/go/src . io/.Writerscip-go gomod github.com/golang/go/src . io/Writer#, recipients ...Recipientscip-go gomod filippo.io/age . `filippo.io/age`/Recipient#) (ioscip-go gomod github.com/golang/go/src . io/.WriteCloserscip-go gomod github.com/golang/go/src . io/WriteCloser#, error) {
155 fileKey := make([]byte, fileKeySizescip-go gomod filippo.io/age . `filippo.io/age`/fileKeySize.)
156 randscip-go gomod github.com/golang/go/src . `crypto/rand`/.Readscip-go gomod github.com/golang/go/src . `crypto/rand`/Read().(fileKey)
157
158 hdr, err := encryptHdrscip-go gomod filippo.io/age . `filippo.io/age`/encryptHdr().(fileKey, recipients...)
159 if err != nil {
160 return nil, err
161 }
162 if err := hdr.Marshalscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/Header#Marshal().(dst); err != nil {
163 return nil, fmtscip-go gomod github.com/golang/go/src . fmt/.Errorfscip-go gomod github.com/golang/go/src . fmt/Errorf().("failed to write header: %w", err)
164 }
165
166 nonce := make([]byte, streamNonceSizescip-go gomod filippo.io/age . `filippo.io/age`/streamNonceSize.)
167 randscip-go gomod github.com/golang/go/src . `crypto/rand`/.Readscip-go gomod github.com/golang/go/src . `crypto/rand`/Read().(nonce)
168 if _, err := dst.Writescip-go gomod github.com/golang/go/src . io/Writer#Write().(nonce); err != nil {
169 return nil, fmtscip-go gomod github.com/golang/go/src . fmt/.Errorfscip-go gomod github.com/golang/go/src . fmt/Errorf().("failed to write nonce: %w", err)
170 }
171
172 return streamscip-go gomod filippo.io/age . `filippo.io/age/internal/stream`/.NewEncryptWriterscip-go gomod filippo.io/age . `filippo.io/age/internal/stream`/NewEncryptWriter().(streamKeyscip-go gomod filippo.io/age . `filippo.io/age`/streamKey().(fileKey, nonce), dst)
173 }
174
175 // EncryptReader encrypts a file to one or more recipients. Every recipient will be
176 // able to decrypt the file.
177 //
178 // Reads from the returned Reader produce the encrypted file, where the plaintext
179 // is read from src.
180 func EncryptReaderscip-go gomod filippo.io/age . `filippo.io/age`/EncryptReader().(src ioscip-go gomod github.com/golang/go/src . io/.Readerscip-go gomod github.com/golang/go/src . io/Reader#, recipients ...Recipientscip-go gomod filippo.io/age . `filippo.io/age`/Recipient#) (ioscip-go gomod github.com/golang/go/src . io/.Readerscip-go gomod github.com/golang/go/src . io/Reader#, error) {
181 fileKey := make([]byte, fileKeySizescip-go gomod filippo.io/age . `filippo.io/age`/fileKeySize.)
182 randscip-go gomod github.com/golang/go/src . `crypto/rand`/.Readscip-go gomod github.com/golang/go/src . `crypto/rand`/Read().(fileKey)
183
184 hdr, err := encryptHdrscip-go gomod filippo.io/age . `filippo.io/age`/encryptHdr().(fileKey, recipients...)
185 if err != nil {
186 return nil, err
187 }
188 buf := &bytesscip-go gomod github.com/golang/go/src . bytes/.Bufferscip-go gomod github.com/golang/go/src . bytes/Buffer#{}
189 if err := hdr.Marshalscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/Header#Marshal().(buf); err != nil {
190 return nil, fmtscip-go gomod github.com/golang/go/src . fmt/.Errorfscip-go gomod github.com/golang/go/src . fmt/Errorf().("failed to prepare header: %w", err)
191 }
192
193 nonce := make([]byte, streamNonceSizescip-go gomod filippo.io/age . `filippo.io/age`/streamNonceSize.)
194 randscip-go gomod github.com/golang/go/src . `crypto/rand`/.Readscip-go gomod github.com/golang/go/src . `crypto/rand`/Read().(nonce)
195
196 r, err := streamscip-go gomod filippo.io/age . `filippo.io/age/internal/stream`/.NewEncryptReaderscip-go gomod filippo.io/age . `filippo.io/age/internal/stream`/NewEncryptReader().(streamKeyscip-go gomod filippo.io/age . `filippo.io/age`/streamKey().(fileKey, nonce), src)
197 if err != nil {
198 return nil, err
199 }
200 return ioscip-go gomod github.com/golang/go/src . io/.MultiReaderscip-go gomod github.com/golang/go/src . io/MultiReader().(buf, bytesscip-go gomod github.com/golang/go/src . bytes/.NewReaderscip-go gomod github.com/golang/go/src . bytes/NewReader().(nonce), r), nil
201 }
202
203 func wrapWithLabelsscip-go gomod filippo.io/age . `filippo.io/age`/wrapWithLabels().(r Recipientscip-go gomod filippo.io/age . `filippo.io/age`/Recipient#, fileKey []byte) (s []*Stanzascip-go gomod filippo.io/age . `filippo.io/age`/Stanza#, labels []string, err error) {
204 if r, ok := r.(RecipientWithLabelsscip-go gomod filippo.io/age . `filippo.io/age`/RecipientWithLabels#); ok {
205 return r.WrapWithLabelsscip-go gomod filippo.io/age . `filippo.io/age`/RecipientWithLabels#WrapWithLabels.(fileKey)
206 }
207 s, err = r.Wrapscip-go gomod filippo.io/age . `filippo.io/age`/Recipient#Wrap.(fileKey)
208 return
209 }
210
211 func incompatibleLabelsErrorscip-go gomod filippo.io/age . `filippo.io/age`/incompatibleLabelsError().(l1, l2 []string) error {
212 hasPQ1 := slicesscip-go gomod github.com/golang/go/src . slices/.Containsscip-go gomod github.com/golang/go/src . slices/Contains().(l1, "postquantum")
213 hasPQ2 := slicesscip-go gomod github.com/golang/go/src . slices/.Containsscip-go gomod github.com/golang/go/src . slices/Contains().(l2, "postquantum")
214 if hasPQ1 != hasPQ2 {
215 return fmtscip-go gomod github.com/golang/go/src . fmt/.Errorfscip-go gomod github.com/golang/go/src . fmt/Errorf().("incompatible recipients: can't mix post-quantum and classic recipients, or the file would be vulnerable to quantum computers")
216 }
217 return fmtscip-go gomod github.com/golang/go/src . fmt/.Errorfscip-go gomod github.com/golang/go/src . fmt/Errorf().("incompatible recipients: %q and %q can't be mixed", l1, l2)
218 }
219
220 // NoIdentityMatchError is returned by [Decrypt] when none of the supplied
221 // identities match the encrypted file.
222 type NoIdentityMatchErrorscip-go gomod filippo.io/age . `filippo.io/age`/NoIdentityMatchError# struct {
223 // Errors is a slice of all the errors returned to Decrypt by the Unwrap
224 // calls it made. They all wrap [ErrIncorrectIdentity].
225 Errorsscip-go gomod filippo.io/age . `filippo.io/age`/NoIdentityMatchError#Errors. []error
226 // StanzaTypes are the first argument of each recipient stanza in the
227 // encrypted file's header.
228 StanzaTypesscip-go gomod filippo.io/age . `filippo.io/age`/NoIdentityMatchError#StanzaTypes. []string
229 }
230
231 func (e *NoIdentityMatchErrorscip-go gomod filippo.io/age . `filippo.io/age`/NoIdentityMatchError#) Errorscip-go gomod filippo.io/age . `filippo.io/age`/NoIdentityMatchError#Error().() string {
232 if len(e.Errorsscip-go gomod filippo.io/age . `filippo.io/age`/NoIdentityMatchError#Errors.) == 1 {
233 return "identity did not match any of the recipients: " + e.Errorsscip-go gomod filippo.io/age . `filippo.io/age`/NoIdentityMatchError#Errors.[0].Error()
234 }
235 return "no identity matched any of the recipients"
236 }
237
238 func (e *NoIdentityMatchErrorscip-go gomod filippo.io/age . `filippo.io/age`/NoIdentityMatchError#) Unwrapscip-go gomod filippo.io/age . `filippo.io/age`/NoIdentityMatchError#Unwrap().() []error {
239 return e.Errorsscip-go gomod filippo.io/age . `filippo.io/age`/NoIdentityMatchError#Errors.
240 }
241
242 // Decrypt decrypts a file encrypted to one or more identities.
243 // All identities will be tried until one successfully decrypts the file.
244 // Native, non-interactive identities are tried before any other identities.
245 //
246 // Decrypt returns a Reader reading the decrypted plaintext of the age file read
247 // from src. If no identity matches the encrypted file, the returned error will
248 // be of type [NoIdentityMatchError].
249 func Decryptscip-go gomod filippo.io/age . `filippo.io/age`/Decrypt().(src ioscip-go gomod github.com/golang/go/src . io/.Readerscip-go gomod github.com/golang/go/src . io/Reader#, identities ...Identityscip-go gomod filippo.io/age . `filippo.io/age`/Identity#) (ioscip-go gomod github.com/golang/go/src . io/.Readerscip-go gomod github.com/golang/go/src . io/Reader#, error) {
250 hdr, payload, err := formatscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/.Parsescip-go gomod filippo.io/age . `filippo.io/age/internal/format`/Parse().(src)
251 if err != nil {
252 return nil, fmtscip-go gomod github.com/golang/go/src . fmt/.Errorfscip-go gomod github.com/golang/go/src . fmt/Errorf().("failed to read header: %w", err)
253 }
254
255 fileKey, err := decryptHdrscip-go gomod filippo.io/age . `filippo.io/age`/decryptHdr().(hdr, identities...)
256 if err != nil {
257 return nil, err
258 }
259
260 nonce := make([]byte, streamNonceSizescip-go gomod filippo.io/age . `filippo.io/age`/streamNonceSize.)
261 if _, err := ioscip-go gomod github.com/golang/go/src . io/.ReadFullscip-go gomod github.com/golang/go/src . io/ReadFull().(payload, nonce); err != nil {
262 return nil, fmtscip-go gomod github.com/golang/go/src . fmt/.Errorfscip-go gomod github.com/golang/go/src . fmt/Errorf().("failed to read nonce: %w", err)
263 }
264
265 return streamscip-go gomod filippo.io/age . `filippo.io/age/internal/stream`/.NewDecryptReaderscip-go gomod filippo.io/age . `filippo.io/age/internal/stream`/NewDecryptReader().(streamKeyscip-go gomod filippo.io/age . `filippo.io/age`/streamKey().(fileKey, nonce), payload)
266 }
267
268 // DecryptReaderAt decrypts a file encrypted to one or more identities.
269 // All identities will be tried until one successfully decrypts the file.
270 // Native, non-interactive identities are tried before any other identities.
271 //
272 // DecryptReaderAt takes an underlying [io.ReaderAt] and its total encrypted
273 // size, and returns a ReaderAt of the decrypted plaintext and the plaintext
274 // size. These can be used for example to instantiate an [io.SectionReader],
275 // which implements [io.Reader] and [io.Seeker], or for [zip.NewReader].
276 // Note that ReaderAt by definition disregards the seek position of src.
277 //
278 // The ReadAt method of the returned ReaderAt can be called concurrently.
279 // The ReaderAt will internally cache the most recently decrypted chunk.
280 // DecryptReaderAt reads and decrypts the final chunk before returning,
281 // to authenticate the plaintext size.
282 //
283 // If no identity matches the encrypted file, the returned error will be of
284 // type [NoIdentityMatchError].
285 func DecryptReaderAtscip-go gomod filippo.io/age . `filippo.io/age`/DecryptReaderAt().(src ioscip-go gomod github.com/golang/go/src . io/.ReaderAtscip-go gomod github.com/golang/go/src . io/ReaderAt#, encryptedSize int64, identities ...Identityscip-go gomod filippo.io/age . `filippo.io/age`/Identity#) (ioscip-go gomod github.com/golang/go/src . io/.ReaderAtscip-go gomod github.com/golang/go/src . io/ReaderAt#, int64, error) {
286 srcReader := ioscip-go gomod github.com/golang/go/src . io/.NewSectionReaderscip-go gomod github.com/golang/go/src . io/NewSectionReader().(src, 0, encryptedSize)
287 hdr, payload, err := formatscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/.Parsescip-go gomod filippo.io/age . `filippo.io/age/internal/format`/Parse().(srcReader)
288 if err != nil {
289 return nil, 0, fmtscip-go gomod github.com/golang/go/src . fmt/.Errorfscip-go gomod github.com/golang/go/src . fmt/Errorf().("failed to read header: %w", err)
290 }
291 buf := &bytesscip-go gomod github.com/golang/go/src . bytes/.Bufferscip-go gomod github.com/golang/go/src . bytes/Buffer#{}
292 if err := hdr.Marshalscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/Header#Marshal().(buf); err != nil {
293 return nil, 0, fmtscip-go gomod github.com/golang/go/src . fmt/.Errorfscip-go gomod github.com/golang/go/src . fmt/Errorf().("failed to serialize header: %w", err)
294 }
295
296 fileKey, err := decryptHdrscip-go gomod filippo.io/age . `filippo.io/age`/decryptHdr().(hdr, identities...)
297 if err != nil {
298 return nil, 0, err
299 }
300
301 nonce := make([]byte, streamNonceSizescip-go gomod filippo.io/age . `filippo.io/age`/streamNonceSize.)
302 if _, err := ioscip-go gomod github.com/golang/go/src . io/.ReadFullscip-go gomod github.com/golang/go/src . io/ReadFull().(payload, nonce); err != nil {
303 return nil, 0, fmtscip-go gomod github.com/golang/go/src . fmt/.Errorfscip-go gomod github.com/golang/go/src . fmt/Errorf().("failed to read nonce: %w", err)
304 }
305
306 payloadOffset := int64(buf.Lenscip-go gomod github.com/golang/go/src . bytes/Buffer#Len().()) + int64(len(nonce))
307 payloadSize := encryptedSize - payloadOffset
308 plaintextSize, err := streamscip-go gomod filippo.io/age . `filippo.io/age/internal/stream`/.PlaintextSizescip-go gomod filippo.io/age . `filippo.io/age/internal/stream`/PlaintextSize().(payloadSize)
309 if err != nil {
310 return nil, 0, err
311 }
312 payloadReaderAt := ioscip-go gomod github.com/golang/go/src . io/.NewSectionReaderscip-go gomod github.com/golang/go/src . io/NewSectionReader().(src, payloadOffset, payloadSize)
313 r, err := streamscip-go gomod filippo.io/age . `filippo.io/age/internal/stream`/.NewDecryptReaderAtscip-go gomod filippo.io/age . `filippo.io/age/internal/stream`/NewDecryptReaderAt().(streamKeyscip-go gomod filippo.io/age . `filippo.io/age`/streamKey().(fileKey, nonce), payloadReaderAt, payloadSize)
314 if err != nil {
315 return nil, 0, err
316 }
317 return r, plaintextSize, nil
318 }
319
320 func decryptHdrscip-go gomod filippo.io/age . `filippo.io/age`/decryptHdr().(hdr *formatscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/.Headerscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/Header#, identities ...Identityscip-go gomod filippo.io/age . `filippo.io/age`/Identity#) ([]byte, error) {
321 if len(identities) == 0 {
322 return nil, errorsscip-go gomod github.com/golang/go/src . errors/.Newscip-go gomod github.com/golang/go/src . errors/New().("no identities specified")
323 }
324 // Don't sort the caller's slice in place.
325 identities = slicesscip-go gomod github.com/golang/go/src . slices/.Clonescip-go gomod github.com/golang/go/src . slices/Clone().(identities)
326 slicesscip-go gomod github.com/golang/go/src . slices/.SortStableFuncscip-go gomod github.com/golang/go/src . slices/SortStableFunc().(identities, func(a, b Identityscip-go gomod filippo.io/age . `filippo.io/age`/Identity#) int {
327 var aIsNative, bIsNative bool
328 switch a.(type) {
329 case *X25519Identityscip-go gomod filippo.io/age . `filippo.io/age`/X25519Identity#, *HybridIdentityscip-go gomod filippo.io/age . `filippo.io/age`/HybridIdentity#, *ScryptIdentityscip-go gomod filippo.io/age . `filippo.io/age`/ScryptIdentity#:
330 aIsNative = true
331 }
332 switch b.(type) {
333 case *X25519Identityscip-go gomod filippo.io/age . `filippo.io/age`/X25519Identity#, *HybridIdentityscip-go gomod filippo.io/age . `filippo.io/age`/HybridIdentity#, *ScryptIdentityscip-go gomod filippo.io/age . `filippo.io/age`/ScryptIdentity#:
334 bIsNative = true
335 }
336 if aIsNative && !bIsNative {
337 return -1
338 }
339 if !aIsNative && bIsNative {
340 return 1
341 }
342 return 0
343 })
344
345 stanzas := make([]*Stanzascip-go gomod filippo.io/age . `filippo.io/age`/Stanza#, 0, len(hdr.Recipientsscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/Header#Recipients.))
346 errNoMatch := &NoIdentityMatchErrorscip-go gomod filippo.io/age . `filippo.io/age`/NoIdentityMatchError#{}
347 for _, s := range hdr.Recipientsscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/Header#Recipients. {
348 errNoMatch.StanzaTypesscip-go gomod filippo.io/age . `filippo.io/age`/NoIdentityMatchError#StanzaTypes. = append(errNoMatch.StanzaTypesscip-go gomod filippo.io/age . `filippo.io/age`/NoIdentityMatchError#StanzaTypes., s.Typescip-go gomod filippo.io/age . `filippo.io/age/internal/format`/Stanza#Type.)
349 stanzas = append(stanzas, (*Stanzascip-go gomod filippo.io/age . `filippo.io/age`/Stanza#)(s))
350 }
351 var fileKey []byte
352 for _, id := range identities {
353 var err error
354 fileKey, err = id.Unwrapscip-go gomod filippo.io/age . `filippo.io/age`/Identity#Unwrap.(stanzas)
355 if errorsscip-go gomod github.com/golang/go/src . errors/.Isscip-go gomod github.com/golang/go/src . errors/Is().(err, ErrIncorrectIdentityscip-go gomod filippo.io/age . `filippo.io/age`/ErrIncorrectIdentity.) {
356 errNoMatch.Errorsscip-go gomod filippo.io/age . `filippo.io/age`/NoIdentityMatchError#Errors. = append(errNoMatch.Errorsscip-go gomod filippo.io/age . `filippo.io/age`/NoIdentityMatchError#Errors., err)
357 continue
358 }
359 if err != nil {
360 return nil, err
361 }
362
363 break
364 }
365 if fileKey == nil {
366 return nil, errNoMatch
367 }
368
369 if mac, err := headerMACscip-go gomod filippo.io/age . `filippo.io/age`/headerMAC().(fileKey, hdr); err != nil {
370 return nil, fmtscip-go gomod github.com/golang/go/src . fmt/.Errorfscip-go gomod github.com/golang/go/src . fmt/Errorf().("failed to compute header MAC: %v", err)
371 } else if !hmacscip-go gomod github.com/golang/go/src . `crypto/hmac`/.Equalscip-go gomod github.com/golang/go/src . `crypto/hmac`/Equal().(mac, hdr.MACscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/Header#MAC.) {
372 return nil, errorsscip-go gomod github.com/golang/go/src . errors/.Newscip-go gomod github.com/golang/go/src . errors/New().("bad header MAC")
373 }
374
375 return fileKey, nil
376 }
377
378 // multiUnwrap is a helper that implements Identity.Unwrap in terms of a
379 // function that unwraps a single recipient stanza.
380 func multiUnwrapscip-go gomod filippo.io/age . `filippo.io/age`/multiUnwrap().(unwrap func(*Stanzascip-go gomod filippo.io/age . `filippo.io/age`/Stanza#) ([]byte, error), stanzas []*Stanzascip-go gomod filippo.io/age . `filippo.io/age`/Stanza#) ([]byte, error) {
381 for _, s := range stanzas {
382 fileKey, err := unwrap(s)
383 if errorsscip-go gomod github.com/golang/go/src . errors/.Isscip-go gomod github.com/golang/go/src . errors/Is().(err, ErrIncorrectIdentityscip-go gomod filippo.io/age . `filippo.io/age`/ErrIncorrectIdentity.) {
384 // If we ever start returning something interesting wrapping
385 // ErrIncorrectIdentity, we should let it make its way up through
386 // Decrypt into NoIdentityMatchError.Errors.
387 continue
388 }
389 if err != nil {
390 return nil, err
391 }
392 return fileKey, nil
393 }
394 return nil, ErrIncorrectIdentityscip-go gomod filippo.io/age . `filippo.io/age`/ErrIncorrectIdentity.
395 }
396
397 // ExtractHeader returns a detached header from the src file.
398 //
399 // The detached header can be decrypted with [DecryptHeader] (for example on a
400 // different system, without sharing the ciphertext) and then the file key can
401 // be used with [NewInjectedFileKeyIdentity].
402 //
403 // This is a low-level function that most users won't need.
404 func ExtractHeaderscip-go gomod filippo.io/age . `filippo.io/age`/ExtractHeader().(src ioscip-go gomod github.com/golang/go/src . io/.Readerscip-go gomod github.com/golang/go/src . io/Reader#) ([]byte, error) {
405 hdr, _, err := formatscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/.Parsescip-go gomod filippo.io/age . `filippo.io/age/internal/format`/Parse().(src)
406 if err != nil {
407 return nil, fmtscip-go gomod github.com/golang/go/src . fmt/.Errorfscip-go gomod github.com/golang/go/src . fmt/Errorf().("failed to read header: %w", err)
408 }
409 buf := &bytesscip-go gomod github.com/golang/go/src . bytes/.Bufferscip-go gomod github.com/golang/go/src . bytes/Buffer#{}
410 if err := hdr.Marshalscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/Header#Marshal().(buf); err != nil {
411 return nil, fmtscip-go gomod github.com/golang/go/src . fmt/.Errorfscip-go gomod github.com/golang/go/src . fmt/Errorf().("failed to serialize header: %w", err)
412 }
413 return buf.Bytesscip-go gomod github.com/golang/go/src . bytes/Buffer#Bytes().(), nil
414 }
415
416 // DecryptHeader decrypts a detached header and returns a file key.
417 //
418 // The detached header can be produced by [ExtractHeader], and the
419 // returned file key can be used with [NewInjectedFileKeyIdentity].
420 //
421 // This is a low-level function that most users won't need.
422 // It is the caller's responsibility to keep track of what file the
423 // returned file key decrypts, and to ensure the file key is not used
424 // for any other purpose.
425 func DecryptHeaderscip-go gomod filippo.io/age . `filippo.io/age`/DecryptHeader().(header []byte, identities ...Identityscip-go gomod filippo.io/age . `filippo.io/age`/Identity#) ([]byte, error) {
426 hdr, _, err := formatscip-go gomod filippo.io/age . `filippo.io/age/internal/format`/.Parsescip-go gomod filippo.io/age . `filippo.io/age/internal/format`/Parse().(bytesscip-go gomod github.com/golang/go/src . bytes/.NewReaderscip-go gomod github.com/golang/go/src . bytes/NewReader().(header))
427 if err != nil {
428 return nil, fmtscip-go gomod github.com/golang/go/src . fmt/.Errorfscip-go gomod github.com/golang/go/src . fmt/Errorf().("failed to read header: %w", err)
429 }
430 return decryptHdrscip-go gomod filippo.io/age . `filippo.io/age`/decryptHdr().(hdr, identities...)
431 }
432
433 type injectedFileKeyIdentityscip-go gomod filippo.io/age . `filippo.io/age`/injectedFileKeyIdentity# struct {
434 fileKeyscip-go gomod filippo.io/age . `filippo.io/age`/injectedFileKeyIdentity#fileKey. []byte
435 }
436
437 // NewInjectedFileKeyIdentity returns an [Identity] that always produces
438 // a fixed file key, allowing the use of a file key obtained out-of-band,
439 // for example via [DecryptHeader].
440 //
441 // This is a low-level function that most users won't need.
442 func NewInjectedFileKeyIdentityscip-go gomod filippo.io/age . `filippo.io/age`/NewInjectedFileKeyIdentity().(fileKey []byte) Identityscip-go gomod filippo.io/age . `filippo.io/age`/Identity# {
443 return injectedFileKeyIdentityscip-go gomod filippo.io/age . `filippo.io/age`/injectedFileKeyIdentity#{fileKey}
444 }
445
446 func (i injectedFileKeyIdentityscip-go gomod filippo.io/age . `filippo.io/age`/injectedFileKeyIdentity#) Unwrapscip-go gomod filippo.io/age . `filippo.io/age`/injectedFileKeyIdentity#Unwrap().(stanzas []*Stanzascip-go gomod filippo.io/age . `filippo.io/age`/Stanza#) (fileKey []byte, err error) {
447 return i.fileKeyscip-go gomod filippo.io/age . `filippo.io/age`/injectedFileKeyIdentity#fileKey., nil
448 }