rsa.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * ZGrab Copyright 2015 Regents of the University of Michigan
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy
  6. * of the License at http://www.apache.org/licenses/LICENSE-2.0
  7. *
  8. * Unless required by applicable law or agreed to in writing, software
  9. * distributed under the License is distributed on an "AS IS" BASIS,
  10. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  11. * implied. See the License for the specific language governing
  12. * permissions and limitations under the License.
  13. */
  14. package json
  15. import (
  16. "crypto/rsa"
  17. "encoding/json"
  18. "fmt"
  19. "math/big"
  20. )
  21. // RSAPublicKey provides JSON methods for the standard rsa.PublicKey.
  22. type RSAPublicKey struct {
  23. *rsa.PublicKey
  24. }
  25. type auxRSAPublicKey struct {
  26. Exponent int `json:"exponent"`
  27. Modulus []byte `json:"modulus"`
  28. Length int `json:"length"`
  29. }
  30. // RSAClientParams are the TLS key exchange parameters for RSA keys.
  31. type RSAClientParams struct {
  32. Length uint16 `json:"length,omitempty"`
  33. EncryptedPMS []byte `json:"encrypted_pre_master_secret,omitempty"`
  34. }
  35. // MarshalJSON implements the json.Marshal interface
  36. func (rp *RSAPublicKey) MarshalJSON() ([]byte, error) {
  37. var aux auxRSAPublicKey
  38. if rp.PublicKey != nil {
  39. aux.Exponent = rp.E
  40. aux.Modulus = rp.N.Bytes()
  41. aux.Length = len(aux.Modulus) * 8
  42. }
  43. return json.Marshal(&aux)
  44. }
  45. // UnmarshalJSON implements the json.Unmarshal interface
  46. func (rp *RSAPublicKey) UnmarshalJSON(b []byte) error {
  47. var aux auxRSAPublicKey
  48. if err := json.Unmarshal(b, &aux); err != nil {
  49. return err
  50. }
  51. if rp.PublicKey == nil {
  52. rp.PublicKey = new(rsa.PublicKey)
  53. }
  54. rp.E = aux.Exponent
  55. rp.N = big.NewInt(0).SetBytes(aux.Modulus)
  56. if len(aux.Modulus)*8 != aux.Length {
  57. return fmt.Errorf("mismatched length (got %d, field specified %d)", len(aux.Modulus), aux.Length)
  58. }
  59. return nil
  60. }