You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

156 lines
4.7 KiB

  1. // Copyright 2011 The Go 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. package packet
  5. import (
  6. "bytes"
  7. "crypto/cipher"
  8. "io"
  9. "strconv"
  10. "golang.org/x/crypto/openpgp/errors"
  11. "golang.org/x/crypto/openpgp/s2k"
  12. )
  13. // This is the largest session key that we'll support. Since no 512-bit cipher
  14. // has even been seriously used, this is comfortably large.
  15. const maxSessionKeySizeInBytes = 64
  16. // SymmetricKeyEncrypted represents a passphrase protected session key. See RFC
  17. // 4880, section 5.3.
  18. type SymmetricKeyEncrypted struct {
  19. CipherFunc CipherFunction
  20. s2k func(out, in []byte)
  21. encryptedKey []byte
  22. }
  23. const symmetricKeyEncryptedVersion = 4
  24. func (ske *SymmetricKeyEncrypted) parse(r io.Reader) error {
  25. // RFC 4880, section 5.3.
  26. var buf [2]byte
  27. if _, err := readFull(r, buf[:]); err != nil {
  28. return err
  29. }
  30. if buf[0] != symmetricKeyEncryptedVersion {
  31. return errors.UnsupportedError("SymmetricKeyEncrypted version")
  32. }
  33. ske.CipherFunc = CipherFunction(buf[1])
  34. if ske.CipherFunc.KeySize() == 0 {
  35. return errors.UnsupportedError("unknown cipher: " + strconv.Itoa(int(buf[1])))
  36. }
  37. var err error
  38. ske.s2k, err = s2k.Parse(r)
  39. if err != nil {
  40. return err
  41. }
  42. encryptedKey := make([]byte, maxSessionKeySizeInBytes)
  43. // The session key may follow. We just have to try and read to find
  44. // out. If it exists then we limit it to maxSessionKeySizeInBytes.
  45. n, err := readFull(r, encryptedKey)
  46. if err != nil && err != io.ErrUnexpectedEOF {
  47. return err
  48. }
  49. if n != 0 {
  50. if n == maxSessionKeySizeInBytes {
  51. return errors.UnsupportedError("oversized encrypted session key")
  52. }
  53. ske.encryptedKey = encryptedKey[:n]
  54. }
  55. return nil
  56. }
  57. // Decrypt attempts to decrypt an encrypted session key and returns the key and
  58. // the cipher to use when decrypting a subsequent Symmetrically Encrypted Data
  59. // packet.
  60. func (ske *SymmetricKeyEncrypted) Decrypt(passphrase []byte) ([]byte, CipherFunction, error) {
  61. key := make([]byte, ske.CipherFunc.KeySize())
  62. ske.s2k(key, passphrase)
  63. if len(ske.encryptedKey) == 0 {
  64. return key, ske.CipherFunc, nil
  65. }
  66. // the IV is all zeros
  67. iv := make([]byte, ske.CipherFunc.blockSize())
  68. c := cipher.NewCFBDecrypter(ske.CipherFunc.new(key), iv)
  69. plaintextKey := make([]byte, len(ske.encryptedKey))
  70. c.XORKeyStream(plaintextKey, ske.encryptedKey)
  71. cipherFunc := CipherFunction(plaintextKey[0])
  72. if cipherFunc.blockSize() == 0 {
  73. return nil, ske.CipherFunc, errors.UnsupportedError("unknown cipher: " + strconv.Itoa(int(cipherFunc)))
  74. }
  75. plaintextKey = plaintextKey[1:]
  76. if l, cipherKeySize := len(plaintextKey), cipherFunc.KeySize(); l != cipherFunc.KeySize() {
  77. return nil, cipherFunc, errors.StructuralError("length of decrypted key (" + strconv.Itoa(l) + ") " +
  78. "not equal to cipher keysize (" + strconv.Itoa(cipherKeySize) + ")")
  79. }
  80. return plaintextKey, cipherFunc, nil
  81. }
  82. // SerializeSymmetricKeyEncrypted serializes a symmetric key packet to w. The
  83. // packet contains a random session key, encrypted by a key derived from the
  84. // given passphrase. The session key is returned and must be passed to
  85. // SerializeSymmetricallyEncrypted.
  86. // If config is nil, sensible defaults will be used.
  87. func SerializeSymmetricKeyEncrypted(w io.Writer, passphrase []byte, config *Config) (key []byte, err error) {
  88. cipherFunc := config.Cipher()
  89. keySize := cipherFunc.KeySize()
  90. if keySize == 0 {
  91. return nil, errors.UnsupportedError("unknown cipher: " + strconv.Itoa(int(cipherFunc)))
  92. }
  93. s2kBuf := new(bytes.Buffer)
  94. keyEncryptingKey := make([]byte, keySize)
  95. // s2k.Serialize salts and stretches the passphrase, and writes the
  96. // resulting key to keyEncryptingKey and the s2k descriptor to s2kBuf.
  97. err = s2k.Serialize(s2kBuf, keyEncryptingKey, config.Random(), passphrase, &s2k.Config{Hash: config.Hash(), S2KCount: config.PasswordHashIterations()})
  98. if err != nil {
  99. return
  100. }
  101. s2kBytes := s2kBuf.Bytes()
  102. packetLength := 2 /* header */ + len(s2kBytes) + 1 /* cipher type */ + keySize
  103. err = serializeHeader(w, packetTypeSymmetricKeyEncrypted, packetLength)
  104. if err != nil {
  105. return
  106. }
  107. var buf [2]byte
  108. buf[0] = symmetricKeyEncryptedVersion
  109. buf[1] = byte(cipherFunc)
  110. _, err = w.Write(buf[:])
  111. if err != nil {
  112. return
  113. }
  114. _, err = w.Write(s2kBytes)
  115. if err != nil {
  116. return
  117. }
  118. sessionKey := make([]byte, keySize)
  119. _, err = io.ReadFull(config.Random(), sessionKey)
  120. if err != nil {
  121. return
  122. }
  123. iv := make([]byte, cipherFunc.blockSize())
  124. c := cipher.NewCFBEncrypter(cipherFunc.new(keyEncryptingKey), iv)
  125. encryptedCipherAndKey := make([]byte, keySize+1)
  126. c.XORKeyStream(encryptedCipherAndKey, buf[1:])
  127. c.XORKeyStream(encryptedCipherAndKey[1:], sessionKey)
  128. _, err = w.Write(encryptedCipherAndKey)
  129. if err != nil {
  130. return
  131. }
  132. key = sessionKey
  133. return
  134. }