rsa_intersect_base.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. #
  2. # Copyright 2021 The FATE Authors. All Rights Reserved.
  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. import random
  17. from federatedml.param.intersect_param import DEFAULT_RANDOM_BIT
  18. from federatedml.secureprotol import gmpy_math
  19. from federatedml.secureprotol.encrypt import RsaEncrypt
  20. from federatedml.secureprotol.hash.hash_factory import Hash
  21. from federatedml.statistic.intersect import Intersect
  22. from federatedml.transfer_variable.transfer_class.rsa_intersect_transfer_variable import RsaIntersectTransferVariable
  23. from federatedml.util import consts, LOGGER
  24. class RsaIntersect(Intersect):
  25. def __init__(self):
  26. super().__init__()
  27. # self.intersect_cache_param = intersect_params.intersect_cache_param
  28. self.rcv_e = None
  29. self.rcv_n = None
  30. self.e = None
  31. self.d = None
  32. self.n = None
  33. self.p = None
  34. self.q = None
  35. self.cp = None
  36. self.cq = None
  37. # self.r = None
  38. self.transfer_variable = RsaIntersectTransferVariable()
  39. self.role = None
  40. def load_params(self, param):
  41. super().load_params(param=param)
  42. self.rsa_params = param.rsa_params
  43. self.random_bit = self.rsa_params.random_bit
  44. self.split_calculation = self.rsa_params.split_calculation
  45. self.random_base_fraction = self.rsa_params.random_base_fraction
  46. self.first_hash_operator = Hash(self.rsa_params.hash_method, False)
  47. self.final_hash_operator = Hash(self.rsa_params.final_hash_method, False)
  48. self.salt = self.rsa_params.salt
  49. def get_intersect_method_meta(self):
  50. rsa_meta = {"intersect_method": consts.RSA,
  51. "hash_method": self.rsa_params.hash_method,
  52. "final_hash_method": self.rsa_params.final_hash_method,
  53. "salt": self.salt,
  54. "random_bit": self.random_bit}
  55. return rsa_meta
  56. @staticmethod
  57. def extend_pair(v1, v2):
  58. return v1 + v2
  59. @staticmethod
  60. def pubkey_id_process(data, fraction, random_bit, rsa_e, rsa_n, hash_operator=None, salt=''):
  61. if fraction and fraction <= consts.MAX_BASE_FRACTION:
  62. LOGGER.debug(f"fraction value: {fraction} provided, use fraction in pubkey id process")
  63. count = max(round(data.count() * max(fraction, consts.MIN_BASE_FRACTION)), 1)
  64. def group_kv(kv_iterator):
  65. res = []
  66. for k, v in kv_iterator:
  67. if hash_operator is not None:
  68. v = (k, v)
  69. k = int(Intersect.hash(k, hash_operator, salt), 16)
  70. res.append((k % count, [(k, v)]))
  71. return res
  72. reduced_pair_group = data.mapReducePartitions(group_kv, RsaIntersect.extend_pair)
  73. def pubkey_id_generate(k, pair):
  74. r = random.SystemRandom().getrandbits(random_bit)
  75. r_e = gmpy_math.powmod(r, rsa_e, rsa_n)
  76. for hash_sid, v in pair:
  77. processed_id = r_e * hash_sid % rsa_n
  78. yield processed_id, (v[0], r)
  79. return reduced_pair_group.flatMap(pubkey_id_generate)
  80. else:
  81. LOGGER.debug(f"fraction not provided or invalid, fraction value: {fraction}.")
  82. return data.map(lambda k, v: RsaIntersect.pubkey_id_process_per(k, v, random_bit, rsa_e, rsa_n,
  83. hash_operator, salt))
  84. @staticmethod
  85. def generate_rsa_key(rsa_bit=1024):
  86. LOGGER.info(f"Generate {rsa_bit}-bit RSA key.")
  87. encrypt_operator = RsaEncrypt()
  88. encrypt_operator.generate_key(rsa_bit)
  89. return encrypt_operator.get_key_pair()
  90. def generate_protocol_key(self):
  91. if self.role == consts.HOST:
  92. self.e, self.d, self.n, self.p, self.q = self.generate_rsa_key(self.rsa_params.key_length)
  93. self.cp, self.cq = gmpy_math.crt_coefficient(self.p, self.q)
  94. else:
  95. e, d, n, p, q, cp, cq = [], [], [], [], [], [], []
  96. for i in range(len(self.host_party_id_list)):
  97. e_i, d_i, n_i, p_i, q_i = self.generate_rsa_key(self.rsa_params.key_length)
  98. cp_i, cq_i = gmpy_math.crt_coefficient(p_i, q_i)
  99. e.append(e_i)
  100. d.append(d_i)
  101. n.append(n_i)
  102. p.append(p_i)
  103. q.append(q_i)
  104. cp.append(cp_i)
  105. cq.append(cq_i)
  106. self.e = e
  107. self.d = d
  108. self.n = n
  109. self.p = p
  110. self.q = q
  111. self.cp = cp
  112. self.cq = cq
  113. @staticmethod
  114. def pubkey_id_process_per(hash_sid, v, random_bit, rsa_e, rsa_n, hash_operator=None, salt=''):
  115. r = random.SystemRandom().getrandbits(random_bit)
  116. if hash_operator:
  117. processed_id = gmpy_math.powmod(r, rsa_e, rsa_n) * \
  118. int(Intersect.hash(hash_sid, hash_operator, salt), 16) % rsa_n
  119. return processed_id, (hash_sid, r)
  120. else:
  121. processed_id = gmpy_math.powmod(r, rsa_e, rsa_n) * hash_sid % rsa_n
  122. return processed_id, (v[0], r)
  123. @staticmethod
  124. def prvkey_id_process(
  125. hash_sid,
  126. v,
  127. rsa_d,
  128. rsa_n,
  129. rsa_p,
  130. rsa_q,
  131. cp,
  132. cq,
  133. final_hash_operator,
  134. salt,
  135. first_hash_operator=None):
  136. if first_hash_operator:
  137. processed_id = Intersect.hash(gmpy_math.powmod_crt(int(Intersect.hash(
  138. hash_sid, first_hash_operator, salt), 16), rsa_d, rsa_n, rsa_p, rsa_q, cp, cq), final_hash_operator, salt)
  139. return processed_id, hash_sid
  140. else:
  141. processed_id = Intersect.hash(gmpy_math.powmod_crt(hash_sid, rsa_d, rsa_n, rsa_p, rsa_q, cp, cq),
  142. final_hash_operator,
  143. salt)
  144. return processed_id, v[0]
  145. def cal_prvkey_ids_process_pair(self, data_instances, d, n, p, q, cp, cq, first_hash_operator=None):
  146. return data_instances.map(
  147. lambda k, v: self.prvkey_id_process(k, v, d, n, p, q, cp, cq,
  148. self.final_hash_operator,
  149. self.rsa_params.salt,
  150. first_hash_operator)
  151. )
  152. @staticmethod
  153. def sign_id(hash_sid, rsa_d, rsa_n, rsa_p, rsa_q, cp, cq):
  154. return gmpy_math.powmod_crt(hash_sid, rsa_d, rsa_n, rsa_p, rsa_q, cp, cq)
  155. def split_calculation_process(self, data_instances):
  156. raise NotImplementedError("This method should not be called here")
  157. def unified_calculation_process(self, data_instances):
  158. raise NotImplementedError("This method should not be called here")
  159. def cache_unified_calculation_process(self, data_instances, cache_set):
  160. raise NotImplementedError("This method should not be called here")
  161. def run_intersect(self, data_instances):
  162. LOGGER.info("Start RSA Intersection")
  163. if self.split_calculation:
  164. # H(k), (k, v)
  165. hash_data_instances = data_instances.map(
  166. lambda k, v: (int(Intersect.hash(k, self.first_hash_operator, self.salt), 16), (k, v)))
  167. intersect_ids = self.split_calculation_process(hash_data_instances)
  168. else:
  169. intersect_ids = self.unified_calculation_process(data_instances)
  170. if intersect_ids is not None:
  171. intersect_ids = intersect_ids.mapValues(lambda v: None)
  172. return intersect_ids
  173. def run_cache_intersect(self, data_instances, cache_data):
  174. LOGGER.info("Start RSA Intersection with cache")
  175. if self.split_calculation:
  176. LOGGER.warning(f"split_calculation not applicable to cache-enabled RSA intersection.")
  177. intersect_ids = self.cache_unified_calculation_process(data_instances, cache_data)
  178. if intersect_ids is not None:
  179. intersect_ids = intersect_ids.mapValues(lambda v: None)
  180. return intersect_ids