22
22
// 4880, section 5.3.
23
23
type SymmetricKeyEncrypted struct {
24
24
CipherFunc CipherFunction
26
Key []byte // Empty unless Encrypted is false.
27
25
s2k func(out, in []byte)
28
26
encryptedKey []byte
31
29
const symmetricKeyEncryptedVersion = 4
33
func (ske *SymmetricKeyEncrypted) parse(r io.Reader) (err error) {
31
func (ske *SymmetricKeyEncrypted) parse(r io.Reader) error {
34
32
// RFC 4880, section 5.3.
36
_, err = readFull(r, buf[:])
34
if _, err := readFull(r, buf[:]); err != nil {
40
37
if buf[0] != symmetricKeyEncryptedVersion {
41
38
return errors.UnsupportedError("SymmetricKeyEncrypted version")
56
54
// out. If it exists then we limit it to maxSessionKeySizeInBytes.
57
55
n, err := readFull(r, encryptedKey)
58
56
if err != nil && err != io.ErrUnexpectedEOF {
63
61
if n == maxSessionKeySizeInBytes {
64
62
return errors.UnsupportedError("oversized encrypted session key")
66
64
ske.encryptedKey = encryptedKey[:n]
74
// Decrypt attempts to decrypt an encrypted session key. If it returns nil,
75
// ske.Key will contain the session key.
76
func (ske *SymmetricKeyEncrypted) Decrypt(passphrase []byte) error {
70
// Decrypt attempts to decrypt an encrypted session key and returns the key and
71
// the cipher to use when decrypting a subsequent Symmetrically Encrypted Data
73
func (ske *SymmetricKeyEncrypted) Decrypt(passphrase []byte) ([]byte, CipherFunction, error) {
81
74
key := make([]byte, ske.CipherFunc.KeySize())
82
75
ske.s2k(key, passphrase)
84
77
if len(ske.encryptedKey) == 0 {
87
// the IV is all zeros
88
iv := make([]byte, ske.CipherFunc.blockSize())
89
c := cipher.NewCFBDecrypter(ske.CipherFunc.new(key), iv)
90
c.XORKeyStream(ske.encryptedKey, ske.encryptedKey)
91
ske.CipherFunc = CipherFunction(ske.encryptedKey[0])
92
if ske.CipherFunc.blockSize() == 0 {
93
return errors.UnsupportedError("unknown cipher: " + strconv.Itoa(int(ske.CipherFunc)))
95
ske.CipherFunc = CipherFunction(ske.encryptedKey[0])
96
ske.Key = ske.encryptedKey[1:]
97
if len(ske.Key)%ske.CipherFunc.blockSize() != 0 {
99
return errors.StructuralError("length of decrypted key not a multiple of block size")
103
ske.Encrypted = false
78
return key, ske.CipherFunc, nil
81
// the IV is all zeros
82
iv := make([]byte, ske.CipherFunc.blockSize())
83
c := cipher.NewCFBDecrypter(ske.CipherFunc.new(key), iv)
84
plaintextKey := make([]byte, len(ske.encryptedKey))
85
c.XORKeyStream(plaintextKey, ske.encryptedKey)
86
cipherFunc := CipherFunction(plaintextKey[0])
87
if cipherFunc.blockSize() == 0 {
88
return nil, ske.CipherFunc, errors.UnsupportedError("unknown cipher: " + strconv.Itoa(int(cipherFunc)))
90
plaintextKey = plaintextKey[1:]
91
if l := len(plaintextKey); l == 0 || l%cipherFunc.blockSize() != 0 {
92
return nil, cipherFunc, errors.StructuralError("length of decrypted key not a multiple of block size")
95
return plaintextKey, cipherFunc, nil
107
98
// SerializeSymmetricKeyEncrypted serializes a symmetric key packet to w. The