crypter.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. /*-
  2. * Copyright 2014 Square Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package jose
  17. import (
  18. "crypto/ecdsa"
  19. "crypto/rsa"
  20. "errors"
  21. "fmt"
  22. "reflect"
  23. "gopkg.in/square/go-jose.v2/json"
  24. )
  25. // Encrypter represents an encrypter which produces an encrypted JWE object.
  26. type Encrypter interface {
  27. Encrypt(plaintext []byte) (*JSONWebEncryption, error)
  28. EncryptWithAuthData(plaintext []byte, aad []byte) (*JSONWebEncryption, error)
  29. Options() EncrypterOptions
  30. }
  31. // A generic content cipher
  32. type contentCipher interface {
  33. keySize() int
  34. encrypt(cek []byte, aad, plaintext []byte) (*aeadParts, error)
  35. decrypt(cek []byte, aad []byte, parts *aeadParts) ([]byte, error)
  36. }
  37. // A key generator (for generating/getting a CEK)
  38. type keyGenerator interface {
  39. keySize() int
  40. genKey() ([]byte, rawHeader, error)
  41. }
  42. // A generic key encrypter
  43. type keyEncrypter interface {
  44. encryptKey(cek []byte, alg KeyAlgorithm) (recipientInfo, error) // Encrypt a key
  45. }
  46. // A generic key decrypter
  47. type keyDecrypter interface {
  48. decryptKey(headers rawHeader, recipient *recipientInfo, generator keyGenerator) ([]byte, error) // Decrypt a key
  49. }
  50. // A generic encrypter based on the given key encrypter and content cipher.
  51. type genericEncrypter struct {
  52. contentAlg ContentEncryption
  53. compressionAlg CompressionAlgorithm
  54. cipher contentCipher
  55. recipients []recipientKeyInfo
  56. keyGenerator keyGenerator
  57. extraHeaders map[HeaderKey]interface{}
  58. }
  59. type recipientKeyInfo struct {
  60. keyID string
  61. keyAlg KeyAlgorithm
  62. keyEncrypter keyEncrypter
  63. }
  64. // EncrypterOptions represents options that can be set on new encrypters.
  65. type EncrypterOptions struct {
  66. Compression CompressionAlgorithm
  67. // Optional map of additional keys to be inserted into the protected header
  68. // of a JWS object. Some specifications which make use of JWS like to insert
  69. // additional values here. All values must be JSON-serializable.
  70. ExtraHeaders map[HeaderKey]interface{}
  71. }
  72. // WithHeader adds an arbitrary value to the ExtraHeaders map, initializing it
  73. // if necessary. It returns itself and so can be used in a fluent style.
  74. func (eo *EncrypterOptions) WithHeader(k HeaderKey, v interface{}) *EncrypterOptions {
  75. if eo.ExtraHeaders == nil {
  76. eo.ExtraHeaders = map[HeaderKey]interface{}{}
  77. }
  78. eo.ExtraHeaders[k] = v
  79. return eo
  80. }
  81. // WithContentType adds a content type ("cty") header and returns the updated
  82. // EncrypterOptions.
  83. func (eo *EncrypterOptions) WithContentType(contentType ContentType) *EncrypterOptions {
  84. return eo.WithHeader(HeaderContentType, contentType)
  85. }
  86. // WithType adds a type ("typ") header and returns the updated EncrypterOptions.
  87. func (eo *EncrypterOptions) WithType(typ ContentType) *EncrypterOptions {
  88. return eo.WithHeader(HeaderType, typ)
  89. }
  90. // Recipient represents an algorithm/key to encrypt messages to.
  91. //
  92. // PBES2Count and PBES2Salt correspond with the "p2c" and "p2s" headers used
  93. // on the password-based encryption algorithms PBES2-HS256+A128KW,
  94. // PBES2-HS384+A192KW, and PBES2-HS512+A256KW. If they are not provided a safe
  95. // default of 100000 will be used for the count and a 128-bit random salt will
  96. // be generated.
  97. type Recipient struct {
  98. Algorithm KeyAlgorithm
  99. Key interface{}
  100. KeyID string
  101. PBES2Count int
  102. PBES2Salt []byte
  103. }
  104. // NewEncrypter creates an appropriate encrypter based on the key type
  105. func NewEncrypter(enc ContentEncryption, rcpt Recipient, opts *EncrypterOptions) (Encrypter, error) {
  106. encrypter := &genericEncrypter{
  107. contentAlg: enc,
  108. recipients: []recipientKeyInfo{},
  109. cipher: getContentCipher(enc),
  110. }
  111. if opts != nil {
  112. encrypter.compressionAlg = opts.Compression
  113. encrypter.extraHeaders = opts.ExtraHeaders
  114. }
  115. if encrypter.cipher == nil {
  116. return nil, ErrUnsupportedAlgorithm
  117. }
  118. var keyID string
  119. var rawKey interface{}
  120. switch encryptionKey := rcpt.Key.(type) {
  121. case JSONWebKey:
  122. keyID, rawKey = encryptionKey.KeyID, encryptionKey.Key
  123. case *JSONWebKey:
  124. keyID, rawKey = encryptionKey.KeyID, encryptionKey.Key
  125. case OpaqueKeyEncrypter:
  126. keyID, rawKey = encryptionKey.KeyID(), encryptionKey
  127. default:
  128. rawKey = encryptionKey
  129. }
  130. switch rcpt.Algorithm {
  131. case DIRECT:
  132. // Direct encryption mode must be treated differently
  133. if reflect.TypeOf(rawKey) != reflect.TypeOf([]byte{}) {
  134. return nil, ErrUnsupportedKeyType
  135. }
  136. if encrypter.cipher.keySize() != len(rawKey.([]byte)) {
  137. return nil, ErrInvalidKeySize
  138. }
  139. encrypter.keyGenerator = staticKeyGenerator{
  140. key: rawKey.([]byte),
  141. }
  142. recipientInfo, _ := newSymmetricRecipient(rcpt.Algorithm, rawKey.([]byte))
  143. recipientInfo.keyID = keyID
  144. if rcpt.KeyID != "" {
  145. recipientInfo.keyID = rcpt.KeyID
  146. }
  147. encrypter.recipients = []recipientKeyInfo{recipientInfo}
  148. return encrypter, nil
  149. case ECDH_ES:
  150. // ECDH-ES (w/o key wrapping) is similar to DIRECT mode
  151. typeOf := reflect.TypeOf(rawKey)
  152. if typeOf != reflect.TypeOf(&ecdsa.PublicKey{}) {
  153. return nil, ErrUnsupportedKeyType
  154. }
  155. encrypter.keyGenerator = ecKeyGenerator{
  156. size: encrypter.cipher.keySize(),
  157. algID: string(enc),
  158. publicKey: rawKey.(*ecdsa.PublicKey),
  159. }
  160. recipientInfo, _ := newECDHRecipient(rcpt.Algorithm, rawKey.(*ecdsa.PublicKey))
  161. recipientInfo.keyID = keyID
  162. if rcpt.KeyID != "" {
  163. recipientInfo.keyID = rcpt.KeyID
  164. }
  165. encrypter.recipients = []recipientKeyInfo{recipientInfo}
  166. return encrypter, nil
  167. default:
  168. // Can just add a standard recipient
  169. encrypter.keyGenerator = randomKeyGenerator{
  170. size: encrypter.cipher.keySize(),
  171. }
  172. err := encrypter.addRecipient(rcpt)
  173. return encrypter, err
  174. }
  175. }
  176. // NewMultiEncrypter creates a multi-encrypter based on the given parameters
  177. func NewMultiEncrypter(enc ContentEncryption, rcpts []Recipient, opts *EncrypterOptions) (Encrypter, error) {
  178. cipher := getContentCipher(enc)
  179. if cipher == nil {
  180. return nil, ErrUnsupportedAlgorithm
  181. }
  182. if rcpts == nil || len(rcpts) == 0 {
  183. return nil, fmt.Errorf("square/go-jose: recipients is nil or empty")
  184. }
  185. encrypter := &genericEncrypter{
  186. contentAlg: enc,
  187. recipients: []recipientKeyInfo{},
  188. cipher: cipher,
  189. keyGenerator: randomKeyGenerator{
  190. size: cipher.keySize(),
  191. },
  192. }
  193. if opts != nil {
  194. encrypter.compressionAlg = opts.Compression
  195. }
  196. for _, recipient := range rcpts {
  197. err := encrypter.addRecipient(recipient)
  198. if err != nil {
  199. return nil, err
  200. }
  201. }
  202. return encrypter, nil
  203. }
  204. func (ctx *genericEncrypter) addRecipient(recipient Recipient) (err error) {
  205. var recipientInfo recipientKeyInfo
  206. switch recipient.Algorithm {
  207. case DIRECT, ECDH_ES:
  208. return fmt.Errorf("square/go-jose: key algorithm '%s' not supported in multi-recipient mode", recipient.Algorithm)
  209. }
  210. recipientInfo, err = makeJWERecipient(recipient.Algorithm, recipient.Key)
  211. if recipient.KeyID != "" {
  212. recipientInfo.keyID = recipient.KeyID
  213. }
  214. switch recipient.Algorithm {
  215. case PBES2_HS256_A128KW, PBES2_HS384_A192KW, PBES2_HS512_A256KW:
  216. if sr, ok := recipientInfo.keyEncrypter.(*symmetricKeyCipher); ok {
  217. sr.p2c = recipient.PBES2Count
  218. sr.p2s = recipient.PBES2Salt
  219. }
  220. }
  221. if err == nil {
  222. ctx.recipients = append(ctx.recipients, recipientInfo)
  223. }
  224. return err
  225. }
  226. func makeJWERecipient(alg KeyAlgorithm, encryptionKey interface{}) (recipientKeyInfo, error) {
  227. switch encryptionKey := encryptionKey.(type) {
  228. case *rsa.PublicKey:
  229. return newRSARecipient(alg, encryptionKey)
  230. case *ecdsa.PublicKey:
  231. return newECDHRecipient(alg, encryptionKey)
  232. case []byte:
  233. return newSymmetricRecipient(alg, encryptionKey)
  234. case string:
  235. return newSymmetricRecipient(alg, []byte(encryptionKey))
  236. case *JSONWebKey:
  237. recipient, err := makeJWERecipient(alg, encryptionKey.Key)
  238. recipient.keyID = encryptionKey.KeyID
  239. return recipient, err
  240. }
  241. if encrypter, ok := encryptionKey.(OpaqueKeyEncrypter); ok {
  242. return newOpaqueKeyEncrypter(alg, encrypter)
  243. }
  244. return recipientKeyInfo{}, ErrUnsupportedKeyType
  245. }
  246. // newDecrypter creates an appropriate decrypter based on the key type
  247. func newDecrypter(decryptionKey interface{}) (keyDecrypter, error) {
  248. switch decryptionKey := decryptionKey.(type) {
  249. case *rsa.PrivateKey:
  250. return &rsaDecrypterSigner{
  251. privateKey: decryptionKey,
  252. }, nil
  253. case *ecdsa.PrivateKey:
  254. return &ecDecrypterSigner{
  255. privateKey: decryptionKey,
  256. }, nil
  257. case []byte:
  258. return &symmetricKeyCipher{
  259. key: decryptionKey,
  260. }, nil
  261. case string:
  262. return &symmetricKeyCipher{
  263. key: []byte(decryptionKey),
  264. }, nil
  265. case JSONWebKey:
  266. return newDecrypter(decryptionKey.Key)
  267. case *JSONWebKey:
  268. return newDecrypter(decryptionKey.Key)
  269. }
  270. if okd, ok := decryptionKey.(OpaqueKeyDecrypter); ok {
  271. return &opaqueKeyDecrypter{decrypter: okd}, nil
  272. }
  273. return nil, ErrUnsupportedKeyType
  274. }
  275. // Implementation of encrypt method producing a JWE object.
  276. func (ctx *genericEncrypter) Encrypt(plaintext []byte) (*JSONWebEncryption, error) {
  277. return ctx.EncryptWithAuthData(plaintext, nil)
  278. }
  279. // Implementation of encrypt method producing a JWE object.
  280. func (ctx *genericEncrypter) EncryptWithAuthData(plaintext, aad []byte) (*JSONWebEncryption, error) {
  281. obj := &JSONWebEncryption{}
  282. obj.aad = aad
  283. obj.protected = &rawHeader{}
  284. err := obj.protected.set(headerEncryption, ctx.contentAlg)
  285. if err != nil {
  286. return nil, err
  287. }
  288. obj.recipients = make([]recipientInfo, len(ctx.recipients))
  289. if len(ctx.recipients) == 0 {
  290. return nil, fmt.Errorf("square/go-jose: no recipients to encrypt to")
  291. }
  292. cek, headers, err := ctx.keyGenerator.genKey()
  293. if err != nil {
  294. return nil, err
  295. }
  296. obj.protected.merge(&headers)
  297. for i, info := range ctx.recipients {
  298. recipient, err := info.keyEncrypter.encryptKey(cek, info.keyAlg)
  299. if err != nil {
  300. return nil, err
  301. }
  302. err = recipient.header.set(headerAlgorithm, info.keyAlg)
  303. if err != nil {
  304. return nil, err
  305. }
  306. if info.keyID != "" {
  307. err = recipient.header.set(headerKeyID, info.keyID)
  308. if err != nil {
  309. return nil, err
  310. }
  311. }
  312. obj.recipients[i] = recipient
  313. }
  314. if len(ctx.recipients) == 1 {
  315. // Move per-recipient headers into main protected header if there's
  316. // only a single recipient.
  317. obj.protected.merge(obj.recipients[0].header)
  318. obj.recipients[0].header = nil
  319. }
  320. if ctx.compressionAlg != NONE {
  321. plaintext, err = compress(ctx.compressionAlg, plaintext)
  322. if err != nil {
  323. return nil, err
  324. }
  325. err = obj.protected.set(headerCompression, ctx.compressionAlg)
  326. if err != nil {
  327. return nil, err
  328. }
  329. }
  330. for k, v := range ctx.extraHeaders {
  331. b, err := json.Marshal(v)
  332. if err != nil {
  333. return nil, err
  334. }
  335. (*obj.protected)[k] = makeRawMessage(b)
  336. }
  337. authData := obj.computeAuthData()
  338. parts, err := ctx.cipher.encrypt(cek, authData, plaintext)
  339. if err != nil {
  340. return nil, err
  341. }
  342. obj.iv = parts.iv
  343. obj.ciphertext = parts.ciphertext
  344. obj.tag = parts.tag
  345. return obj, nil
  346. }
  347. func (ctx *genericEncrypter) Options() EncrypterOptions {
  348. return EncrypterOptions{
  349. Compression: ctx.compressionAlg,
  350. ExtraHeaders: ctx.extraHeaders,
  351. }
  352. }
  353. // Decrypt and validate the object and return the plaintext. Note that this
  354. // function does not support multi-recipient, if you desire multi-recipient
  355. // decryption use DecryptMulti instead.
  356. func (obj JSONWebEncryption) Decrypt(decryptionKey interface{}) ([]byte, error) {
  357. headers := obj.mergedHeaders(nil)
  358. if len(obj.recipients) > 1 {
  359. return nil, errors.New("square/go-jose: too many recipients in payload; expecting only one")
  360. }
  361. critical, err := headers.getCritical()
  362. if err != nil {
  363. return nil, fmt.Errorf("square/go-jose: invalid crit header")
  364. }
  365. if len(critical) > 0 {
  366. return nil, fmt.Errorf("square/go-jose: unsupported crit header")
  367. }
  368. decrypter, err := newDecrypter(decryptionKey)
  369. if err != nil {
  370. return nil, err
  371. }
  372. cipher := getContentCipher(headers.getEncryption())
  373. if cipher == nil {
  374. return nil, fmt.Errorf("square/go-jose: unsupported enc value '%s'", string(headers.getEncryption()))
  375. }
  376. generator := randomKeyGenerator{
  377. size: cipher.keySize(),
  378. }
  379. parts := &aeadParts{
  380. iv: obj.iv,
  381. ciphertext: obj.ciphertext,
  382. tag: obj.tag,
  383. }
  384. authData := obj.computeAuthData()
  385. var plaintext []byte
  386. recipient := obj.recipients[0]
  387. recipientHeaders := obj.mergedHeaders(&recipient)
  388. cek, err := decrypter.decryptKey(recipientHeaders, &recipient, generator)
  389. if err == nil {
  390. // Found a valid CEK -- let's try to decrypt.
  391. plaintext, err = cipher.decrypt(cek, authData, parts)
  392. }
  393. if plaintext == nil {
  394. return nil, ErrCryptoFailure
  395. }
  396. // The "zip" header parameter may only be present in the protected header.
  397. if comp := obj.protected.getCompression(); comp != "" {
  398. plaintext, err = decompress(comp, plaintext)
  399. }
  400. return plaintext, err
  401. }
  402. // DecryptMulti decrypts and validates the object and returns the plaintexts,
  403. // with support for multiple recipients. It returns the index of the recipient
  404. // for which the decryption was successful, the merged headers for that recipient,
  405. // and the plaintext.
  406. func (obj JSONWebEncryption) DecryptMulti(decryptionKey interface{}) (int, Header, []byte, error) {
  407. globalHeaders := obj.mergedHeaders(nil)
  408. critical, err := globalHeaders.getCritical()
  409. if err != nil {
  410. return -1, Header{}, nil, fmt.Errorf("square/go-jose: invalid crit header")
  411. }
  412. if len(critical) > 0 {
  413. return -1, Header{}, nil, fmt.Errorf("square/go-jose: unsupported crit header")
  414. }
  415. decrypter, err := newDecrypter(decryptionKey)
  416. if err != nil {
  417. return -1, Header{}, nil, err
  418. }
  419. encryption := globalHeaders.getEncryption()
  420. cipher := getContentCipher(encryption)
  421. if cipher == nil {
  422. return -1, Header{}, nil, fmt.Errorf("square/go-jose: unsupported enc value '%s'", string(encryption))
  423. }
  424. generator := randomKeyGenerator{
  425. size: cipher.keySize(),
  426. }
  427. parts := &aeadParts{
  428. iv: obj.iv,
  429. ciphertext: obj.ciphertext,
  430. tag: obj.tag,
  431. }
  432. authData := obj.computeAuthData()
  433. index := -1
  434. var plaintext []byte
  435. var headers rawHeader
  436. for i, recipient := range obj.recipients {
  437. recipientHeaders := obj.mergedHeaders(&recipient)
  438. cek, err := decrypter.decryptKey(recipientHeaders, &recipient, generator)
  439. if err == nil {
  440. // Found a valid CEK -- let's try to decrypt.
  441. plaintext, err = cipher.decrypt(cek, authData, parts)
  442. if err == nil {
  443. index = i
  444. headers = recipientHeaders
  445. break
  446. }
  447. }
  448. }
  449. if plaintext == nil || err != nil {
  450. return -1, Header{}, nil, ErrCryptoFailure
  451. }
  452. // The "zip" header parameter may only be present in the protected header.
  453. if comp := obj.protected.getCompression(); comp != "" {
  454. plaintext, err = decompress(comp, plaintext)
  455. }
  456. sanitized, err := headers.sanitized()
  457. if err != nil {
  458. return -1, Header{}, nil, fmt.Errorf("square/go-jose: failed to sanitize header: %v", err)
  459. }
  460. return index, sanitized, plaintext, err
  461. }