Пример #1
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."
Пример #2
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!!!")
Пример #3
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!!!")
Пример #4
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
Пример #5
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(
Пример #6
0
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")
#print ("\n\n",pk["g"], "\n", pk["g2"], "\n",pk["h"], "\n",pk["f"], "\n",pk["e_gg_alpha"], "\n" )
#print ("\n\n---\n")
print("mk => ", mk, "\n")

sk = hyb_abe.keygen(pk, mk, ['ONE', 'TWO', 'THREE'])
#print("sk => ", sk, "\n")

ct = hyb_abe.encrypt(pk, message, access_policy)
#print("ct => ", ct, "\n")

mdec = hyb_abe.decrypt(pk, sk, ct)
assert mdec == message, "Failed Decryption!!!"

print("Successful Decryption!!!", "\n")

print('end')

    
class pairingElement(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, pairingElement):
#            for i in obj:
#                print(i)            
Пример #7
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!!!")
Пример #8
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
Пример #9
0
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']

print(sara_attributes)
print(kevin_attributes)

sara_sk = hybrid_abe.keygen(pk, mk, sara_attributes)
sara_sk = objectToBytes(sara_sk, groupObj)
if debug: print("sara_sk => ", sara_sk)

kevin_sk = hybrid_abe.keygen(pk, mk, kevin_attributes)
kevin_sk = objectToBytes(kevin_sk, groupObj)
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)