一、问题描述
使用bn256( Barreto-Naehrig curve )实现了bls公钥的产生、签名以及验证。但是后面做网络编程的时候,发现产生的bls公钥没办法编码成 JSON 字符串,如下:
TypeError: Object of type curve_twist is not JSON serializable
没办法编码那就没办法发送公钥了。(因为没实现过密码方案,不知道还可以用pickle封装。)
二、解决思路
保存公钥的参数,然后编码成JSON 字符串,发送到服务端之后再恢复。
三、解决办法
办法一(不行)
进入bn256模块发现公钥是这个类型的:
twist_G = curve_twist(
gfp_2(21167961636542580255011770066570541300993051739349375019639421053990175267184,
64746500191241794695844075326670126197795977525365406531717464316923369116492),
gfp_2(20666913350058776956210519119118544732556678129809273996262322366050359951122,
17778617556404439934652658462602675281523610326338642107814333856843981424549),
gfp_2(0,1))
然后我就:
import json
bls_priv, bls_pub = bls_keygen(103)
# gfp-2
x, y, z = bls_pub[0], bls_pub[1], bls_pub[2]
# gfp-1
x1, x2 = x[0], x[1]
y1, y2 = y[0], y[1]
z1, z2 = z[0], z[1]
# v
x11 = x1[0]
x21 = x2[0]
y11 = y1[0]
y21 = y2[0]
z11 = z1[0]
z21 = z2[0]
bls_pub_key = {'x': (x11, x21), 'y': (y11, y21), 'z': (z11, z21)}
s1_bls_pub = json.dumps(bls_pub)
结果:
x, y, z = bls_pub[0], bls_pub[1], bls_pub[2]
TypeError: 'curve_twist' object is not subscriptable
好的,是我天真了。
方法二
后来看了一下bn256模块中curve_twist和gfp_2、gfp_1的部分定义,发现要提取公钥里面的值还是不太容易的。看来只能重新想办法了。
然后看了一下Paillier公钥是怎么传送的,发现人家自己写了个类可以提取参数。
又找了找其他的加密算法,让我发现了pickle模块,可以对公钥进行封装。
import pickle
bls_priv, bls_pub = bls_keygen(103)
s1_bls_pub = pickle.dumps(bls_pub)
s2_bls_pub = pickle.loads(s1_bls_pub)
print("bls_pub:", bls_pub)
print("s2_bls_pub:", s2_bls_pub)
输出结果:
bls_pub: ((58674098498214840478542848191202633647988712003756354423963557765213149794711,18074130537995541126339902448898846562816713830034544124462264265137164275848), (46191122735729332449374068183914912413659308068662976614949151663835585648232,37229712564877209688660641825331527879679434919660153195038976686333320202989))
s2_bls_pub: ((58674098498214840478542848191202633647988712003756354423963557765213149794711,18074130537995541126339902448898846562816713830034544124462264265137164275848), (46191122735729332449374068183914912413659308068662976614949151663835585648232,37229712564877209688660641825331527879679434919660153195038976686333320202989))