forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
armor62_encrypt.go
66 lines (59 loc) · 2.12 KB
/
armor62_encrypt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.
package kbcmf
import (
"bytes"
"io"
)
type closeForwarder []io.WriteCloser
func (c closeForwarder) Write(b []byte) (int, error) {
return c[0].Write(b)
}
func (c closeForwarder) Close() error {
for _, w := range c {
if e := w.Close(); e != nil {
return e
}
}
return nil
}
// NewEncryptArmor62Stream creates a stream that consumes plaintext data.
// It will write out encrypted data to the io.Writer passed in as ciphertext.
// The encryption is from the specified sender, and is encrypted for the
// given receivers. Note that receivers as specified as two-dimensional array.
// Each inner group of receivers shares the same pairwise MAC-key, so should
// represent a logic receiver split across multiple devices. Each group of
// receivers represents a mutually distrustful set of receivers, and will each
// get their own pairwise-MAC keys.
//
// The ciphertext is additionally armored with the recommended armor62-style format.
//
// Returns an io.WriteCloser that accepts plaintext data to be encrypted; and
// also returns an error if initialization failed.
func NewEncryptArmor62Stream(ciphertext io.Writer, sender BoxSecretKey, receivers [][]BoxPublicKey) (plaintext io.WriteCloser, err error) {
enc, err := NewArmor62EncoderStream(ciphertext, EncryptionArmorHeader, EncryptionArmorFooter)
if err != nil {
return nil, err
}
out, err := NewEncryptStream(enc, sender, receivers)
if err != nil {
return nil, err
}
return closeForwarder([]io.WriteCloser{out, enc}), nil
}
// EncryptArmor62Seal is the non-streaming version of NewEncryptArmor62Stream, which
// inputs a plaintext (in bytes) and output a ciphertext (as a string).
func EncryptArmor62Seal(plaintext []byte, sender BoxSecretKey, receivers [][]BoxPublicKey) (string, error) {
var buf bytes.Buffer
enc, err := NewEncryptArmor62Stream(&buf, sender, receivers)
if err != nil {
return "", err
}
if _, err := enc.Write(plaintext); err != nil {
return "", err
}
if err := enc.Close(); err != nil {
return "", err
}
return buf.String(), nil
}