jwk.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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"
  19. "crypto/ecdsa"
  20. "crypto/elliptic"
  21. "crypto/rsa"
  22. "crypto/x509"
  23. "encoding/base64"
  24. "errors"
  25. "fmt"
  26. "math/big"
  27. "reflect"
  28. "strings"
  29. "golang.org/x/crypto/ed25519"
  30. "gopkg.in/square/go-jose.v2/json"
  31. )
  32. // rawJSONWebKey represents a public or private key in JWK format, used for parsing/serializing.
  33. type rawJSONWebKey struct {
  34. Use string `json:"use,omitempty"`
  35. Kty string `json:"kty,omitempty"`
  36. Kid string `json:"kid,omitempty"`
  37. Crv string `json:"crv,omitempty"`
  38. Alg string `json:"alg,omitempty"`
  39. K *byteBuffer `json:"k,omitempty"`
  40. X *byteBuffer `json:"x,omitempty"`
  41. Y *byteBuffer `json:"y,omitempty"`
  42. N *byteBuffer `json:"n,omitempty"`
  43. E *byteBuffer `json:"e,omitempty"`
  44. // -- Following fields are only used for private keys --
  45. // RSA uses D, P and Q, while ECDSA uses only D. Fields Dp, Dq, and Qi are
  46. // completely optional. Therefore for RSA/ECDSA, D != nil is a contract that
  47. // we have a private key whereas D == nil means we have only a public key.
  48. D *byteBuffer `json:"d,omitempty"`
  49. P *byteBuffer `json:"p,omitempty"`
  50. Q *byteBuffer `json:"q,omitempty"`
  51. Dp *byteBuffer `json:"dp,omitempty"`
  52. Dq *byteBuffer `json:"dq,omitempty"`
  53. Qi *byteBuffer `json:"qi,omitempty"`
  54. // Certificates
  55. X5c []string `json:"x5c,omitempty"`
  56. }
  57. // JSONWebKey represents a public or private key in JWK format.
  58. type JSONWebKey struct {
  59. Key interface{}
  60. Certificates []*x509.Certificate
  61. KeyID string
  62. Algorithm string
  63. Use string
  64. }
  65. // MarshalJSON serializes the given key to its JSON representation.
  66. func (k JSONWebKey) MarshalJSON() ([]byte, error) {
  67. var raw *rawJSONWebKey
  68. var err error
  69. switch key := k.Key.(type) {
  70. case ed25519.PublicKey:
  71. raw = fromEdPublicKey(key)
  72. case *ecdsa.PublicKey:
  73. raw, err = fromEcPublicKey(key)
  74. case *rsa.PublicKey:
  75. raw = fromRsaPublicKey(key)
  76. case ed25519.PrivateKey:
  77. raw, err = fromEdPrivateKey(key)
  78. case *ecdsa.PrivateKey:
  79. raw, err = fromEcPrivateKey(key)
  80. case *rsa.PrivateKey:
  81. raw, err = fromRsaPrivateKey(key)
  82. case []byte:
  83. raw, err = fromSymmetricKey(key)
  84. default:
  85. return nil, fmt.Errorf("square/go-jose: unknown key type '%s'", reflect.TypeOf(key))
  86. }
  87. if err != nil {
  88. return nil, err
  89. }
  90. raw.Kid = k.KeyID
  91. raw.Alg = k.Algorithm
  92. raw.Use = k.Use
  93. for _, cert := range k.Certificates {
  94. raw.X5c = append(raw.X5c, base64.StdEncoding.EncodeToString(cert.Raw))
  95. }
  96. return json.Marshal(raw)
  97. }
  98. // UnmarshalJSON reads a key from its JSON representation.
  99. func (k *JSONWebKey) UnmarshalJSON(data []byte) (err error) {
  100. var raw rawJSONWebKey
  101. err = json.Unmarshal(data, &raw)
  102. if err != nil {
  103. return err
  104. }
  105. var key interface{}
  106. switch raw.Kty {
  107. case "EC":
  108. if raw.D != nil {
  109. key, err = raw.ecPrivateKey()
  110. } else {
  111. key, err = raw.ecPublicKey()
  112. }
  113. case "RSA":
  114. if raw.D != nil {
  115. key, err = raw.rsaPrivateKey()
  116. } else {
  117. key, err = raw.rsaPublicKey()
  118. }
  119. case "oct":
  120. key, err = raw.symmetricKey()
  121. case "OKP":
  122. if raw.Crv == "Ed25519" && raw.X != nil {
  123. if raw.D != nil {
  124. key, err = raw.edPrivateKey()
  125. } else {
  126. key, err = raw.edPublicKey()
  127. }
  128. } else {
  129. err = fmt.Errorf("square/go-jose: unknown curve %s'", raw.Crv)
  130. }
  131. default:
  132. err = fmt.Errorf("square/go-jose: unknown json web key type '%s'", raw.Kty)
  133. }
  134. if err == nil {
  135. *k = JSONWebKey{Key: key, KeyID: raw.Kid, Algorithm: raw.Alg, Use: raw.Use}
  136. k.Certificates, err = parseCertificateChain(raw.X5c)
  137. if err != nil {
  138. return fmt.Errorf("failed to unmarshal x5c field: %s", err)
  139. }
  140. }
  141. return
  142. }
  143. // JSONWebKeySet represents a JWK Set object.
  144. type JSONWebKeySet struct {
  145. Keys []JSONWebKey `json:"keys"`
  146. }
  147. // Key convenience method returns keys by key ID. Specification states
  148. // that a JWK Set "SHOULD" use distinct key IDs, but allows for some
  149. // cases where they are not distinct. Hence method returns a slice
  150. // of JSONWebKeys.
  151. func (s *JSONWebKeySet) Key(kid string) []JSONWebKey {
  152. var keys []JSONWebKey
  153. for _, key := range s.Keys {
  154. if key.KeyID == kid {
  155. keys = append(keys, key)
  156. }
  157. }
  158. return keys
  159. }
  160. const rsaThumbprintTemplate = `{"e":"%s","kty":"RSA","n":"%s"}`
  161. const ecThumbprintTemplate = `{"crv":"%s","kty":"EC","x":"%s","y":"%s"}`
  162. const edThumbprintTemplate = `{"crv":"%s","kty":"OKP",x":"%s"}`
  163. func ecThumbprintInput(curve elliptic.Curve, x, y *big.Int) (string, error) {
  164. coordLength := curveSize(curve)
  165. crv, err := curveName(curve)
  166. if err != nil {
  167. return "", err
  168. }
  169. return fmt.Sprintf(ecThumbprintTemplate, crv,
  170. newFixedSizeBuffer(x.Bytes(), coordLength).base64(),
  171. newFixedSizeBuffer(y.Bytes(), coordLength).base64()), nil
  172. }
  173. func rsaThumbprintInput(n *big.Int, e int) (string, error) {
  174. return fmt.Sprintf(rsaThumbprintTemplate,
  175. newBufferFromInt(uint64(e)).base64(),
  176. newBuffer(n.Bytes()).base64()), nil
  177. }
  178. func edThumbprintInput(ed ed25519.PublicKey) (string, error) {
  179. crv := "Ed25519"
  180. return fmt.Sprintf(edThumbprintTemplate, crv,
  181. newFixedSizeBuffer(ed, 32).base64()), nil
  182. }
  183. // Thumbprint computes the JWK Thumbprint of a key using the
  184. // indicated hash algorithm.
  185. func (k *JSONWebKey) Thumbprint(hash crypto.Hash) ([]byte, error) {
  186. var input string
  187. var err error
  188. switch key := k.Key.(type) {
  189. case ed25519.PublicKey:
  190. input, err = edThumbprintInput(key)
  191. case *ecdsa.PublicKey:
  192. input, err = ecThumbprintInput(key.Curve, key.X, key.Y)
  193. case *ecdsa.PrivateKey:
  194. input, err = ecThumbprintInput(key.Curve, key.X, key.Y)
  195. case *rsa.PublicKey:
  196. input, err = rsaThumbprintInput(key.N, key.E)
  197. case *rsa.PrivateKey:
  198. input, err = rsaThumbprintInput(key.N, key.E)
  199. case ed25519.PrivateKey:
  200. input, err = edThumbprintInput(ed25519.PublicKey(key[0:32]))
  201. default:
  202. return nil, fmt.Errorf("square/go-jose: unknown key type '%s'", reflect.TypeOf(key))
  203. }
  204. if err != nil {
  205. return nil, err
  206. }
  207. h := hash.New()
  208. h.Write([]byte(input))
  209. return h.Sum(nil), nil
  210. }
  211. // IsPublic returns true if the JWK represents a public key (not symmetric, not private).
  212. func (k *JSONWebKey) IsPublic() bool {
  213. switch k.Key.(type) {
  214. case *ecdsa.PublicKey, *rsa.PublicKey, ed25519.PublicKey:
  215. return true
  216. default:
  217. return false
  218. }
  219. }
  220. // Public creates JSONWebKey with corresponding publik key if JWK represents asymmetric private key.
  221. func (k *JSONWebKey) Public() JSONWebKey {
  222. if k.IsPublic() {
  223. return *k
  224. }
  225. ret := *k
  226. switch key := k.Key.(type) {
  227. case *ecdsa.PrivateKey:
  228. ret.Key = key.Public()
  229. case *rsa.PrivateKey:
  230. ret.Key = key.Public()
  231. case ed25519.PrivateKey:
  232. ret.Key = key.Public()
  233. default:
  234. return JSONWebKey{} // returning invalid key
  235. }
  236. return ret
  237. }
  238. // Valid checks that the key contains the expected parameters.
  239. func (k *JSONWebKey) Valid() bool {
  240. if k.Key == nil {
  241. return false
  242. }
  243. switch key := k.Key.(type) {
  244. case *ecdsa.PublicKey:
  245. if key.Curve == nil || key.X == nil || key.Y == nil {
  246. return false
  247. }
  248. case *ecdsa.PrivateKey:
  249. if key.Curve == nil || key.X == nil || key.Y == nil || key.D == nil {
  250. return false
  251. }
  252. case *rsa.PublicKey:
  253. if key.N == nil || key.E == 0 {
  254. return false
  255. }
  256. case *rsa.PrivateKey:
  257. if key.N == nil || key.E == 0 || key.D == nil || len(key.Primes) < 2 {
  258. return false
  259. }
  260. case ed25519.PublicKey:
  261. if len(key) != 32 {
  262. return false
  263. }
  264. case ed25519.PrivateKey:
  265. if len(key) != 64 {
  266. return false
  267. }
  268. default:
  269. return false
  270. }
  271. return true
  272. }
  273. func (key rawJSONWebKey) rsaPublicKey() (*rsa.PublicKey, error) {
  274. if key.N == nil || key.E == nil {
  275. return nil, fmt.Errorf("square/go-jose: invalid RSA key, missing n/e values")
  276. }
  277. return &rsa.PublicKey{
  278. N: key.N.bigInt(),
  279. E: key.E.toInt(),
  280. }, nil
  281. }
  282. func fromEdPublicKey(pub ed25519.PublicKey) *rawJSONWebKey {
  283. return &rawJSONWebKey{
  284. Kty: "OKP",
  285. Crv: "Ed25519",
  286. X: newBuffer(pub),
  287. }
  288. }
  289. func fromRsaPublicKey(pub *rsa.PublicKey) *rawJSONWebKey {
  290. return &rawJSONWebKey{
  291. Kty: "RSA",
  292. N: newBuffer(pub.N.Bytes()),
  293. E: newBufferFromInt(uint64(pub.E)),
  294. }
  295. }
  296. func (key rawJSONWebKey) ecPublicKey() (*ecdsa.PublicKey, error) {
  297. var curve elliptic.Curve
  298. switch key.Crv {
  299. case "P-256":
  300. curve = elliptic.P256()
  301. case "P-384":
  302. curve = elliptic.P384()
  303. case "P-521":
  304. curve = elliptic.P521()
  305. default:
  306. return nil, fmt.Errorf("square/go-jose: unsupported elliptic curve '%s'", key.Crv)
  307. }
  308. if key.X == nil || key.Y == nil {
  309. return nil, errors.New("square/go-jose: invalid EC key, missing x/y values")
  310. }
  311. x := key.X.bigInt()
  312. y := key.Y.bigInt()
  313. if !curve.IsOnCurve(x, y) {
  314. return nil, errors.New("square/go-jose: invalid EC key, X/Y are not on declared curve")
  315. }
  316. return &ecdsa.PublicKey{
  317. Curve: curve,
  318. X: x,
  319. Y: y,
  320. }, nil
  321. }
  322. func fromEcPublicKey(pub *ecdsa.PublicKey) (*rawJSONWebKey, error) {
  323. if pub == nil || pub.X == nil || pub.Y == nil {
  324. return nil, fmt.Errorf("square/go-jose: invalid EC key (nil, or X/Y missing)")
  325. }
  326. name, err := curveName(pub.Curve)
  327. if err != nil {
  328. return nil, err
  329. }
  330. size := curveSize(pub.Curve)
  331. xBytes := pub.X.Bytes()
  332. yBytes := pub.Y.Bytes()
  333. if len(xBytes) > size || len(yBytes) > size {
  334. return nil, fmt.Errorf("square/go-jose: invalid EC key (X/Y too large)")
  335. }
  336. key := &rawJSONWebKey{
  337. Kty: "EC",
  338. Crv: name,
  339. X: newFixedSizeBuffer(xBytes, size),
  340. Y: newFixedSizeBuffer(yBytes, size),
  341. }
  342. return key, nil
  343. }
  344. func (key rawJSONWebKey) edPrivateKey() (ed25519.PrivateKey, error) {
  345. var missing []string
  346. switch {
  347. case key.D == nil:
  348. missing = append(missing, "D")
  349. case key.X == nil:
  350. missing = append(missing, "X")
  351. }
  352. if len(missing) > 0 {
  353. return nil, fmt.Errorf("square/go-jose: invalid Ed25519 private key, missing %s value(s)", strings.Join(missing, ", "))
  354. }
  355. privateKey := make([]byte, ed25519.PrivateKeySize)
  356. copy(privateKey[0:32], key.X.bytes())
  357. copy(privateKey[32:], key.D.bytes())
  358. rv := ed25519.PrivateKey(privateKey)
  359. return rv, nil
  360. }
  361. func (key rawJSONWebKey) edPublicKey() (ed25519.PublicKey, error) {
  362. if key.X == nil {
  363. return nil, fmt.Errorf("square/go-jose: invalid Ed key, missing x value")
  364. }
  365. publicKey := make([]byte, ed25519.PublicKeySize)
  366. copy(publicKey[0:32], key.X.bytes())
  367. rv := ed25519.PublicKey(publicKey)
  368. return rv, nil
  369. }
  370. func (key rawJSONWebKey) rsaPrivateKey() (*rsa.PrivateKey, error) {
  371. var missing []string
  372. switch {
  373. case key.N == nil:
  374. missing = append(missing, "N")
  375. case key.E == nil:
  376. missing = append(missing, "E")
  377. case key.D == nil:
  378. missing = append(missing, "D")
  379. case key.P == nil:
  380. missing = append(missing, "P")
  381. case key.Q == nil:
  382. missing = append(missing, "Q")
  383. }
  384. if len(missing) > 0 {
  385. return nil, fmt.Errorf("square/go-jose: invalid RSA private key, missing %s value(s)", strings.Join(missing, ", "))
  386. }
  387. rv := &rsa.PrivateKey{
  388. PublicKey: rsa.PublicKey{
  389. N: key.N.bigInt(),
  390. E: key.E.toInt(),
  391. },
  392. D: key.D.bigInt(),
  393. Primes: []*big.Int{
  394. key.P.bigInt(),
  395. key.Q.bigInt(),
  396. },
  397. }
  398. if key.Dp != nil {
  399. rv.Precomputed.Dp = key.Dp.bigInt()
  400. }
  401. if key.Dq != nil {
  402. rv.Precomputed.Dq = key.Dq.bigInt()
  403. }
  404. if key.Qi != nil {
  405. rv.Precomputed.Qinv = key.Qi.bigInt()
  406. }
  407. err := rv.Validate()
  408. return rv, err
  409. }
  410. func fromEdPrivateKey(ed ed25519.PrivateKey) (*rawJSONWebKey, error) {
  411. raw := fromEdPublicKey(ed25519.PublicKey(ed[0:32]))
  412. raw.D = newBuffer(ed[32:])
  413. return raw, nil
  414. }
  415. func fromRsaPrivateKey(rsa *rsa.PrivateKey) (*rawJSONWebKey, error) {
  416. if len(rsa.Primes) != 2 {
  417. return nil, ErrUnsupportedKeyType
  418. }
  419. raw := fromRsaPublicKey(&rsa.PublicKey)
  420. raw.D = newBuffer(rsa.D.Bytes())
  421. raw.P = newBuffer(rsa.Primes[0].Bytes())
  422. raw.Q = newBuffer(rsa.Primes[1].Bytes())
  423. return raw, nil
  424. }
  425. func (key rawJSONWebKey) ecPrivateKey() (*ecdsa.PrivateKey, error) {
  426. var curve elliptic.Curve
  427. switch key.Crv {
  428. case "P-256":
  429. curve = elliptic.P256()
  430. case "P-384":
  431. curve = elliptic.P384()
  432. case "P-521":
  433. curve = elliptic.P521()
  434. default:
  435. return nil, fmt.Errorf("square/go-jose: unsupported elliptic curve '%s'", key.Crv)
  436. }
  437. if key.X == nil || key.Y == nil || key.D == nil {
  438. return nil, fmt.Errorf("square/go-jose: invalid EC private key, missing x/y/d values")
  439. }
  440. x := key.X.bigInt()
  441. y := key.Y.bigInt()
  442. if !curve.IsOnCurve(x, y) {
  443. return nil, errors.New("square/go-jose: invalid EC key, X/Y are not on declared curve")
  444. }
  445. return &ecdsa.PrivateKey{
  446. PublicKey: ecdsa.PublicKey{
  447. Curve: curve,
  448. X: x,
  449. Y: y,
  450. },
  451. D: key.D.bigInt(),
  452. }, nil
  453. }
  454. func fromEcPrivateKey(ec *ecdsa.PrivateKey) (*rawJSONWebKey, error) {
  455. raw, err := fromEcPublicKey(&ec.PublicKey)
  456. if err != nil {
  457. return nil, err
  458. }
  459. if ec.D == nil {
  460. return nil, fmt.Errorf("square/go-jose: invalid EC private key")
  461. }
  462. raw.D = newBuffer(ec.D.Bytes())
  463. return raw, nil
  464. }
  465. func fromSymmetricKey(key []byte) (*rawJSONWebKey, error) {
  466. return &rawJSONWebKey{
  467. Kty: "oct",
  468. K: newBuffer(key),
  469. }, nil
  470. }
  471. func (key rawJSONWebKey) symmetricKey() ([]byte, error) {
  472. if key.K == nil {
  473. return nil, fmt.Errorf("square/go-jose: invalid OCT (symmetric) key, missing k value")
  474. }
  475. return key.K.bytes(), nil
  476. }