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.6 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 := len(plaintextKey); l == 0 || l%cipherFunc.blockSize() != 0 {
  77. return nil, cipherFunc, errors.StructuralError("length of decrypted key not a multiple of block size")
  78. }
  79. return plaintextKey, cipherFunc, nil
  80. }
  81. // SerializeSymmetricKeyEncrypted serializes a symmetric key packet to w. The
  82. // packet contains a random session key, encrypted by a key derived from the
  83. // given passphrase. The session key is returned and must be passed to
  84. // SerializeSymmetricallyEncrypted.
  85. // If config is nil, sensible defaults will be used.
  86. func SerializeSymmetricKeyEncrypted(w io.Writer, passphrase []byte, config *Config) (key []byte, err error) {
  87. cipherFunc := config.Cipher()
  88. keySize := cipherFunc.KeySize()
  89. if keySize == 0 {
  90. return nil, errors.UnsupportedError("unknown cipher: " + strconv.Itoa(int(cipherFunc)))
  91. }
  92. s2kBuf := new(bytes.Buffer)
  93. keyEncryptingKey := make([]byte, keySize)
  94. // s2k.Serialize salts and stretches the passphrase, and writes the
  95. // resulting key to keyEncryptingKey and the s2k descriptor to s2kBuf.
  96. err = s2k.Serialize(s2kBuf, keyEncryptingKey, config.Random(), passphrase, &s2k.Config{Hash: config.Hash(), S2KCount: config.PasswordHashIterations()})
  97. if err != nil {
  98. return
  99. }
  100. s2kBytes := s2kBuf.Bytes()
  101. packetLength := 2 /* header */ + len(s2kBytes) + 1 /* cipher type */ + keySize
  102. err = serializeHeader(w, packetTypeSymmetricKeyEncrypted, packetLength)
  103. if err != nil {
  104. return
  105. }
  106. var buf [2]byte
  107. buf[0] = symmetricKeyEncryptedVersion
  108. buf[1] = byte(cipherFunc)
  109. _, err = w.Write(buf[:])
  110. if err != nil {
  111. return
  112. }
  113. _, err = w.Write(s2kBytes)
  114. if err != nil {
  115. return
  116. }
  117. sessionKey := make([]byte, keySize)
  118. _, err = io.ReadFull(config.Random(), sessionKey)
  119. if err != nil {
  120. return
  121. }
  122. iv := make([]byte, cipherFunc.blockSize())
  123. c := cipher.NewCFBEncrypter(cipherFunc.new(keyEncryptingKey), iv)
  124. encryptedCipherAndKey := make([]byte, keySize+1)
  125. c.XORKeyStream(encryptedCipherAndKey, buf[1:])
  126. c.XORKeyStream(encryptedCipherAndKey[1:], sessionKey)
  127. _, err = w.Write(encryptedCipherAndKey)
  128. if err != nil {
  129. return
  130. }
  131. key = sessionKey
  132. return
  133. }