rsa_key.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. package libtrust
  2. import (
  3. "crypto"
  4. "crypto/rand"
  5. "crypto/rsa"
  6. "crypto/x509"
  7. "encoding/json"
  8. "encoding/pem"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "math/big"
  13. )
  14. /*
  15. * RSA DSA PUBLIC KEY
  16. */
  17. // rsaPublicKey implements a JWK Public Key using RSA digital signature algorithms.
  18. type rsaPublicKey struct {
  19. *rsa.PublicKey
  20. extended map[string]interface{}
  21. }
  22. func fromRSAPublicKey(cryptoPublicKey *rsa.PublicKey) *rsaPublicKey {
  23. return &rsaPublicKey{cryptoPublicKey, map[string]interface{}{}}
  24. }
  25. // KeyType returns the JWK key type for RSA keys, i.e., "RSA".
  26. func (k *rsaPublicKey) KeyType() string {
  27. return "RSA"
  28. }
  29. // KeyID returns a distinct identifier which is unique to this Public Key.
  30. func (k *rsaPublicKey) KeyID() string {
  31. return keyIDFromCryptoKey(k)
  32. }
  33. func (k *rsaPublicKey) String() string {
  34. return fmt.Sprintf("RSA Public Key <%s>", k.KeyID())
  35. }
  36. // Verify verifyies the signature of the data in the io.Reader using this Public Key.
  37. // The alg parameter should be the name of the JWA digital signature algorithm
  38. // which was used to produce the signature and should be supported by this
  39. // public key. Returns a nil error if the signature is valid.
  40. func (k *rsaPublicKey) Verify(data io.Reader, alg string, signature []byte) error {
  41. // Verify the signature of the given date, return non-nil error if valid.
  42. sigAlg, err := rsaSignatureAlgorithmByName(alg)
  43. if err != nil {
  44. return fmt.Errorf("unable to verify Signature: %s", err)
  45. }
  46. hasher := sigAlg.HashID().New()
  47. _, err = io.Copy(hasher, data)
  48. if err != nil {
  49. return fmt.Errorf("error reading data to sign: %s", err)
  50. }
  51. hash := hasher.Sum(nil)
  52. err = rsa.VerifyPKCS1v15(k.PublicKey, sigAlg.HashID(), hash, signature)
  53. if err != nil {
  54. return fmt.Errorf("invalid %s signature: %s", sigAlg.HeaderParam(), err)
  55. }
  56. return nil
  57. }
  58. // CryptoPublicKey returns the internal object which can be used as a
  59. // crypto.PublicKey for use with other standard library operations. The type
  60. // is either *rsa.PublicKey or *ecdsa.PublicKey
  61. func (k *rsaPublicKey) CryptoPublicKey() crypto.PublicKey {
  62. return k.PublicKey
  63. }
  64. func (k *rsaPublicKey) toMap() map[string]interface{} {
  65. jwk := make(map[string]interface{})
  66. for k, v := range k.extended {
  67. jwk[k] = v
  68. }
  69. jwk["kty"] = k.KeyType()
  70. jwk["kid"] = k.KeyID()
  71. jwk["n"] = joseBase64UrlEncode(k.N.Bytes())
  72. jwk["e"] = joseBase64UrlEncode(serializeRSAPublicExponentParam(k.E))
  73. return jwk
  74. }
  75. // MarshalJSON serializes this Public Key using the JWK JSON serialization format for
  76. // RSA keys.
  77. func (k *rsaPublicKey) MarshalJSON() (data []byte, err error) {
  78. return json.Marshal(k.toMap())
  79. }
  80. // PEMBlock serializes this Public Key to DER-encoded PKIX format.
  81. func (k *rsaPublicKey) PEMBlock() (*pem.Block, error) {
  82. derBytes, err := x509.MarshalPKIXPublicKey(k.PublicKey)
  83. if err != nil {
  84. return nil, fmt.Errorf("unable to serialize RSA PublicKey to DER-encoded PKIX format: %s", err)
  85. }
  86. k.extended["kid"] = k.KeyID() // For display purposes.
  87. return createPemBlock("PUBLIC KEY", derBytes, k.extended)
  88. }
  89. func (k *rsaPublicKey) AddExtendedField(field string, value interface{}) {
  90. k.extended[field] = value
  91. }
  92. func (k *rsaPublicKey) GetExtendedField(field string) interface{} {
  93. v, ok := k.extended[field]
  94. if !ok {
  95. return nil
  96. }
  97. return v
  98. }
  99. func rsaPublicKeyFromMap(jwk map[string]interface{}) (*rsaPublicKey, error) {
  100. // JWK key type (kty) has already been determined to be "RSA".
  101. // Need to extract 'n', 'e', and 'kid' and check for
  102. // consistency.
  103. // Get the modulus parameter N.
  104. nB64Url, err := stringFromMap(jwk, "n")
  105. if err != nil {
  106. return nil, fmt.Errorf("JWK RSA Public Key modulus: %s", err)
  107. }
  108. n, err := parseRSAModulusParam(nB64Url)
  109. if err != nil {
  110. return nil, fmt.Errorf("JWK RSA Public Key modulus: %s", err)
  111. }
  112. // Get the public exponent E.
  113. eB64Url, err := stringFromMap(jwk, "e")
  114. if err != nil {
  115. return nil, fmt.Errorf("JWK RSA Public Key exponent: %s", err)
  116. }
  117. e, err := parseRSAPublicExponentParam(eB64Url)
  118. if err != nil {
  119. return nil, fmt.Errorf("JWK RSA Public Key exponent: %s", err)
  120. }
  121. key := &rsaPublicKey{
  122. PublicKey: &rsa.PublicKey{N: n, E: e},
  123. }
  124. // Key ID is optional, but if it exists, it should match the key.
  125. _, ok := jwk["kid"]
  126. if ok {
  127. kid, err := stringFromMap(jwk, "kid")
  128. if err != nil {
  129. return nil, fmt.Errorf("JWK RSA Public Key ID: %s", err)
  130. }
  131. if kid != key.KeyID() {
  132. return nil, fmt.Errorf("JWK RSA Public Key ID does not match: %s", kid)
  133. }
  134. }
  135. if _, ok := jwk["d"]; ok {
  136. return nil, fmt.Errorf("JWK RSA Public Key cannot contain private exponent")
  137. }
  138. key.extended = jwk
  139. return key, nil
  140. }
  141. /*
  142. * RSA DSA PRIVATE KEY
  143. */
  144. // rsaPrivateKey implements a JWK Private Key using RSA digital signature algorithms.
  145. type rsaPrivateKey struct {
  146. rsaPublicKey
  147. *rsa.PrivateKey
  148. }
  149. func fromRSAPrivateKey(cryptoPrivateKey *rsa.PrivateKey) *rsaPrivateKey {
  150. return &rsaPrivateKey{
  151. *fromRSAPublicKey(&cryptoPrivateKey.PublicKey),
  152. cryptoPrivateKey,
  153. }
  154. }
  155. // PublicKey returns the Public Key data associated with this Private Key.
  156. func (k *rsaPrivateKey) PublicKey() PublicKey {
  157. return &k.rsaPublicKey
  158. }
  159. func (k *rsaPrivateKey) String() string {
  160. return fmt.Sprintf("RSA Private Key <%s>", k.KeyID())
  161. }
  162. // Sign signs the data read from the io.Reader using a signature algorithm supported
  163. // by the RSA private key. If the specified hashing algorithm is supported by
  164. // this key, that hash function is used to generate the signature otherwise the
  165. // the default hashing algorithm for this key is used. Returns the signature
  166. // and the name of the JWK signature algorithm used, e.g., "RS256", "RS384",
  167. // "RS512".
  168. func (k *rsaPrivateKey) Sign(data io.Reader, hashID crypto.Hash) (signature []byte, alg string, err error) {
  169. // Generate a signature of the data using the internal alg.
  170. sigAlg := rsaPKCS1v15SignatureAlgorithmForHashID(hashID)
  171. hasher := sigAlg.HashID().New()
  172. _, err = io.Copy(hasher, data)
  173. if err != nil {
  174. return nil, "", fmt.Errorf("error reading data to sign: %s", err)
  175. }
  176. hash := hasher.Sum(nil)
  177. signature, err = rsa.SignPKCS1v15(rand.Reader, k.PrivateKey, sigAlg.HashID(), hash)
  178. if err != nil {
  179. return nil, "", fmt.Errorf("error producing signature: %s", err)
  180. }
  181. alg = sigAlg.HeaderParam()
  182. return
  183. }
  184. // CryptoPrivateKey returns the internal object which can be used as a
  185. // crypto.PublicKey for use with other standard library operations. The type
  186. // is either *rsa.PublicKey or *ecdsa.PublicKey
  187. func (k *rsaPrivateKey) CryptoPrivateKey() crypto.PrivateKey {
  188. return k.PrivateKey
  189. }
  190. func (k *rsaPrivateKey) toMap() map[string]interface{} {
  191. k.Precompute() // Make sure the precomputed values are stored.
  192. jwk := k.rsaPublicKey.toMap()
  193. jwk["d"] = joseBase64UrlEncode(k.D.Bytes())
  194. jwk["p"] = joseBase64UrlEncode(k.Primes[0].Bytes())
  195. jwk["q"] = joseBase64UrlEncode(k.Primes[1].Bytes())
  196. jwk["dp"] = joseBase64UrlEncode(k.Precomputed.Dp.Bytes())
  197. jwk["dq"] = joseBase64UrlEncode(k.Precomputed.Dq.Bytes())
  198. jwk["qi"] = joseBase64UrlEncode(k.Precomputed.Qinv.Bytes())
  199. otherPrimes := k.Primes[2:]
  200. if len(otherPrimes) > 0 {
  201. otherPrimesInfo := make([]interface{}, len(otherPrimes))
  202. for i, r := range otherPrimes {
  203. otherPrimeInfo := make(map[string]string, 3)
  204. otherPrimeInfo["r"] = joseBase64UrlEncode(r.Bytes())
  205. crtVal := k.Precomputed.CRTValues[i]
  206. otherPrimeInfo["d"] = joseBase64UrlEncode(crtVal.Exp.Bytes())
  207. otherPrimeInfo["t"] = joseBase64UrlEncode(crtVal.Coeff.Bytes())
  208. otherPrimesInfo[i] = otherPrimeInfo
  209. }
  210. jwk["oth"] = otherPrimesInfo
  211. }
  212. return jwk
  213. }
  214. // MarshalJSON serializes this Private Key using the JWK JSON serialization format for
  215. // RSA keys.
  216. func (k *rsaPrivateKey) MarshalJSON() (data []byte, err error) {
  217. return json.Marshal(k.toMap())
  218. }
  219. // PEMBlock serializes this Private Key to DER-encoded PKIX format.
  220. func (k *rsaPrivateKey) PEMBlock() (*pem.Block, error) {
  221. derBytes := x509.MarshalPKCS1PrivateKey(k.PrivateKey)
  222. k.extended["keyID"] = k.KeyID() // For display purposes.
  223. return createPemBlock("RSA PRIVATE KEY", derBytes, k.extended)
  224. }
  225. func rsaPrivateKeyFromMap(jwk map[string]interface{}) (*rsaPrivateKey, error) {
  226. // The JWA spec for RSA Private Keys (draft rfc section 5.3.2) states that
  227. // only the private key exponent 'd' is REQUIRED, the others are just for
  228. // signature/decryption optimizations and SHOULD be included when the JWK
  229. // is produced. We MAY choose to accept a JWK which only includes 'd', but
  230. // we're going to go ahead and not choose to accept it without the extra
  231. // fields. Only the 'oth' field will be optional (for multi-prime keys).
  232. privateExponent, err := parseRSAPrivateKeyParamFromMap(jwk, "d")
  233. if err != nil {
  234. return nil, fmt.Errorf("JWK RSA Private Key exponent: %s", err)
  235. }
  236. firstPrimeFactor, err := parseRSAPrivateKeyParamFromMap(jwk, "p")
  237. if err != nil {
  238. return nil, fmt.Errorf("JWK RSA Private Key prime factor: %s", err)
  239. }
  240. secondPrimeFactor, err := parseRSAPrivateKeyParamFromMap(jwk, "q")
  241. if err != nil {
  242. return nil, fmt.Errorf("JWK RSA Private Key prime factor: %s", err)
  243. }
  244. firstFactorCRT, err := parseRSAPrivateKeyParamFromMap(jwk, "dp")
  245. if err != nil {
  246. return nil, fmt.Errorf("JWK RSA Private Key CRT exponent: %s", err)
  247. }
  248. secondFactorCRT, err := parseRSAPrivateKeyParamFromMap(jwk, "dq")
  249. if err != nil {
  250. return nil, fmt.Errorf("JWK RSA Private Key CRT exponent: %s", err)
  251. }
  252. crtCoeff, err := parseRSAPrivateKeyParamFromMap(jwk, "qi")
  253. if err != nil {
  254. return nil, fmt.Errorf("JWK RSA Private Key CRT coefficient: %s", err)
  255. }
  256. var oth interface{}
  257. if _, ok := jwk["oth"]; ok {
  258. oth = jwk["oth"]
  259. delete(jwk, "oth")
  260. }
  261. // JWK key type (kty) has already been determined to be "RSA".
  262. // Need to extract the public key information, then extract the private
  263. // key values.
  264. publicKey, err := rsaPublicKeyFromMap(jwk)
  265. if err != nil {
  266. return nil, err
  267. }
  268. privateKey := &rsa.PrivateKey{
  269. PublicKey: *publicKey.PublicKey,
  270. D: privateExponent,
  271. Primes: []*big.Int{firstPrimeFactor, secondPrimeFactor},
  272. Precomputed: rsa.PrecomputedValues{
  273. Dp: firstFactorCRT,
  274. Dq: secondFactorCRT,
  275. Qinv: crtCoeff,
  276. },
  277. }
  278. if oth != nil {
  279. // Should be an array of more JSON objects.
  280. otherPrimesInfo, ok := oth.([]interface{})
  281. if !ok {
  282. return nil, errors.New("JWK RSA Private Key: Invalid other primes info: must be an array")
  283. }
  284. numOtherPrimeFactors := len(otherPrimesInfo)
  285. if numOtherPrimeFactors == 0 {
  286. return nil, errors.New("JWK RSA Privake Key: Invalid other primes info: must be absent or non-empty")
  287. }
  288. otherPrimeFactors := make([]*big.Int, numOtherPrimeFactors)
  289. productOfPrimes := new(big.Int).Mul(firstPrimeFactor, secondPrimeFactor)
  290. crtValues := make([]rsa.CRTValue, numOtherPrimeFactors)
  291. for i, val := range otherPrimesInfo {
  292. otherPrimeinfo, ok := val.(map[string]interface{})
  293. if !ok {
  294. return nil, errors.New("JWK RSA Private Key: Invalid other prime info: must be a JSON object")
  295. }
  296. otherPrimeFactor, err := parseRSAPrivateKeyParamFromMap(otherPrimeinfo, "r")
  297. if err != nil {
  298. return nil, fmt.Errorf("JWK RSA Private Key prime factor: %s", err)
  299. }
  300. otherFactorCRT, err := parseRSAPrivateKeyParamFromMap(otherPrimeinfo, "d")
  301. if err != nil {
  302. return nil, fmt.Errorf("JWK RSA Private Key CRT exponent: %s", err)
  303. }
  304. otherCrtCoeff, err := parseRSAPrivateKeyParamFromMap(otherPrimeinfo, "t")
  305. if err != nil {
  306. return nil, fmt.Errorf("JWK RSA Private Key CRT coefficient: %s", err)
  307. }
  308. crtValue := crtValues[i]
  309. crtValue.Exp = otherFactorCRT
  310. crtValue.Coeff = otherCrtCoeff
  311. crtValue.R = productOfPrimes
  312. otherPrimeFactors[i] = otherPrimeFactor
  313. productOfPrimes = new(big.Int).Mul(productOfPrimes, otherPrimeFactor)
  314. }
  315. privateKey.Primes = append(privateKey.Primes, otherPrimeFactors...)
  316. privateKey.Precomputed.CRTValues = crtValues
  317. }
  318. key := &rsaPrivateKey{
  319. rsaPublicKey: *publicKey,
  320. PrivateKey: privateKey,
  321. }
  322. return key, nil
  323. }
  324. /*
  325. * Key Generation Functions.
  326. */
  327. func generateRSAPrivateKey(bits int) (k *rsaPrivateKey, err error) {
  328. k = new(rsaPrivateKey)
  329. k.PrivateKey, err = rsa.GenerateKey(rand.Reader, bits)
  330. if err != nil {
  331. return nil, err
  332. }
  333. k.rsaPublicKey.PublicKey = &k.PrivateKey.PublicKey
  334. k.extended = make(map[string]interface{})
  335. return
  336. }
  337. // GenerateRSA2048PrivateKey generates a key pair using 2048-bit RSA.
  338. func GenerateRSA2048PrivateKey() (PrivateKey, error) {
  339. k, err := generateRSAPrivateKey(2048)
  340. if err != nil {
  341. return nil, fmt.Errorf("error generating RSA 2048-bit key: %s", err)
  342. }
  343. return k, nil
  344. }
  345. // GenerateRSA3072PrivateKey generates a key pair using 3072-bit RSA.
  346. func GenerateRSA3072PrivateKey() (PrivateKey, error) {
  347. k, err := generateRSAPrivateKey(3072)
  348. if err != nil {
  349. return nil, fmt.Errorf("error generating RSA 3072-bit key: %s", err)
  350. }
  351. return k, nil
  352. }
  353. // GenerateRSA4096PrivateKey generates a key pair using 4096-bit RSA.
  354. func GenerateRSA4096PrivateKey() (PrivateKey, error) {
  355. k, err := generateRSAPrivateKey(4096)
  356. if err != nil {
  357. return nil, fmt.Errorf("error generating RSA 4096-bit key: %s", err)
  358. }
  359. return k, nil
  360. }