Exemple #1
0
    def decrypt(self, master_public_key, sk, cipher_matrix, vertices):
        '''
        Decryption requires master_public_key, user secret key, and cipher
        '''
        group = PairingGroup('SS512')
        cpabe = CPabe_BSW07(group)
        hyb_abe = HybridABEnc(cpabe, group)

        N = len(vertices)

        resMat = [None] * N
        for i in range(0, N):
            resMat[i] = [None] * N
            for j in range(0, N):
                #convert to lower case
                s = vertices[i].lower()
                s2 = vertices[j].lower()

                cipher = cipher_matrix.get_cell_by_symbol(s, s2)
                resMat[i][j] = hyb_abe.decrypt(master_public_key, sk, cipher)
                if resMat[i][j] == False:
                    return False

        result = AdjMatrixDiGraph(mat=resMat)
        return SymbolDiGraphMat(vertices, G=result)
Exemple #2
0
 def decrypt(self, master_public_key, sk, cipher_matrix, vertices):
     '''
     Decryption requires master_public_key, user secret key, and cipher
     '''
     group = PairingGroup('SS512')
     cpabe = CPabe_BSW07(group)
     hyb_abe = HybridABEnc(cpabe, group)
     
     N = len(vertices)
     
     resMat = [None]*N;
     for i in range(0,N):
         resMat[i] = [None]*N
         for j in range(0,N):
             #convert to lower case
             s = vertices[i].lower()
             s2 = vertices[j].lower()
         
             cipher = cipher_matrix.get_cell_by_symbol(s, s2)
             resMat[i][j] = hyb_abe.decrypt(master_public_key, sk, cipher)
             if resMat[i][j]==False:
                 return False
     
     result = AdjMatrixDiGraph(mat=resMat)
     return SymbolDiGraphMat(vertices, G=result)
Exemple #3
0
    def __init__(self, symbol_graph):
        '''
        Constructor
        '''
        # initialize CPABE object
        self._group = PairingGroup('SS512')
        self._cpabe = CPabe_BSW07(self._group)
        self._hyb_abe = HybridABEnc(self._cpabe, self._group)
        #access_policy = '(ar and bc)'
        #message = "hello world this is an important message."
        #(pk, mk) = self._hyb_abe.setup()
        #sk = self._hyb_abe.keygen(pk, mk, ['AR', 'BC'])
        #ct = self._hyb_abe.encrypt(pk, message, access_policy)
        #try:
        #    result = self._hyb_abe.decrypt(pk, sk, ct)
        #    print result
        #except Exception:
        #    pass

        # attributes should be vertices
        # since its diDraph, the query of two vertices sequence matters
        # row and col symbol is interpreted differently
        self._symbol_graph = symbol_graph
        symbols = self._symbol_graph.get_keys()
        for i in symbols:
            # r means row attributes
            self._attributes.append(symbols[i] + 'r')
            # c means column attributes
            self._attributes.append(symbols[i] + 'c')
Exemple #4
0
def test_charm_crypto():
    # instantiate a bilinear pairing map
    pairing_group = PairingGroup('MNT224')

    cpabe = CPabe_BSW07(pairing_group)
    hyb_abe = HybridABEnc(cpabe, pairing_group)
    # run the set up
    (pk, msk) = hyb_abe.setup()  # Public Key and Master SECRET Key

    # generate a key
    attr_list = ['U-11890454', 'D-46', 'D-46-GUEST']
    key = hyb_abe.keygen(pk, msk, attr_list)

    serialized_pk = serialize_charm_object(pk, pairing_group)
    pk = deserialize_charm_object(serialized_pk, pairing_group)

    serialized_key = serialize_charm_object(key, pairing_group)
    key = deserialize_charm_object(serialized_key, pairing_group)

    # choose a random message
    msg = "Hello World"

    # generate a ciphertext
    policy_str = '(u-11890454 OR d-46 OR d-46-GUEST)'  # evaluates to "((U-11890454 or D-46) or D-46-GUEST)" - see upper chars
    ctxt = hyb_abe.encrypt(pk, msg, policy_str)

    policy_str = '(u-1 AND d-46 AND d-46-GUEST)'  # Re-encrypted data with new policy
    ctxt2 = hyb_abe.encrypt(pk, msg, policy_str)

    # decryption
    rec_msg = hyb_abe.decrypt(pk, key, ctxt).decode("utf-8")
    with pytest.raises(Exception):
        hyb_abe.decrypt(pk, key, ctxt2)
    assert rec_msg == msg, "Failed."  # "First successfully decrypted, second not."
