pem_decrypt.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. // Copyright 2012 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 x509
  5. // RFC 1423 describes the encryption of PEM blocks. The algorithm used to
  6. // generate a key from the password was derived by looking at the OpenSSL
  7. // implementation.
  8. import (
  9. "crypto/aes"
  10. "crypto/cipher"
  11. "crypto/des"
  12. "crypto/md5"
  13. "encoding/hex"
  14. "encoding/pem"
  15. "errors"
  16. "io"
  17. "strings"
  18. )
  19. type PEMCipher int
  20. // Possible values for the EncryptPEMBlock encryption algorithm.
  21. const (
  22. _ PEMCipher = iota
  23. PEMCipherDES
  24. PEMCipher3DES
  25. PEMCipherAES128
  26. PEMCipherAES192
  27. PEMCipherAES256
  28. )
  29. // rfc1423Algo holds a method for enciphering a PEM block.
  30. type rfc1423Algo struct {
  31. cipher PEMCipher
  32. name string
  33. cipherFunc func(key []byte) (cipher.Block, error)
  34. keySize int
  35. blockSize int
  36. }
  37. // rfc1423Algos holds a slice of the possible ways to encrypt a PEM
  38. // block. The ivSize numbers were taken from the OpenSSL source.
  39. var rfc1423Algos = []rfc1423Algo{{
  40. cipher: PEMCipherDES,
  41. name: "DES-CBC",
  42. cipherFunc: des.NewCipher,
  43. keySize: 8,
  44. blockSize: des.BlockSize,
  45. }, {
  46. cipher: PEMCipher3DES,
  47. name: "DES-EDE3-CBC",
  48. cipherFunc: des.NewTripleDESCipher,
  49. keySize: 24,
  50. blockSize: des.BlockSize,
  51. }, {
  52. cipher: PEMCipherAES128,
  53. name: "AES-128-CBC",
  54. cipherFunc: aes.NewCipher,
  55. keySize: 16,
  56. blockSize: aes.BlockSize,
  57. }, {
  58. cipher: PEMCipherAES192,
  59. name: "AES-192-CBC",
  60. cipherFunc: aes.NewCipher,
  61. keySize: 24,
  62. blockSize: aes.BlockSize,
  63. }, {
  64. cipher: PEMCipherAES256,
  65. name: "AES-256-CBC",
  66. cipherFunc: aes.NewCipher,
  67. keySize: 32,
  68. blockSize: aes.BlockSize,
  69. },
  70. }
  71. // deriveKey uses a key derivation function to stretch the password into a key
  72. // with the number of bits our cipher requires. This algorithm was derived from
  73. // the OpenSSL source.
  74. func (c rfc1423Algo) deriveKey(password, salt []byte) []byte {
  75. hash := md5.New()
  76. out := make([]byte, c.keySize)
  77. var digest []byte
  78. for i := 0; i < len(out); i += len(digest) {
  79. hash.Reset()
  80. hash.Write(digest)
  81. hash.Write(password)
  82. hash.Write(salt)
  83. digest = hash.Sum(digest[:0])
  84. copy(out[i:], digest)
  85. }
  86. return out
  87. }
  88. // IsEncryptedPEMBlock returns if the PEM block is password encrypted.
  89. func IsEncryptedPEMBlock(b *pem.Block) bool {
  90. _, ok := b.Headers["DEK-Info"]
  91. return ok
  92. }
  93. // IncorrectPasswordError is returned when an incorrect password is detected.
  94. var IncorrectPasswordError = errors.New("x509: decryption password incorrect")
  95. // DecryptPEMBlock takes a password encrypted PEM block and the password used to
  96. // encrypt it and returns a slice of decrypted DER encoded bytes. It inspects
  97. // the DEK-Info header to determine the algorithm used for decryption. If no
  98. // DEK-Info header is present, an error is returned. If an incorrect password
  99. // is detected an IncorrectPasswordError is returned.
  100. func DecryptPEMBlock(b *pem.Block, password []byte) ([]byte, error) {
  101. dek, ok := b.Headers["DEK-Info"]
  102. if !ok {
  103. return nil, errors.New("x509: no DEK-Info header in block")
  104. }
  105. idx := strings.Index(dek, ",")
  106. if idx == -1 {
  107. return nil, errors.New("x509: malformed DEK-Info header")
  108. }
  109. mode, hexIV := dek[:idx], dek[idx+1:]
  110. ciph := cipherByName(mode)
  111. if ciph == nil {
  112. return nil, errors.New("x509: unknown encryption mode")
  113. }
  114. iv, err := hex.DecodeString(hexIV)
  115. if err != nil {
  116. return nil, err
  117. }
  118. if len(iv) != ciph.blockSize {
  119. return nil, errors.New("x509: incorrect IV size")
  120. }
  121. // Based on the OpenSSL implementation. The salt is the first 8 bytes
  122. // of the initialization vector.
  123. key := ciph.deriveKey(password, iv[:8])
  124. block, err := ciph.cipherFunc(key)
  125. if err != nil {
  126. return nil, err
  127. }
  128. data := make([]byte, len(b.Bytes))
  129. dec := cipher.NewCBCDecrypter(block, iv)
  130. dec.CryptBlocks(data, b.Bytes)
  131. // Blocks are padded using a scheme where the last n bytes of padding are all
  132. // equal to n. It can pad from 1 to blocksize bytes inclusive. See RFC 1423.
  133. // For example:
  134. // [x y z 2 2]
  135. // [x y 7 7 7 7 7 7 7]
  136. // If we detect a bad padding, we assume it is an invalid password.
  137. dlen := len(data)
  138. if dlen == 0 || dlen%ciph.blockSize != 0 {
  139. return nil, errors.New("x509: invalid padding")
  140. }
  141. last := int(data[dlen-1])
  142. if dlen < last {
  143. return nil, IncorrectPasswordError
  144. }
  145. if last == 0 || last > ciph.blockSize {
  146. return nil, IncorrectPasswordError
  147. }
  148. for _, val := range data[dlen-last:] {
  149. if int(val) != last {
  150. return nil, IncorrectPasswordError
  151. }
  152. }
  153. return data[:dlen-last], nil
  154. }
  155. // EncryptPEMBlock returns a PEM block of the specified type holding the
  156. // given DER-encoded data encrypted with the specified algorithm and
  157. // password.
  158. func EncryptPEMBlock(rand io.Reader, blockType string, data, password []byte, alg PEMCipher) (*pem.Block, error) {
  159. ciph := cipherByKey(alg)
  160. if ciph == nil {
  161. return nil, errors.New("x509: unknown encryption mode")
  162. }
  163. iv := make([]byte, ciph.blockSize)
  164. if _, err := io.ReadFull(rand, iv); err != nil {
  165. return nil, errors.New("x509: cannot generate IV: " + err.Error())
  166. }
  167. // The salt is the first 8 bytes of the initialization vector,
  168. // matching the key derivation in DecryptPEMBlock.
  169. key := ciph.deriveKey(password, iv[:8])
  170. block, err := ciph.cipherFunc(key)
  171. if err != nil {
  172. return nil, err
  173. }
  174. enc := cipher.NewCBCEncrypter(block, iv)
  175. pad := ciph.blockSize - len(data)%ciph.blockSize
  176. encrypted := make([]byte, len(data), len(data)+pad)
  177. // We could save this copy by encrypting all the whole blocks in
  178. // the data separately, but it doesn't seem worth the additional
  179. // code.
  180. copy(encrypted, data)
  181. // See RFC 1423, section 1.1
  182. for i := 0; i < pad; i++ {
  183. encrypted = append(encrypted, byte(pad))
  184. }
  185. enc.CryptBlocks(encrypted, encrypted)
  186. return &pem.Block{
  187. Type: blockType,
  188. Headers: map[string]string{
  189. "Proc-Type": "4,ENCRYPTED",
  190. "DEK-Info": ciph.name + "," + hex.EncodeToString(iv),
  191. },
  192. Bytes: encrypted,
  193. }, nil
  194. }
  195. func cipherByName(name string) *rfc1423Algo {
  196. for i := range rfc1423Algos {
  197. alg := &rfc1423Algos[i]
  198. if alg.name == name {
  199. return alg
  200. }
  201. }
  202. return nil
  203. }
  204. func cipherByKey(key PEMCipher) *rfc1423Algo {
  205. for i := range rfc1423Algos {
  206. alg := &rfc1423Algos[i]
  207. if alg.cipher == key {
  208. return alg
  209. }
  210. }
  211. return nil
  212. }