github.com/zmap/zcrypto@v0.0.0-20240512203510-0fef58d9a9db/json/rsa.go (about)

     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  
    15  package json
    16  
    17  import (
    18  	"crypto/rsa"
    19  	"encoding/json"
    20  	"fmt"
    21  	"math/big"
    22  )
    23  
    24  // RSAPublicKey provides JSON methods for the standard rsa.PublicKey.
    25  type RSAPublicKey struct {
    26  	*rsa.PublicKey
    27  }
    28  
    29  type auxRSAPublicKey struct {
    30  	Exponent int    `json:"exponent"`
    31  	Modulus  []byte `json:"modulus"`
    32  	Length   int    `json:"length"`
    33  }
    34  
    35  // RSAClientParams are the TLS key exchange parameters for RSA keys.
    36  type RSAClientParams struct {
    37  	Length       uint16 `json:"length,omitempty"`
    38  	EncryptedPMS []byte `json:"encrypted_pre_master_secret,omitempty"`
    39  }
    40  
    41  // MarshalJSON implements the json.Marshal interface
    42  func (rp *RSAPublicKey) MarshalJSON() ([]byte, error) {
    43  	var aux auxRSAPublicKey
    44  	if rp.PublicKey != nil {
    45  		aux.Exponent = rp.E
    46  		aux.Modulus = rp.N.Bytes()
    47  		aux.Length = len(aux.Modulus) * 8
    48  	}
    49  	return json.Marshal(&aux)
    50  }
    51  
    52  // UnmarshalJSON implements the json.Unmarshal interface
    53  func (rp *RSAPublicKey) UnmarshalJSON(b []byte) error {
    54  	var aux auxRSAPublicKey
    55  	if err := json.Unmarshal(b, &aux); err != nil {
    56  		return err
    57  	}
    58  	if rp.PublicKey == nil {
    59  		rp.PublicKey = new(rsa.PublicKey)
    60  	}
    61  	rp.E = aux.Exponent
    62  	rp.N = big.NewInt(0).SetBytes(aux.Modulus)
    63  	if len(aux.Modulus)*8 != aux.Length {
    64  		return fmt.Errorf("mismatched length (got %d, field specified %d)", len(aux.Modulus), aux.Length)
    65  	}
    66  	return nil
    67  }