Exemple #5
0
 def testHybridABEnc(self):
     groupObj = PairingGroup('SS512')
     cpabe = CPabe_BSW07(groupObj)
     hyb_abe = HybridABEnc(cpabe, groupObj)
     access_policy = '((four or three) and (two or one))'
     message = b"hello world this is an important message."
     (pk, mk) = hyb_abe.setup()
     if debug: print("pk => ", pk)
     if debug: print("mk => ", mk)
     sk = hyb_abe.keygen(pk, mk, ['ONE', 'TWO', 'THREE'])
     if debug: print("sk => ", sk)
     ct = hyb_abe.encrypt(pk, message, access_policy)
     mdec = hyb_abe.decrypt(pk, sk, ct)
     assert mdec == message, "Failed Decryption!!!"
     if debug: print("Successful Decryption!!!")
Exemple #6
0
 def __init__(self, symbol_graph):
     '''
     Constructor
     '''
     # initialize CPABE object
     self._group = PairingGroup('SS512')
     self._cpabe = CPabe_BSW07(self._group)
     self._hyb_abe = HybridABEnc(self._cpabe, self._group)
     #access_policy = '(ar and bc)'
     #message = "hello world this is an important message."
     #(pk, mk) = self._hyb_abe.setup()
     #sk = self._hyb_abe.keygen(pk, mk, ['AR', 'BC'])
     #ct = self._hyb_abe.encrypt(pk, message, access_policy)
     #try:
     #    result = self._hyb_abe.decrypt(pk, sk, ct)
     #    print result
     #except Exception:
     #    pass
     
     # attributes should be vertices
     # since its diDraph, the query of two vertices sequence matters
     # row and col symbol is interpreted differently
     self._symbol_graph = symbol_graph
     symbols = self._symbol_graph.get_keys()
     for i in symbols:
         # r means row attributes
         self._attributes.append(symbols[i]+'r')
         # c means column attributes
         self._attributes.append(symbols[i]+'c')
Exemple #7
0
    def __init__(self, group = "SS512"):
        self._group = PairingGroup(group)
        self._cpabe = CPabe09(self._group)
        self._hybrid_abe = HybridABEnc(self._cpabe, self._group)

        # TODO: Master keys should be generated once and stored securely 
        #       somewhere else.
        self._master_secret, self._master_public = self._cpabe.setup()
Exemple #8
0
    def decrypt_query(self, master_public_key, sk, cipher_matrix, queries):
        '''
        Decryption requires master_public_key, user secret key, and cipher
        '''
        group = PairingGroup('SS512')
        cpabe = CPabe_BSW07(group)
        hyb_abe = HybridABEnc(cpabe, group)

        msg = ''
        for query in queries:
            #convert to lower case
            s1 = query[0].lower()
            s2 = query[1].lower()

            cipher = cipher_matrix.get_cell_by_symbol(s1, s2)
            msg += hyb_abe.decrypt(master_public_key, sk, cipher) + " "

        return msg
Exemple #9
0
 def decrypt_query(self, master_public_key, sk, cipher_matrix, queries):
     '''
     Decryption requires master_public_key, user secret key, and cipher
     '''
     group = PairingGroup('SS512')
     cpabe = CPabe_BSW07(group)
     hyb_abe = HybridABEnc(cpabe, group)
     
     msg = ''
     for query in queries:
         #convert to lower case
         s1 = query[0].lower()
         s2 = query[1].lower()
         
         cipher = cipher_matrix.get_cell_by_symbol(s1, s2)
         msg += hyb_abe.decrypt(master_public_key, sk, cipher) + " "
     
     return msg
 def __init__(self, curve):
     global DEBUG
     try:                               
         self.__debug = DEBUG
     except:
         pass
     
     self.curve = curve
     self.groupObj = PairingGroup(self.curve)
     cpabe = CPabe_BSW07(self.groupObj)
     self.cpabe = HybridABEnc(cpabe, self.groupObj)
