Charm-crypto的安装与使用

  1. Charm简介
    Charm是Joseph A. Akinyele等在2013提出的一个用于进行快速加密的平台(Python库),再Charm平台里有着各种工具包能够进行加密,解密等,具体包括IBE,ABE,AES,DES,RSA等对称以及非堆成加密。
    Charm是一个基于Python的开源项目,项目地址,最底层使用斯坦福大学的PBC库,用于配对运算;以及大数运算GMP库,用于大数运算。
    在Charm项目Intsall文件里已经写出来了Charm库的安装过程,但是在实际的安装过程中存在一些问题。
    这个博客主要是Ubuntu16.04,python3环境下在学习配置,使用Charm的记录。
  2. Charm安装前准备工作
    (1) 下载Charm包。这里使用的为Charm-Crypto0.43 python3版https://github.com/JHUISI/charm/releases/download/v0.43/Charm-Crypto-0.43_Python3.tar.gz
    (2) 下载PBC库。https://crypto.stanford.edu/pbc/files/pbc-0.5.14.tar.gz
    (3) 下载GMP。ftp://ftp.gmplib.org/pub/gmp/gmp-5.1.3.tar.bz2
    (4) 下载Python IDE 这里用的是Pycharm
  3. 安装过程
    以下命令为ROOT用户,如果不是root请加sudo
    (1) 安装Python3
    Ubuntu16.04本身自带Python2.7。如果不能确定自己的Python版本,在命令行输入python查看即可
    输入Python结果
    如果本身自带Python2.7,使用apt安装Python3。安装完成后系统显示的仍为Python2.7,需要进行切换。
    参考如下,或者使用其它方式安装,需要切换Pyhon为Python3.https://www.cnblogs.com/yjlch1016/p/8641910.html
    (2)第一步是安装GMP库,GMP库是PBC库的基础,如果先安装PBC库会报错。安装GMP库的过程如下
    2.1 ./configure --enable-cxx
    2.2 make
    2.3 make check
    2.4 make install
    (3)安装PBC库
    3.1 ./configure
    3.2 make
    3.3 make check
    3.4 make install
    如果在安装过程中报错
    缺少 flex
    使用命令 apt-get install flex即可
    还可能缺少Bison
    apt-get install bison
    (4)安装Charm
    4.1 解压charm
    tar -zxvf Charm-crypto.xxxxx
    4.2 检测配置
    ./configure
    结果如下
    Charm-crypto的安装与使用_第1张图片
    4.3 make
    在make过程中,如果报错,ssl required
    下载 distribute0.6.42,放到解压后的Charm包里即可,不需要解压。
    4.4 make check
    4.5 make install
    4.6 ldconfig 添加环境变量
  4. 测试
    使用解压Pycharm包,在bin文件夹输入 sh pycharm.sh即可进入pycham图形化界面进行编程。
    注意,需要切换Pycharm的编译环境为system Interpreter,这样在写代码时能
    import charm.xxx

ABE BSW方案代码

from charm.toolbox.pairinggroup import PairingGroup,ZR,G1,G2,GT,pair
from charm.toolbox.secretutil import SecretUtil
from charm.toolbox.ABEnc import ABEnc, Input, Output

# type annotations
pk_t = { 'g':G1, 'g2':G2, 'h':G1, 'f':G1, 'e_gg_alpha':GT }
mk_t = {'beta':ZR, 'g2_alpha':G2 }
sk_t = { 'D':G2, 'Dj':G2, 'Djp':G1, 'S':str }
ct_t = { 'C_tilde':GT, 'C':G1, 'Cy':G1, 'Cyp':G2 }

debug = False
class CPabe_BSW07(ABEnc):
    """
    >>> from charm.toolbox.pairinggroup import PairingGroup,ZR,G1,G2,GT,pair
    >>> group = PairingGroup('SS512')
    >>> cpabe = CPabe_BSW07(group)
    >>> msg = group.random(GT)
    >>> attributes = ['ONE', 'TWO', 'THREE']
    >>> access_policy = '((four or three) and (three or one))'
    >>> (master_public_key, master_key) = cpabe.setup()
    >>> secret_key = cpabe.keygen(master_public_key, master_key, attributes)
    >>> cipher_text = cpabe.encrypt(master_public_key, msg, access_policy)
    >>> decrypted_msg = cpabe.decrypt(master_public_key, secret_key, cipher_text)
    >>> msg == decrypted_msg
    True
    """ 
         
    def __init__(self, groupObj):
        ABEnc.__init__(self)
        global util, group
        util = SecretUtil(groupObj, verbose=False)
        group = groupObj

    @Output(pk_t, mk_t)    
    def setup(self):
        g, gp = group.random(G1), group.random(G2)
        alpha, beta = group.random(ZR), group.random(ZR)
        # initialize pre-processing for generators
        g.initPP(); gp.initPP()
        
        h = g ** beta; f = g ** ~beta
        e_gg_alpha = pair(g, gp ** alpha)
        
        pk = { 'g':g, 'g2':gp, 'h':h, 'f':f, 'e_gg_alpha':e_gg_alpha }
        mk = {'beta':beta, 'g2_alpha':gp ** alpha }
        return (pk, mk)
    
    @Input(pk_t, mk_t, [str])
    @Output(sk_t)
    def keygen(self, pk, mk, S):
        r = group.random() 
        g_r = (pk['g2'] ** r)    
        D = (mk['g2_alpha'] * g_r) ** (1 / mk['beta'])        
        D_j, D_j_pr = {}, {}
        for j in S:
            r_j = group.random()
            D_j[j] = g_r * (group.hash(j, G2) ** r_j)
            D_j_pr[j] = pk['g'] ** r_j
        return { 'D':D, 'Dj':D_j, 'Djp':D_j_pr, 'S':S }
    
    @Input(pk_t, GT, str)
    @Output(ct_t)
    def encrypt(self, pk, M, policy_str): 
        policy = util.createPolicy(policy_str)
        a_list = util.getAttributeList(policy)
        s = group.random(ZR)
        shares = util.calculateSharesDict(s, policy)      

        C = pk['h'] ** s
        C_y, C_y_pr = {}, {}
        for i in shares.keys():
            j = util.strip_index(i)
            C_y[i] = pk['g'] ** shares[i]
            C_y_pr[i] = group.hash(j, G2) ** shares[i] 
        
        return { 'C_tilde':(pk['e_gg_alpha'] ** s) * M,
                 'C':C, 'Cy':C_y, 'Cyp':C_y_pr, 'policy':policy_str, 'attributes':a_list }
    
    @Input(pk_t, sk_t, ct_t)
    @Output(GT)
    def decrypt(self, pk, sk, ct):
        policy = util.createPolicy(ct['policy'])
        pruned_list = util.prune(policy, sk['S'])
        if pruned_list == False:
            return False
        z = util.getCoefficients(policy)
        A = 1 
        for i in pruned_list:
            j = i.getAttributeAndIndex(); k = i.getAttribute()
            A *= ( pair(ct['Cy'][j], sk['Dj'][k]) / pair(sk['Djp'][k], ct['Cyp'][j]) ) ** z[j]
        
        return ct['C_tilde'] / (pair(ct['C'], sk['D']) / A)


