pem_decrypt.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. Because of deficiencies
  100. // in the encrypted-PEM format, it's not always possible to detect an incorrect
  101. // password. In these cases no error will be returned but the decrypted DER
  102. // bytes will be random noise.
  103. func DecryptPEMBlock(b *pem.Block, password []byte) ([]byte, error) {
  104. dek, ok := b.Headers["DEK-Info"]
  105. if !ok {
  106. return nil, errors.New("x509: no DEK-Info header in block")
  107. }
  108. idx := strings.Index(dek, ",")
  109. if idx == -1 {
  110. return nil, errors.New("x509: malformed DEK-Info header")
  111. }
  112. mode, hexIV := dek[:idx], dek[idx+1:]
  113. ciph := cipherByName(mode)
  114. if ciph == nil {
  115. return nil, errors.New("x509: unknown encryption mode")
  116. }
  117. iv, err := hex.DecodeString(hexIV)
  118. if err != nil {
  119. return nil, err
  120. }
  121. if len(iv) != ciph.blockSize {
  122. return nil, errors.New("x509: incorrect IV size")
  123. }
  124. // Based on the OpenSSL implementation. The salt is the first 8 bytes
  125. // of the initialization vector.
  126. key := ciph.deriveKey(password, iv[:8])
  127. block, err := ciph.cipherFunc(key)
  128. if err != nil {
  129. return nil, err
  130. }
  131. if len(b.Bytes)%block.BlockSize() != 0 {
  132. return nil, errors.New("x509: encrypted PEM data is not a multiple of the block size")
  133. }
  134. data := make([]byte, len(b.Bytes))
  135. dec := cipher.NewCBCDecrypter(block, iv)
  136. dec.CryptBlocks(data, b.Bytes)
  137. // Blocks are padded using a scheme where the last n bytes of padding are all
  138. // equal to n. It can pad from 1 to blocksize bytes inclusive. See RFC 1423.
  139. // For example:
  140. // [x y z 2 2]
  141. // [x y 7 7 7 7 7 7 7]
  142. // If we detect a bad padding, we assume it is an invalid password.
  143. dlen := len(data)
  144. if dlen == 0 || dlen%ciph.blockSize != 0 {
  145. return nil, errors.New("x509: invalid padding")
  146. }
  147. last := int(data[dlen-1])
  148. if dlen < last {
  149. return nil, IncorrectPasswordError
  150. }
  151. if last == 0 || last > ciph.blockSize {
  152. return nil, IncorrectPasswordError
  153. }
  154. for _, val := range data[dlen-last:] {
  155. if int(val) != last {
  156. return nil, IncorrectPasswordError
  157. }
  158. }
  159. return data[:dlen-last], nil
  160. }
  161. // EncryptPEMBlock returns a PEM block of the specified type holding the
  162. // given DER-encoded data encrypted with the specified algorithm and
  163. // password.
  164. func EncryptPEMBlock(rand io.Reader, blockType string, data, password []byte, alg PEMCipher) (*pem.Block, error) {
  165. ciph := cipherByKey(alg)
  166. if ciph == nil {
  167. return nil, errors.New("x509: unknown encryption mode")
  168. }
  169. iv := make([]byte, ciph.blockSize)
  170. if _, err := io.ReadFull(rand, iv); err != nil {
  171. return nil, errors.New("x509: cannot generate IV: " + err.Error())
  172. }
  173. // The salt is the first 8 bytes of the initialization vector,
  174. // matching the key derivation in DecryptPEMBlock.
  175. key := ciph.deriveKey(password, iv[:8])
  176. block, err := ciph.cipherFunc(key)
  177. if err != nil {
  178. return nil, err
  179. }
  180. enc := cipher.NewCBCEncrypter(block, iv)
  181. pad := ciph.blockSize - len(data)%ciph.blockSize
  182. encrypted := make([]byte, len(data), len(data)+pad)
  183. // We could save this copy by encrypting all the whole blocks in
  184. // the data separately, but it doesn't seem worth the additional
  185. // code.
  186. copy(encrypted, data)
  187. // See RFC 1423, section 1.1
  188. for i := 0; i < pad; i++ {
  189. encrypted = append(encrypted, byte(pad))
  190. }
  191. enc.CryptBlocks(encrypted, encrypted)
  192. return &pem.Block{
  193. Type: blockType,
  194. Headers: map[string]string{
  195. "Proc-Type": "4,ENCRYPTED",
  196. "DEK-Info": ciph.name + "," + hex.EncodeToString(iv),
  197. },
  198. Bytes: encrypted,
  199. }, nil
  200. }
  201. func cipherByName(name string) *rfc1423Algo {
  202. for i := range rfc1423Algos {
  203. alg := &rfc1423Algos[i]
  204. if alg.name == name {
  205. return alg
  206. }
  207. }
  208. return nil
  209. }
  210. func cipherByKey(key PEMCipher) *rfc1423Algo {
  211. for i := range rfc1423Algos {
  212. alg := &rfc1423Algos[i]
  213. if alg.cipher == key {
  214. return alg
  215. }
  216. }
  217. return nil
  218. }