def main():
    groupObj = PairingGroup('SS512')
    cpabe = CPabe_BSW07(groupObj)
    abe = HybridABEnc(cpabe, groupObj)



    f1 = open("private/pk_bytes", "rb")
    f2 = open("private/mk_bytes", "rb")

    pk = f1.read()
    mk = f2.read()

    orig_pk = bytesToObject(pk, groupObj)
    orig_mk = bytesToObject(mk, groupObj)


    print(orig_pk)
    
    
    # (pk,mk) = create_pk_mk_abe(abe)
  
    
    attrs1 = ['CANHTUAN','DUY','MANH']
    attrs2 = ['CANHTUAN','DUY']
    msg = "canhtuan".encode('utf-8')
    # policy = create_policy_abe(attrs2)
    policy = '(CANHTUAN and DUY and MANH)'
    # print(policy)
    


    sk2 = create_scret_key(abe,orig_pk,orig_mk,attrs1)
    ct = encrypt_abe(abe,orig_pk,"tuan".encode('utf-8'), policy)
    # print(ct)
    ct =b'eJydV9tuFEcQ/ZXVPiXSSpme6Us1Eg+WgRjFxomAkIuj1d5srNjE8S5OiOV/z1TVOTMbnmIeMDs91XU9darmfroK0yeT++nhfHd5td7Y7/l8dbXYbufz/mm6/LTbbKezSX96t7j6uLHTX1OYTZLMJqFpZ5PazCax9gf9Yen6/0v/om31bZ5NpH+qvaiopL5p+oekb0PUP50eJZcxdaFRXb3OrNJBXLFeN6Up+YGJSYfTnNx26Q9jfy9naCsqGuClag1NLxb1Xqh+KgLPQoCYve1PSq+lVn3ofxT6pq5EgdumTo2Uht72YQkdDAGBqN4s8NaC0cg1mCL+thRoM9OhbXBblWs46mLShCZktkR6J27RUqixima2Ka5TCxApZvJNcC0pU5MqaPyfvbXQihpqA293cMqtRLzTXGnEFpt6r0pjYTjZ4RBZ5YSM6lv3RTxCTWi0IsCyFBgtzE2gYbWpPmnBNe5EU+aRZzkAKZn5GWKwgJNb1SyoBk2l1a2DB+5sSxD2l3P47aFvg8P/2yLWEeKli1RiENPqVGTccqw4FTQOPanMhQXK8hHeoSE6rMxWdNPttZXhZeu49ZolgNKhqkjOLqx41EMtgqYvwxGtQUE9tFqaxAgF+ttAlNiCqHVlk6lmNW43hLXOHt8YeEvYN7xY6xi2/jMoNMB1ROY0DeZ3cqXqs5ZSmYC1+uTcdvDq6M3bg1ePrZylVtUa3Sj0S/cZyJ1mEplFKJcc8t5B9ioiU1offSUDA1X0XkHRJIMCtBIabaG43nUWEm8CYSO0gHHHejTwSwCHAiIZ/LTcgk30utUFudezSkGjauNlJUGi2Vo+A8MRxctoamu8ocaZ+A0uEYmRlkRjkEv/Kd2ztz8/vlwgaU9gO1jo3IKCx7MX4XMAjH1OAcsJlGkkg0idVIHKPNB6oi1h40FeTSV4QrIaRoIhqvh1Q0DhWLCcVTBT3GutYVaMQwwTU614/jFF1IzRL2NzaigYCsaAAeQIRm0QZAMYYAiFcXQMGS1hTI6z4liyk77NHk2OIJaIKSJpn/0YbBjmWseCCWuZ3ecyEki7Pzwrku2jLiAC2Yt2aOMAJHI8JULbiNt0t4CBs1nDRSSPTBoJf8weafbGZ4QzNmYD23xcgYSFHP8kMIOCJmPHSoCGcJsqmMqCgvhiwmUpCk/JXhnjzDny5otIUh1LWJwUswnrkqXesB6YZWHTVQYEJuCmpGgqwjIQa3Wc+ZV1Jfc69rAaZuyLBeNaANQEShHseIWDc6hqYbIiGNHExCWM6riOZSwMvqWSAcCzWCjcqQLe0WISFeZVhwat+zYzRzIw5OlLgKNaq4RC5X74ZTTJgmExSG4mAzLKIyns7c1mPxGe5CzPWtjrQiHFSt2bPYkiXj8UyjfQhhRaMGITeDvhS6GgnuPaH2bjipG5DHgDYhePXPoqdgYXI8tHdIlgF01Yamw/TvgE4FRsh5syTizjw8JPh5ZfFZ6dRGAxcZ4n0tFns+0xRDlUzR3CjmM4wvZfuBkI15AQR3Bp/tLA6aokcyhkEtDQuoHLQoRKUBPZLmJdKfvdWYTzfWgmkOcwG20VgmnPLncVKJKhl+yDpzolDKTlGOMctg0jsksCSThwSSJLdvgi5Ori61wlH8e9zySDRDNMkI7Ce3XTwt38cXW50p1yut3dPvmKlDlZfFhP+k60/7W4X2sZF7vd7eXyoxa1r6PdGDh25hq0e/HTMGHoWLWGjcXVBQ0dnRwczl8fHbQqfL0dzu/PpgfH3571j73XZ9OT02fP9aHVh5c/6s+zaXj952U5X9+9OL+9fv8yfvfh8Pt//rp4+vRsqlKHlzfvN7dvNn/vXLpcv/jh9OLu3Tf1+KdfTt8dL3/f7p6b9IPaXl9ebLY7ml+vz3PThFo3a1mcr2RRZJmkxLJOZZVWZbWspe3Cqp7Lsqs1rmPMZbFq16GGssx5+vDwL/EqTB0='
    

    giaima = decrypt_abe(abe,orig_pk, sk2, ct)
    print(giaima)