def main():   
    groupObj = PairingGroup('SS512')

    cpabe = CPabe_BSW07(groupObj)
    attrs = ['ONE', 'TWO', 'THREE']
    access_policy = '((four or three) and (three or one))'
    if debug:
        print("Attributes =>", attrs); print("Policy =>", access_policy)

    (pk, mk) = cpabe.setup()

    sk = cpabe.keygen(pk, mk, attrs)
    print("sk :=>", sk)

    rand_msg = groupObj.random(GT)
    if debug: print("msg =>", rand_msg)
    ct = cpabe.encrypt(pk, rand_msg, access_policy)
    if debug: print("\n\nCiphertext...\n")
    groupObj.debug(ct)

    rec_msg = cpabe.decrypt(pk, sk, ct)
    if debug: print("\n\nDecrypt...\n")
    if debug: print("Rec msg =>", rec_msg)

    assert rand_msg == rec_msg, "FAILED Decryption: message is incorrect"
    if debug: print("Successful Decryption!!!")

if __name__ == "__main__":
    debug = True
    main()

运行结果如下:

/usr/bin/python3.4 /usr/local/lib/python3.4/dist-packages/Charm_Crypto-0.43-py3.4-linux-x86_64.egg/charm/schemes/abenc/abenc_bsw07.py
Attributes => ['ONE', 'TWO', 'THREE']
Policy => ((four or three) and (three or one))
sk :=> {'S': ['ONE', 'TWO', 'THREE'], 'Djp': {'ONE': [1656857131215580264510078454299990414175887444678436008332324360542735469179258124011404238217955081837786880138276570000997765310267143522376372323309070, 1020194252724993196593649866987385298542229853736046389300946124764947292401317558598634510350270226065183391641191344619648147673544771643861630244765930], 'TWO': [225317086650852053633971364384383011442618726962646456024839071109721775185973951992657058985833938226532065546643912474416823013889167466674625211542802, 5171211596342072937178509212242286325440319641530025777266992858662275312246353637368148221983474614209038517463417566890813420921040676994561999520751694], 'THREE': [3983328040050770385311661300958091739579156540917924891518947554398379535551315171256600054477162049224364382953582613187356721808236819041319638721047478, 7371267254746006440330119766353676015392228094735514424960465434771080152140386620007509569124264385016600460194218599155681078129987768944069589914239490]}, 'Dj': {'ONE': [1962627967356264304383273587974053565229154214703878240673183565251443678722539149280500080933156652747279940708819879106578786491620869965264661670349793, 738193107865147017138645734354784104728498756789693536386607463562358238023526996038934101133403879620520839670828705709045353274354995694025847243868564], 'TWO': [1733449180497253489761536512695142611941443126530136551522811723599825036941159083481783331690337863390556617893052369395870679686857873242817006664546558, 4558192993466863776692961804292316005634595519974374968695047717435431525272260433088523824208861644574753961533266595792172253018276618231053179769214467], 'THREE': [4409166116875522861349761633571530284175930541585875153977922931849362909800042310349838677159816941927756692334132282340748816972707154754404328168903324, 2144808269640752698084538531728733988657901478917609226246584412293784079675261515400344586913995169491739540527739968312682161005255677193767451989055897]}, 'D': [1635759058468099881703061645255879266664659870999373105240059945250388805865040227776529160859856210338558920903610269519132715827453619802041055435170321, 1091949721784882674875614682399727036457780605367860600157506109557720430784451962510054242801908289120338069045205395273838892330783136286666760942800974]}
msg => [4742011490917596458046505841387905176015968001608409912648099524254019771579532713401953289693580600713620411755823914152995309168774382204143043451006805, 956341419444095659848657352585671568036617096998621143045273563005069499664753599491731504482690115733852065040073109064757188053144907431510452742805115]


Ciphertext...



Decrypt...

Rec msg => [4742011490917596458046505841387905176015968001608409912648099524254019771579532713401953289693580600713620411755823914152995309168774382204143043451006805, 956341419444095659848657352585671568036617096998621143045273563005069499664753599491731504482690115733852065040073109064757188053144907431510452742805115]
Successful Decryption!!!

Process finished with exit code 0

你可能感兴趣的:(ABE)