光棱坦克专栏的宗旨是光学相关的内容,不过由于是我独自一人在业余时间写点东西,可供更新的原创内容并不多。特别是我现在工作重点是跟风利用深度学习的风头,做一点图像和视频识别的工作,离纯光学应用就越走越远了。当然,跟图像处理还是非常相关的。即使是本篇手写代码实践下一个加密第三方计算的实例,其实也可以扯到图像处理上来:最近在策划、说服生科院的员工合作利用深度学习来处理医疗图像以及信号等。这里面涉及到病患隐私保护的问题。一个自然而然的解决方案就是:能不能把原始图像,如fMRI数据加密以后作为训练集交给DNN学习呢?
看上去不可能,但实际已经有很多人在做了。我在查文献的过程中,发现这个问题有很多渊源,其中一个就是姚期智在1982年提出并提供原始示范解答的百万富翁问题(Yao's Millionaires' Problem)。姚期智,正是最近新闻里跟杨振宁一起成为第一批中科院外籍院士的两人之一。
简单来说就是:两个百万富翁(通胀百千倍以后,现在该谈亿万富翁才应景)想比较彼此谁更富有,但是也不愿透漏彼此具体的财富数目。两人的财富以百万计,取以1到10之间的整数。
解法的文字描述很简单,以前用Hash函数拿到的都是密文,而不是数字。既然这个算法讲到用一个任意的大随机数加密一个数字得到另一个数字,看上去就很好玩的样子,于是我就用python手写算法流程实现一下。反正不是CS科班出身,一时也吃不透数学证明,所以不如先从直观的实践入手熟悉下。
代码如下:
# -*- coding: utf-8 -*-
"""Created on Thu Mar 30 23:39:13 2017@author: James Zhu"""
from simpleRSA import *
import random
public_key, private_key = make_key_pair(12) # safe for n<100
A = random.randint(1,9)
B = random.randint(1,9)
def safeCmpAleB(a,b):
print("\nA has i={} millions and B has j={} millions".format(a,b))
print("\nA generate a pair of RSA key:")
print("The public key is {}, which is shared in public".format(public_key))
print("The private key is {}, which is only hold by A\n".format(private_key))
x = random.randint(1000,2000)
print("Step 1: B generate a large random number: ".format(x))
K = public_key.encrypt(x)
print("\tB encryt it with the shared public key to generate a cipher K: ".format(K))
print("\tthen B send c=K-j({}-{}={} to A\n".format(K,b,K-b))
c = K - b
p=29
d=[]
for i in range(c+1,c+11):
d.append( (private_key.decrypt(i) % p))
print("Step 2: A decrypt c+1,...c+10 with his own private key:" )
print("\t{}".format(d))
for i in range(a,10):
d[i]=d[i]+1
print("\n\tA add 1 to c+i+1 to c+10:" )
print("\t{}".format(d))
print("\nStep 3: B test whether x mod p equals to d[j].\n\tif so, i>=j\n\totherwise,i
print("d[j] is {}, x mod p is {}".format(d[b-1],x%p))
if(x%p==d[b-1]):
return True
else:
return False
print(safeCmpAleB(A,B))
print(A>=B)
其实,整个加密比较的算法很容易实现,二三十行代码就搞定了。代码这么长这么啰嗦是因为加入了很多print以便输出中间信息方便我观察。
输出如下:
A has i=4 millions and B has j=3 millions
A generate a pair of RSA key:
The public key is PublicKey(n=3827, e=5), which is shared in public
The private key is PrivateKey(n=3827, d=2957), which is only hold by A
Step 1: B generate a large random number:
B encryt it with the shared public key to generate a cipher K:
then B send c=K-j(343-3=340 to A
Step 2: A decrypt c+1,...c+10 with his own private key:
[15, 25, 9, 3, 21, 3, 11, 3, 28, 10]
A add 1 to c+i+1 to c+10:
[15, 25, 9, 3, 22, 4, 12, 4, 29, 11]
Step 3: B test whether x mod p equals to d[j].
if so, i>=j
otherwise,i
d[j] is 9, x mod p is 9
True
True
当A比B同样富有或同样富有时,输出是true,反之为假。整个计算过程A和B都是不知道彼此的具体数目的。
其中用到的库是直接网上搜到的RSA的不严格简单实现,即只是在形式上实现RSA的基本功能,不确保其安全性和效率等:
当然,这个算法应该只是抛砖引玉的例子,应该有很多与时俱进的先进算法可以更好更快更安全的解决姚百万富翁问题。