# main()
Exemple #12
0
 def testHybridABEnc(self):
     groupObj = PairingGroup('SS512')
     cpabe = CPabe_BSW07(groupObj)
     hyb_abe = HybridABEnc(cpabe, groupObj)
     access_policy = '((four or three) and (two or one))'
     message = b"hello world this is an important message."
     (pk, mk) = hyb_abe.setup()
     if debug: print("pk => ", pk)
     if debug: print("mk => ", mk)
     sk = hyb_abe.keygen(pk, mk, ['ONE', 'TWO', 'THREE'])
     if debug: print("sk => ", sk)
     ct = hyb_abe.encrypt(pk, message, access_policy)
     mdec = hyb_abe.decrypt(pk, sk, ct)
     assert mdec == message, "Failed Decryption!!!"
     if debug: print("Successful Decryption!!!")
Exemple #13
0
class CPABESymbolDiGraph:

    # the symbol graph
    _symbol_graph = None
    # operating group
    _group = None
    # Cipertext-Policy AtSymtribute-Based Encryption object
    _cpabe = None
    # hybrid
    _hyb_abe = None

    _master_public_key = 0
    _master_key = 0
    _attributes = []
    _secret_key = 0

    # Encrypted matrix
    #_enc_symbol_matix = {}

    def __init__(self, symbol_graph):
        '''
        Constructor
        '''
        # initialize CPABE object
        self._group = PairingGroup('SS512')
        self._cpabe = CPabe_BSW07(self._group)
        self._hyb_abe = HybridABEnc(self._cpabe, self._group)
        #access_policy = '(ar and bc)'
        #message = "hello world this is an important message."
        #(pk, mk) = self._hyb_abe.setup()
        #sk = self._hyb_abe.keygen(pk, mk, ['AR', 'BC'])
        #ct = self._hyb_abe.encrypt(pk, message, access_policy)
        #try:
        #    result = self._hyb_abe.decrypt(pk, sk, ct)
        #    print result
        #except Exception:
        #    pass

        # attributes should be vertices
        # since its diDraph, the query of two vertices sequence matters
        # row and col symbol is interpreted differently
        self._symbol_graph = symbol_graph
        symbols = self._symbol_graph.get_keys()
        for i in symbols:
            # r means row attributes
            self._attributes.append(symbols[i] + 'r')
            # c means column attributes
            self._attributes.append(symbols[i] + 'c')

    def setup(self):
        # ABE setup phase
        (self._master_public_key, self._master_key) = self._hyb_abe.setup()
        return self._master_public_key, self._master_key

    def encrypt(self):
        '''
        Encrypt whole graph with each cell in the matrix using corresponding symbols
        '''
        assert self._master_public_key, "Please do setup first."

        size = self._symbol_graph.get_V()
        enc_symbol_matix = SymbolMatrix(size, self._symbol_graph.get_st())
        for i in range(0, size):
            for j in range(0, size):
                msg = str(self._symbol_graph.get_edge_by_index(i, j))
                cell_access_policy = '(%s AND %s)' % (
                    (self._symbol_graph.name(i) + 'r'),
                    (self._symbol_graph.name(j) + 'c'))
                cipher = self._hyb_abe.encrypt(self._master_public_key, msg,
                                               cell_access_policy)
                enc_symbol_matix.set_matrix(cipher, i, j)
        return enc_symbol_matix

    @classmethod
    def decrypt_query(self, master_public_key, sk, cipher_matrix, queries):
        '''
        Decryption requires master_public_key, user secret key, and cipher
        '''
        group = PairingGroup('SS512')
        cpabe = CPabe_BSW07(group)
        hyb_abe = HybridABEnc(cpabe, group)

        msg = ''
        for query in queries:
            #convert to lower case
            s1 = query[0].lower()
            s2 = query[1].lower()

            cipher = cipher_matrix.get_cell_by_symbol(s1, s2)
            msg += hyb_abe.decrypt(master_public_key, sk, cipher) + " "

        return msg

    @classmethod
    def decrypt(self, master_public_key, sk, cipher_matrix, vertices):
        '''
        Decryption requires master_public_key, user secret key, and cipher
        '''
        group = PairingGroup('SS512')
        cpabe = CPabe_BSW07(group)
        hyb_abe = HybridABEnc(cpabe, group)

        N = len(vertices)

        resMat = [None] * N
        for i in range(0, N):
            resMat[i] = [None] * N
            for j in range(0, N):
                #convert to lower case
                s = vertices[i].lower()
                s2 = vertices[j].lower()

                cipher = cipher_matrix.get_cell_by_symbol(s, s2)
                resMat[i][j] = hyb_abe.decrypt(master_public_key, sk, cipher)
                if resMat[i][j] == False:
                    return False

        result = AdjMatrixDiGraph(mat=resMat)
        return SymbolDiGraphMat(vertices, G=result)

    def key_generation(self, attributes):
        '''
        Generate individual's secret key using the given attributes
        '''
        assert (self._master_public_key
                and self._master_key), "Please do setup first."

        # convert strings in attributes to uppercase
        for elem in attributes:
            elem = elem.upper()

        return self._hyb_abe.keygen(self._master_public_key, self._master_key,
                                    attributes)

    @classmethod
    def subgraph(self, cipher_matrix, vertices):
        size = len(vertices)
        enc_symbol_matix = SymbolMatrix(size, vertices=vertices)
        for i in range(0, size):
            for j in range(0, size):
                cipher = cipher_matrix.get_cell_by_symbol(
                    vertices[i], vertices[j])
                enc_symbol_matix.set_matrix(cipher, i, j)

        return enc_symbol_matix

    def out_to_file(self, filename):
        pass

    def read_from_file(self, filename):

        pass
