crypter.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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. type Recipient struct {
  92. Algorithm KeyAlgorithm
  93. Key interface{}
  94. KeyID string
  95. }
  96. // NewEncrypter creates an appropriate encrypter based on the key type
  97. func NewEncrypter(enc ContentEncryption, rcpt Recipient, opts *EncrypterOptions) (Encrypter, error) {
  98. encrypter := &genericEncrypter{
  99. contentAlg: enc,
  100. recipients: []recipientKeyInfo{},
  101. cipher: getContentCipher(enc),
  102. }
  103. if opts != nil {
  104. encrypter.compressionAlg = opts.Compression
  105. encrypter.extraHeaders = opts.ExtraHeaders
  106. }
  107. if encrypter.cipher == nil {
  108. return nil, ErrUnsupportedAlgorithm
  109. }
  110. var keyID string
  111. var rawKey interface{}
  112. switch encryptionKey := rcpt.Key.(type) {
  113. case JSONWebKey:
  114. keyID, rawKey = encryptionKey.KeyID, encryptionKey.Key
  115. case *JSONWebKey:
  116. keyID, rawKey = encryptionKey.KeyID, encryptionKey.Key
  117. default:
  118. rawKey = encryptionKey
  119. }
  120. switch rcpt.Algorithm {
  121. case DIRECT:
  122. // Direct encryption mode must be treated differently
  123. if reflect.TypeOf(rawKey) != reflect.TypeOf([]byte{}) {
  124. return nil, ErrUnsupportedKeyType
  125. }
  126. encrypter.keyGenerator = staticKeyGenerator{
  127. key: rawKey.([]byte),
  128. }
  129. recipientInfo, _ := newSymmetricRecipient(rcpt.Algorithm, rawKey.([]byte))
  130. recipientInfo.keyID = keyID
  131. if rcpt.KeyID != "" {
  132. recipientInfo.keyID = rcpt.KeyID
  133. }
  134. encrypter.recipients = []recipientKeyInfo{recipientInfo}
  135. return encrypter, nil
  136. case ECDH_ES:
  137. // ECDH-ES (w/o key wrapping) is similar to DIRECT mode
  138. typeOf := reflect.TypeOf(rawKey)
  139. if typeOf != reflect.TypeOf(&ecdsa.PublicKey{}) {
  140. return nil, ErrUnsupportedKeyType
  141. }
  142. encrypter.keyGenerator = ecKeyGenerator{
  143. size: encrypter.cipher.keySize(),
  144. algID: string(enc),
  145. publicKey: rawKey.(*ecdsa.PublicKey),
  146. }
  147. recipientInfo, _ := newECDHRecipient(rcpt.Algorithm, rawKey.(*ecdsa.PublicKey))
  148. recipientInfo.keyID = keyID
  149. if rcpt.KeyID != "" {
  150. recipientInfo.keyID = rcpt.KeyID
  151. }
  152. encrypter.recipients = []recipientKeyInfo{recipientInfo}
  153. return encrypter, nil
  154. default:
  155. // Can just add a standard recipient
  156. encrypter.keyGenerator = randomKeyGenerator{
  157. size: encrypter.cipher.keySize(),
  158. }
  159. err := encrypter.addRecipient(rcpt)
  160. return encrypter, err
  161. }
  162. }
  163. // NewMultiEncrypter creates a multi-encrypter based on the given parameters
  164. func NewMultiEncrypter(enc ContentEncryption, rcpts []Recipient, opts *EncrypterOptions) (Encrypter, error) {
  165. cipher := getContentCipher(enc)
  166. if cipher == nil {
  167. return nil, ErrUnsupportedAlgorithm
  168. }
  169. if rcpts == nil || len(rcpts) == 0 {
  170. return nil, fmt.Errorf("square/go-jose: recipients is nil or empty")
  171. }
  172. encrypter := &genericEncrypter{
  173. contentAlg: enc,
  174. recipients: []recipientKeyInfo{},
  175. cipher: cipher,
  176. keyGenerator: randomKeyGenerator{
  177. size: cipher.keySize(),
  178. },
  179. }
  180. if opts != nil {
  181. encrypter.compressionAlg = opts.Compression
  182. }
  183. for _, recipient := range rcpts {
  184. err := encrypter.addRecipient(recipient)
  185. if err != nil {
  186. return nil, err
  187. }
  188. }
  189. return encrypter, nil
  190. }
  191. func (ctx *genericEncrypter) addRecipient(recipient Recipient) (err error) {
  192. var recipientInfo recipientKeyInfo
  193. switch recipient.Algorithm {
  194. case DIRECT, ECDH_ES:
  195. return fmt.Errorf("square/go-jose: key algorithm '%s' not supported in multi-recipient mode", recipient.Algorithm)
  196. }
  197. recipientInfo, err = makeJWERecipient(recipient.Algorithm, recipient.Key)
  198. if recipient.KeyID != "" {
  199. recipientInfo.keyID = recipient.KeyID
  200. }
  201. if err == nil {
  202. ctx.recipients = append(ctx.recipients, recipientInfo)
  203. }
  204. return err
  205. }
  206. func makeJWERecipient(alg KeyAlgorithm, encryptionKey interface{}) (recipientKeyInfo, error) {
  207. switch encryptionKey := encryptionKey.(type) {
  208. case *rsa.PublicKey:
  209. return newRSARecipient(alg, encryptionKey)
  210. case *ecdsa.PublicKey:
  211. return newECDHRecipient(alg, encryptionKey)
  212. case []byte:
  213. return newSymmetricRecipient(alg, encryptionKey)
  214. case *JSONWebKey:
  215. recipient, err := makeJWERecipient(alg, encryptionKey.Key)
  216. recipient.keyID = encryptionKey.KeyID
  217. return recipient, err
  218. default:
  219. return recipientKeyInfo{}, ErrUnsupportedKeyType
  220. }
  221. }
  222. // newDecrypter creates an appropriate decrypter based on the key type
  223. func newDecrypter(decryptionKey interface{}) (keyDecrypter, error) {
  224. switch decryptionKey := decryptionKey.(type) {
  225. case *rsa.PrivateKey:
  226. return &rsaDecrypterSigner{
  227. privateKey: decryptionKey,
  228. }, nil
  229. case *ecdsa.PrivateKey:
  230. return &ecDecrypterSigner{
  231. privateKey: decryptionKey,
  232. }, nil
  233. case []byte:
  234. return &symmetricKeyCipher{
  235. key: decryptionKey,
  236. }, nil
  237. case JSONWebKey:
  238. return newDecrypter(decryptionKey.Key)
  239. case *JSONWebKey:
  240. return newDecrypter(decryptionKey.Key)
  241. default:
  242. return nil, ErrUnsupportedKeyType
  243. }
  244. }
  245. // Implementation of encrypt method producing a JWE object.
  246. func (ctx *genericEncrypter) Encrypt(plaintext []byte) (*JSONWebEncryption, error) {
  247. return ctx.EncryptWithAuthData(plaintext, nil)
  248. }
  249. // Implementation of encrypt method producing a JWE object.
  250. func (ctx *genericEncrypter) EncryptWithAuthData(plaintext, aad []byte) (*JSONWebEncryption, error) {
  251. obj := &JSONWebEncryption{}
  252. obj.aad = aad
  253. obj.protected = &rawHeader{}
  254. err := obj.protected.set(headerEncryption, ctx.contentAlg)
  255. if err != nil {
  256. return nil, err
  257. }
  258. obj.recipients = make([]recipientInfo, len(ctx.recipients))
  259. if len(ctx.recipients) == 0 {
  260. return nil, fmt.Errorf("square/go-jose: no recipients to encrypt to")
  261. }
  262. cek, headers, err := ctx.keyGenerator.genKey()
  263. if err != nil {
  264. return nil, err
  265. }
  266. obj.protected.merge(&headers)
  267. for i, info := range ctx.recipients {
  268. recipient, err := info.keyEncrypter.encryptKey(cek, info.keyAlg)
  269. if err != nil {
  270. return nil, err
  271. }
  272. err = recipient.header.set(headerAlgorithm, info.keyAlg)
  273. if err != nil {
  274. return nil, err
  275. }
  276. if info.keyID != "" {
  277. err = recipient.header.set(headerKeyID, info.keyID)
  278. if err != nil {
  279. return nil, err
  280. }
  281. }
  282. obj.recipients[i] = recipient
  283. }
  284. if len(ctx.recipients) == 1 {
  285. // Move per-recipient headers into main protected header if there's
  286. // only a single recipient.
  287. obj.protected.merge(obj.recipients[0].header)
  288. obj.recipients[0].header = nil
  289. }
  290. if ctx.compressionAlg != NONE {
  291. plaintext, err = compress(ctx.compressionAlg, plaintext)
  292. if err != nil {
  293. return nil, err
  294. }
  295. err = obj.protected.set(headerCompression, ctx.compressionAlg)
  296. if err != nil {
  297. return nil, err
  298. }
  299. }
  300. for k, v := range ctx.extraHeaders {
  301. b, err := json.Marshal(v)
  302. if err != nil {
  303. return nil, err
  304. }
  305. (*obj.protected)[k] = makeRawMessage(b)
  306. }
  307. authData := obj.computeAuthData()
  308. parts, err := ctx.cipher.encrypt(cek, authData, plaintext)
  309. if err != nil {
  310. return nil, err
  311. }
  312. obj.iv = parts.iv
  313. obj.ciphertext = parts.ciphertext
  314. obj.tag = parts.tag
  315. return obj, nil
  316. }
  317. func (ctx *genericEncrypter) Options() EncrypterOptions {
  318. return EncrypterOptions{
  319. Compression: ctx.compressionAlg,
  320. ExtraHeaders: ctx.extraHeaders,
  321. }
  322. }
  323. // Decrypt and validate the object and return the plaintext. Note that this
  324. // function does not support multi-recipient, if you desire multi-recipient
  325. // decryption use DecryptMulti instead.
  326. func (obj JSONWebEncryption) Decrypt(decryptionKey interface{}) ([]byte, error) {
  327. headers := obj.mergedHeaders(nil)
  328. if len(obj.recipients) > 1 {
  329. return nil, errors.New("square/go-jose: too many recipients in payload; expecting only one")
  330. }
  331. critical, err := headers.getCritical()
  332. if err != nil {
  333. return nil, fmt.Errorf("square/go-jose: invalid crit header")
  334. }
  335. if len(critical) > 0 {
  336. return nil, fmt.Errorf("square/go-jose: unsupported crit header")
  337. }
  338. decrypter, err := newDecrypter(decryptionKey)
  339. if err != nil {
  340. return nil, err
  341. }
  342. cipher := getContentCipher(headers.getEncryption())
  343. if cipher == nil {
  344. return nil, fmt.Errorf("square/go-jose: unsupported enc value '%s'", string(headers.getEncryption()))
  345. }
  346. generator := randomKeyGenerator{
  347. size: cipher.keySize(),
  348. }
  349. parts := &aeadParts{
  350. iv: obj.iv,
  351. ciphertext: obj.ciphertext,
  352. tag: obj.tag,
  353. }
  354. authData := obj.computeAuthData()
  355. var plaintext []byte
  356. recipient := obj.recipients[0]
  357. recipientHeaders := obj.mergedHeaders(&recipient)
  358. cek, err := decrypter.decryptKey(recipientHeaders, &recipient, generator)
  359. if err == nil {
  360. // Found a valid CEK -- let's try to decrypt.
  361. plaintext, err = cipher.decrypt(cek, authData, parts)
  362. }
  363. if plaintext == nil {
  364. return nil, ErrCryptoFailure
  365. }
  366. // The "zip" header parameter may only be present in the protected header.
  367. if comp := obj.protected.getCompression(); comp != "" {
  368. plaintext, err = decompress(comp, plaintext)
  369. }
  370. return plaintext, err
  371. }
  372. // DecryptMulti decrypts and validates the object and returns the plaintexts,
  373. // with support for multiple recipients. It returns the index of the recipient
  374. // for which the decryption was successful, the merged headers for that recipient,
  375. // and the plaintext.
  376. func (obj JSONWebEncryption) DecryptMulti(decryptionKey interface{}) (int, Header, []byte, error) {
  377. globalHeaders := obj.mergedHeaders(nil)
  378. critical, err := globalHeaders.getCritical()
  379. if err != nil {
  380. return -1, Header{}, nil, fmt.Errorf("square/go-jose: invalid crit header")
  381. }
  382. if len(critical) > 0 {
  383. return -1, Header{}, nil, fmt.Errorf("square/go-jose: unsupported crit header")
  384. }
  385. decrypter, err := newDecrypter(decryptionKey)
  386. if err != nil {
  387. return -1, Header{}, nil, err
  388. }
  389. encryption := globalHeaders.getEncryption()
  390. cipher := getContentCipher(encryption)
  391. if cipher == nil {
  392. return -1, Header{}, nil, fmt.Errorf("square/go-jose: unsupported enc value '%s'", string(encryption))
  393. }
  394. generator := randomKeyGenerator{
  395. size: cipher.keySize(),
  396. }
  397. parts := &aeadParts{
  398. iv: obj.iv,
  399. ciphertext: obj.ciphertext,
  400. tag: obj.tag,
  401. }
  402. authData := obj.computeAuthData()
  403. index := -1
  404. var plaintext []byte
  405. var headers rawHeader
  406. for i, recipient := range obj.recipients {
  407. recipientHeaders := obj.mergedHeaders(&recipient)
  408. cek, err := decrypter.decryptKey(recipientHeaders, &recipient, generator)
  409. if err == nil {
  410. // Found a valid CEK -- let's try to decrypt.
  411. plaintext, err = cipher.decrypt(cek, authData, parts)
  412. if err == nil {
  413. index = i
  414. headers = recipientHeaders
  415. break
  416. }
  417. }
  418. }
  419. if plaintext == nil || err != nil {
  420. return -1, Header{}, nil, ErrCryptoFailure
  421. }
  422. // The "zip" header parameter may only be present in the protected header.
  423. if comp := obj.protected.getCompression(); comp != "" {
  424. plaintext, err = decompress(comp, plaintext)
  425. }
  426. sanitized, err := headers.sanitized()
  427. if err != nil {
  428. return -1, Header{}, nil, fmt.Errorf("square/go-jose: failed to sanitize header: %v", err)
  429. }
  430. return index, sanitized, plaintext, err
  431. }