def initABE():
    groupObj = PairingGroup('SS512')
    cpabe = CPabe_BSW07(groupObj)
    abe = HybridABEnc(cpabe, groupObj)
    return abe
Exemple #15
0
from config import *

import requests

from charm.toolbox.pairinggroup import PairingGroup
from charm.schemes.abenc.abenc_bsw07 import CPabe_BSW07
from charm.adapters.abenc_adapt_hybrid import HybridABEnc

from charm.core.engine.util import objectToBytes, bytesToObject

policy_length = 16
key_size = 8

groupObj = PairingGroup('SS512')
cpabe = CPabe_BSW07(groupObj)
hybrid_abe = HybridABEnc(cpabe, groupObj)

master_key_file_name = "master_key.json"
def init_abe():
    groupObj = PairingGroup('SS512')
    cpabe = CPabe_BSW07(groupObj)
    abe = HybridABEnc(cpabe, groupObj)
    print(abe)
    return (abe)
Exemple #17
0
from charm.toolbox.pairinggroup import PairingGroup
from charm.schemes.abenc.abenc_bsw07 import CPabe_BSW07
from charm.adapters.abenc_adapt_hybrid import HybridABEnc
import pickle

if __name__ == "__main__":
    groupObj = PairingGroup('SS512')
    cpabe = CPabe_BSW07(groupObj)
    hyb_abe = HybridABEnc(cpabe, groupObj)
    (pk, mk) = hyb_abe.setup()
    access_policy = '((four or three) and (two or one))'
    sk = hyb_abe.keygen(pk, mk, ['ONE', 'TWO', 'THREE'])
    print(sk)
    plaintext = "Bounty Name: EMR Functional Testing"

    ciphertext = hyb_abe.encrypt(pk, plaintext, access_policy)
    print(ciphertext)
    ciphertext["c1"]["C"] = groupObj.serialize(ciphertext["c1"]["C"])
    for key in ciphertext["c1"]["Cy"]:
        ciphertext["c1"]["Cy"][key] = groupObj.serialize(
            ciphertext["c1"]["Cy"][key])
    ciphertext["c1"]["C_tilde"] = groupObj.serialize(
        ciphertext["c1"]["C_tilde"])
    for key in ciphertext["c1"]["Cyp"]:
        ciphertext["c1"]["Cyp"][key] = groupObj.serialize(
            ciphertext["c1"]["Cyp"][key])

    ciphertext2 = ciphertext
    ciphertext2["c1"]["C"] = groupObj.deserialize(ciphertext["c1"]["C"])
    for key in ciphertext2["c1"]["Cy"]:
        ciphertext2["c1"]["Cy"][key] = groupObj.deserialize(
Exemple #18
0
from charm.toolbox.pairinggroup import PairingGroup
from charm.schemes.abenc.abenc_bsw07 import CPabe_BSW07
from charm.adapters.abenc_adapt_hybrid import HybridABEnc

debug = True

groupObj = PairingGroup('SS512')
cpabe = CPabe_BSW07(groupObj)
hyb_abe = HybridABEnc(cpabe, groupObj)
access_policy = '((four or three) and (two or one))'
message = b"hello world this is an important message."
(pk, mk) = hyb_abe.setup()
if debug: print("pk => ", pk)
if debug: print("mk => ", mk)
sk = hyb_abe.keygen(pk, mk, ['ONE', 'TWO', 'THREE'])
if debug: print("sk => ", sk)
ct = hyb_abe.encrypt(pk, message, access_policy)
mdec = hyb_abe.decrypt(pk, sk, ct)
assert mdec == message, "Failed Decryption!!!"
if debug:
    print("Successful Decryption!!!")
Exemple #19
0
from charm.toolbox.pairinggroup import PairingGroup
from charm.schemes.abenc.abenc_bsw07 import CPabe_BSW07
from charm.adapters.abenc_adapt_hybrid import HybridABEnc
import json
import pickle

if __name__ == "__main__":
    groupObj = PairingGroup('MNT224')
    cpabe = CPabe_BSW07(groupObj)
    hyb_abe = HybridABEnc(cpabe, groupObj)
    (pk, mk) = hyb_abe.setup()
    print("*********************************************")
    for key in pk.keys():
        print(key + ": " + str(pk.get(key)))
    print("*********************************************")

    print("*********************************************")
    access_policy = '((FOUR or three) and (two or one))'
    plaintext = "Bounty Name: EMR Functional Testing"
    attr_list = ['ONE', 'FOUR']
    ciphertext = hyb_abe.encrypt(pk, plaintext, access_policy)
    sk = hyb_abe.keygen(pk, mk, attr_list)
    try:
        dt = hyb_abe.decrypt(pk, sk, ciphertext).decode('utf-8')
    except:
        print("failed to decrypt")
    else:
        if (dt == plaintext):
            print(dt)
from charm.core.engine.util import objectToBytes,bytesToObject

bla = {'u1': [3298552771336315058475964122560955936669014483448543089394, 2492329322382145273721764477046581872194066564018674282002], 'u2': [4386798087328702967628570037820998863857227354892500890225, 2643854894262774539282328524705550500360174676349510382374], 'v': [513927001364049699498717302480791263811303229590715045334, 4123403705144654743269887658478304341858296884697172214022], 'e': [3849146896870141713909280592696755725700337296330388339822, 3315575432157417383040094888351986415172274265058848014909]}

print(bla, "\n\n\n")

print(json.dumps(bla), "\n\n\n", bla['u1'], "\n\n\n")

print(bla['u1'])
#exit()

################
groupObj = PairingGroup('SS512')

cpabe = CPabe_BSW07(groupObj)
hyb_abe = HybridABEnc(cpabe, groupObj)

(pk, mk) = hyb_abe.setup()
print ("-----", pk['f'], "-----")
serPK = objectToBytes(pk, groupObj)
groupObj2 = PairingGroup('SS512')
unserPK = bytesToObject(serPK, groupObj2)
print(pk, "\n\n\n", unserPK)
exit()

class MyObj(object):
    def __init__(self, s):
        self.s = s
    def __repr__(self):
        return '<MyObj(%s)>' % self.s
class WrapperCpabeBSW07(Wrapper):
    '''
    wrapper implementation class to call cp-ABE BSW07 with object-to-bytes keys
    '''
    curve = None 
    
    __debug = 4
    """int: debug"""
    
    groupObj = None
    """PairingGroup: groupObj"""
    cpabe = None
    """HybridABEnc: cpabe"""
    
    def __init__(self, curve):
        global DEBUG
        try:                               
            self.__debug = DEBUG
        except:
            pass
        
        self.curve = curve
        self.groupObj = PairingGroup(self.curve)
        cpabe = CPabe_BSW07(self.groupObj)
        self.cpabe = HybridABEnc(cpabe, self.groupObj)
            
    #@list(str, str)            
    def setup(self):
        (PK, MK) = self.cpabe.setup()
        
        serPK = objectToBytes(PK, self.groupObj)
        serMK = objectToBytes(MK, self.groupObj)
        
        return (serPK, serMK)

#    @Input(pk_t, sk_t, ct_t)
#    @Output(serPK, serMK)            
    def keygen(self, serPK, serMK, attributeList):
        if attributeList is None \
        or not(isinstance( attributeList, list)):
            raise Exception("attributeList must be set and a list!")

        PK = bytesToObject(serPK, self.groupObj)
        MK = bytesToObject(serMK, self.groupObj)
        
        SK = self.cpabe.keygen(PK, MK, attributeList)

        serSK = objectToBytes(SK, self.groupObj)
        
        return serSK

    def encrypt(self, serPK, M, accessStructure):
        PK = bytesToObject(serPK, self.groupObj)
        
        return self.cpabe.encrypt(PK, M, accessStructure)
        

    def decrypt(self, serPK, serSK, CT):
        PK = bytesToObject(serPK, self.groupObj)
        SK = bytesToObject(serSK, self.groupObj) 
        
        return self.cpabe.decrypt(PK, SK, CT)
    
    def getDEK(self):
        """selects a new DEK from G1"""        
        return sha1(self.groupObj.random(G1))
    
    def refresh(self, serPK, serMK):
        """
        return tupel: (serPK', serMK', conversionFactor)
        """
        PK = bytesToObject(serPK, self.groupObj)
        MK = bytesToObject(serMK, self.groupObj)
        
        newAlpha = self.groupObj.random(ZR)
        PK['e_gg_alpha'] = pair(PK['g'], PK['g2'] ** newAlpha)
        g2_newAlpha = PK['g2'] ** newAlpha
        conversionFactor = ((g2_newAlpha / MK['g2_alpha']) ** ~(MK['beta'])) 
        MK['g2_alpha'] =g2_newAlpha 
        
        newSerPK = objectToBytes(PK, self.groupObj)
        newSerMK = objectToBytes(MK, self.groupObj)
        
        return (newSerPK, newSerMK, conversionFactor)

    def refreshSK(self, serSK, conversionFactor):
        '''
        refreshes the SK by the conversion_factor
        return newSerSK
        '''
        #{ 'D':D, 'Dj':D_j, 'Djp':D_j_pr, 'S':S }
        
        SK = bytesToObject(serSK, self.groupObj) 
        SK['D'] = SK['D'] *  conversionFactor
        
        return objectToBytes(SK, self.groupObj)
Exemple #22
0
import datetime
import traceback

from charm.core.engine.util import objectToBytes,bytesToObject

from charm.toolbox.pairinggroup import PairingGroup
from charm.schemes.abenc.abenc_bsw07 import CPabe_BSW07
from charm.adapters.abenc_adapt_hybrid import HybridABEnc 

debug = True

groupObj = PairingGroup('SS512')
cpabe = CPabe_BSW07(groupObj)
hybrid_abe = HybridABEnc(cpabe, groupObj)

access_policy = '(SYSADMIN and SECURITYTEAM) or (BUSINESSSTAFF and ((executivelevel7 and auditgroup) or (executivelevel7 and strategyteam) or (auditgroup and strategyteam)))'
data = "hello world this is an important message. encounter in string format"
data = bytes(data, 'utf-8')
(pk, mk) = hybrid_abe.setup()
if debug: print("pk => ", str(objectToBytes(pk,groupObj), 'utf-8'))
if debug: print("mk => ", str(objectToBytes(mk,groupObj), 'utf-8'))

# print(type(data), data)
# print(access_policy)
ciphertext = hybrid_abe.encrypt(pk, data, access_policy)
ciphertext = objectToBytes(ciphertext,groupObj)
print("ciphertext: ", ciphertext)

sara_attributes = ['SYSADMIN', 'ITDEPARTMENT']
kevin_attributes = ['BUSINESSSTAFF', 'STRATEGYTEAM', 'EXECUTIVELEVEL7']
#from pprint import pprint as pp
import json

from charm.adapters.abenc_adapt_hybrid import HybridABEnc as HybridABEnc
from charm.schemes.abenc.abenc_bsw07 import CPabe_BSW07
from charm.toolbox.pairinggroup import PairingGroup #,GT

#from charm.schemes.pkenc.pkenc_cs98 import CS98
#from charm.toolbox.eccurve import prime192v1
#from charm.toolbox.ecgroup import ECGroup


groupObj = PairingGroup('SS512')

cpabe = CPabe_BSW07(groupObj)
hyb_abe = HybridABEnc(cpabe, groupObj)
access_policy = '((four or three) and (two or one))'
message = b"this is my text"

# G1, G2 bilinear groups, e_gg_alpha: generator
#pk = { 'g':g, 'g2':gp, 'h':h, 'f':f, 'e_gg_alpha':e_gg_alpha }
#mk = {'beta':beta, 'g2_alpha':gp ** alpha }
(pk, mk) = hyb_abe.setup()

print ("g: ", type(pk['g']), 'g in real', pk['g'], "\n\n")

#print(json.dumps(pk['g'], cls='pairingElement'))
print(json.dumps({'g' : 1}, cls='pairingElement'))

exit()
#print("pk => ",  pk, "\n")
Exemple #24
0
def create_cp_abe():
    pairing_group = create_pairing_group()
    cpabe = CPabe_BSW07(pairing_group)
    return HybridABEnc(cpabe, pairing_group)
Exemple #25
0
class CPABESymbolDiGraph:
    
    # the symbol graph
    _symbol_graph = None
    # operating group
    _group = None
    # Cipertext-Policy AtSymtribute-Based Encryption object
    _cpabe = None
    # hybrid
    _hyb_abe = None
    
    _master_public_key = 0
    _master_key = 0
    _attributes = []
    _secret_key = 0
    
    # Encrypted matrix
    #_enc_symbol_matix = {}
    
    def __init__(self, symbol_graph):
        '''
        Constructor
        '''
        # initialize CPABE object
        self._group = PairingGroup('SS512')
        self._cpabe = CPabe_BSW07(self._group)
        self._hyb_abe = HybridABEnc(self._cpabe, self._group)
        #access_policy = '(ar and bc)'
        #message = "hello world this is an important message."
        #(pk, mk) = self._hyb_abe.setup()
        #sk = self._hyb_abe.keygen(pk, mk, ['AR', 'BC'])
        #ct = self._hyb_abe.encrypt(pk, message, access_policy)
        #try:
        #    result = self._hyb_abe.decrypt(pk, sk, ct)
        #    print result
        #except Exception:
        #    pass
        
        # attributes should be vertices
        # since its diDraph, the query of two vertices sequence matters
        # row and col symbol is interpreted differently
        self._symbol_graph = symbol_graph
        symbols = self._symbol_graph.get_keys()
        for i in symbols:
            # r means row attributes
            self._attributes.append(symbols[i]+'r')
            # c means column attributes
            self._attributes.append(symbols[i]+'c')
        
        
    def setup(self):
        # ABE setup phase
        (self._master_public_key, self._master_key) = self._hyb_abe.setup()
        return self._master_public_key, self._master_key
        
    def encrypt(self):
        '''
        Encrypt whole graph with each cell in the matrix using corresponding symbols
        '''
        assert self._master_public_key, "Please do setup first."
            
        size = self._symbol_graph.get_V();
        enc_symbol_matix = SymbolMatrix(size, self._symbol_graph.get_st())
        for i in range(0, size):
            for j in range(0, size):
                msg = str(self._symbol_graph.get_edge_by_index(i,j))
                cell_access_policy = '(%s AND %s)'%((self._symbol_graph.name(i)+'r'),
                                                    (self._symbol_graph.name(j)+'c'))
                cipher = self._hyb_abe.encrypt(self._master_public_key, 
                                               msg, 
                                               cell_access_policy)
                enc_symbol_matix.set_matrix(cipher, i, j)
        return enc_symbol_matix

    @classmethod
    def decrypt_query(self, master_public_key, sk, cipher_matrix, queries):
        '''
        Decryption requires master_public_key, user secret key, and cipher
        '''
        group = PairingGroup('SS512')
        cpabe = CPabe_BSW07(group)
        hyb_abe = HybridABEnc(cpabe, group)
        
        msg = ''
        for query in queries:
            #convert to lower case
            s1 = query[0].lower()
            s2 = query[1].lower()
            
            cipher = cipher_matrix.get_cell_by_symbol(s1, s2)
            msg += hyb_abe.decrypt(master_public_key, sk, cipher) + " "
        
        return msg

    
    @classmethod
    def decrypt(self, master_public_key, sk, cipher_matrix, vertices):
        '''
        Decryption requires master_public_key, user secret key, and cipher
        '''
        group = PairingGroup('SS512')
        cpabe = CPabe_BSW07(group)
        hyb_abe = HybridABEnc(cpabe, group)
        
        N = len(vertices)
        
        resMat = [None]*N;
        for i in range(0,N):
            resMat[i] = [None]*N
            for j in range(0,N):
                #convert to lower case
                s = vertices[i].lower()
                s2 = vertices[j].lower()
            
                cipher = cipher_matrix.get_cell_by_symbol(s, s2)
                resMat[i][j] = hyb_abe.decrypt(master_public_key, sk, cipher)
                if resMat[i][j]==False:
                    return False
        
        result = AdjMatrixDiGraph(mat=resMat)
        return SymbolDiGraphMat(vertices, G=result)
    
    
    def key_generation(self, attributes):
        '''
        Generate individual's secret key using the given attributes
        '''
        assert (self._master_public_key and self._master_key), "Please do setup first."
        
        # convert strings in attributes to uppercase
        for elem in attributes:
            elem = elem.upper()
        
        return self._hyb_abe.keygen(self._master_public_key, 
                                  self._master_key,
                                  attributes)
        
    @classmethod
    def subgraph(self, cipher_matrix,vertices):
        size = len(vertices)
        enc_symbol_matix = SymbolMatrix(size, vertices=vertices)
        for i in range(0, size):
            for j in range(0, size):
                cipher = cipher_matrix.get_cell_by_symbol(vertices[i],vertices[j])
                enc_symbol_matix.set_matrix(cipher, i, j)
        
        return enc_symbol_matix
    
    
    def out_to_file(self, filename):
        pass
    
    def read_from_file(self, filename):
        
        pass