예제 #1
0
def main():
    groupObj = PairingGroup('SS512')
    dabe = Dabe(groupObj)
    TP = dabe.get_Trapdoor_json("TRAPDOOR.json")
    par_filelist = get_files("./PARTIAL_CIPHERTEXT")
    if len(par_filelist) == 0:
        return
    des = "./PLAINTEXT/"
    if os.path.exists(des):
        shutil.rmtree(des)
    os.mkdir(des)
    for i in par_filelist:
        Par_CT = dabe.get_Par_CT_json(i)
        orig_m = dabe.full_decrypt(TP, Par_CT)
        #print("\nSymmetric key is")
        #print(orig_m)
        symcrypt = SymmetricCryptoAbstraction(extractor(orig_m))
        filename = "./MATCHED_FILE/SYMMETRIC_CIPHERTEXT_" + (
            i.split('_'))[3].split('.')[0] + ".ct"
        with open(filename, 'r') as f:
            cm = f.read()
        pm = symcrypt.decrypt(cm)
        #print(str(pm, encoding = 'utf-8'))
        filename = "./PLAINTEXT/SYMMETRIC_PLAINTEXT_" + (
            i.split('_'))[3].split('.')[0] + ".pp"
        with open(filename, 'w') as file_object:
            file_object.write(str(pm, encoding='utf-8'))
예제 #2
0
def read(user, record):
    """
    Function to read some public health record, from a given user. Returns
    all parts of the record.

    :param user:      User public key that wants to read the health record
    :param record:    Public health record to be read
    """

    # Get the record from the file system and load the key
    data = data_helper.load(user, record)
    user_key = load_user_key(user)

    # Decrypt the symmetric key using the TIPRE key
    sym_crypto_key = pre.decrypt(get_params(), user_key, data[SYMKEY()])

    # Setup symmetric crypto
    sym_crypto = SymmetricCryptoAbstraction(extract_key(sym_crypto_key))

    # Attempt to decrypt all columns and return
    decrypted_record = {
        k: sym_crypto.decrypt(v)
        for k, v in data.items() if k != SYMKEY()
    }
    return decrypted_record
예제 #3
0
 def MsgTestAESCBCSeperate(self,msg):
     groupObj = PairingGroup('SS512')
     ran = groupObj.random(GT)
     a =  SymmetricCryptoAbstraction(sha1(ran))
     ct = a.encrypt(msg)        
     b =  SymmetricCryptoAbstraction(sha1(ran))
     dmsg = b.decrypt(ct);
     assert msg == dmsg , 'o: =>%s\nm: =>%s' % (msg, dmsg)
예제 #4
0
 def decrypt_text(self, ct, secret):
     try:
         k = extractor(secret)
         symcrypt = SymmetricCryptoAbstraction(k)
         text = symcrypt.decrypt(ct)
         return text
     except Exception as e:
         print("Unexpected error:", str(e))
예제 #5
0
 def encrypt_text(self, pt, secret):
     try:
         k = extractor(secret)
         symcrypt = SymmetricCryptoAbstraction(k)
         ct = symcrypt.encrypt(pt)
         return ct
     except Exception as e:
         print("Unexpected error:", str(e))
예제 #6
0
    def encrypt(self, pk, M, attr_list):
        if debug: print('Encryption Algorithm...')
        k = group.random(ZR)
        Cs = pk**k

        Ci = {}
        for attr in attr_list:
            Ci[attr] = self.attribute[attr]**k

        symcrypt = SymmetricCryptoAbstraction(extractor(Cs))
        C = symcrypt.encrypt(M)

        return {'C': C, 'Ci': Ci, 'attributes': attr_list}
예제 #7
0
def decrypt(key, cipher):
    a = SymmetricCryptoAbstraction(extractor(key))

    results = 0.0
    for i in range(0, number):
        start = time.clock()
        a.decrypt(content)
        end = time.clock()
        results += end - start
    mean = results / number
    logging.info("AES decrypt: " + str(mean))

    content = a.decrypt(cipher)
    return content
예제 #8
0
def main():
    groupObj = PairingGroup('SS512')
    dabe = Dabe(groupObj)
    GP = dabe.get_global_PP_json("./gpp/global_parameters.json")
    filename = "SERVER_KEY.json"
    pk_ser = {}
    with open(filename, 'r') as f:
        Ser_json = json.load(f)
    for i in (Ser_json['pk_ser']).keys():
        pk_ser['V'] = groupObj.deserialize(bytes(Ser_json['pk_ser']['V'], encoding='utf-8'))
        pk_ser['X'] = groupObj.deserialize(bytes(Ser_json['pk_ser']['X'], encoding='utf-8'))
    with open('./policy.pp', 'r') as f:
        lists = f.readlines()
        policy = lists[0].rstrip('\n')
    with open('./message.pp', 'r') as f:
        pm = f.read()
    # symmetric key for encryption
    ssk = groupObj.random(GT)
    print("\nsymmetric key is\n")
    print(ssk)
    symcrypt = SymmetricCryptoAbstraction(extractor(ssk))
    SSCT = symcrypt.encrypt(pm)
    filename = "SYMMETRIC_CIPHERTEXT.ct"
    with open(filename, 'w') as file_object:
        file_object.write(SSCT)
    #m = groupObj.init(GT, tt)
    # Number of keywords for index generation
    print("\nEncrypted search index is")
    num_kw = int(sys.argv[1])
    keywords = []
    for i in range(0, num_kw):
        keywords.append(sys.argv[2 + i])
    Offline_CT = dabe.get_Offline_CT_json("OFFLINE_CIPHERTEXT.json")
    CT = dabe.online_encrypt(GP, pk_ser, Offline_CT, ssk, policy, keywords)
    print(CT)
    filename = "ENCRYPTED_INDEX.json"
    FullCT_json = {}
    for i in CT.keys():
        if type(CT[i]) == dict:
            FullCT_json[i] = {}
            for j in CT[i].keys():
                FullCT_json[i].update({j: str(groupObj.serialize(CT[i][j]), encoding='utf-8')})
        elif i == 'policy':
            FullCT_json[i] = CT[i]
        else:
            FullCT_json[i] = str(groupObj.serialize(CT[i]), encoding='utf-8')
    with open(filename, 'w') as file_object:
        json.dump(FullCT_json, file_object)
예제 #9
0
 def encrypt(self, pk, M, attr_list): 
     if debug: print('Encryption Algorithm...')
     k = group.random(ZR);
     Cs = pk ** k
     
     Ci = {}
     for attr in attr_list:
         Ci[attr] = self.attribute[attr] ** k
     
     symcrypt = SymmetricCryptoAbstraction(hashPair(Cs))
     C = symcrypt.encrypt(M)
     # HMAC
     # from charm.toolbox.symcrypto import MessageAuthenticator
     # m = MessageAuthenticator(extract_key(key))
     # AuthenticatedMessage = m.mac('Hello World')
     return { 'C': C, 'Ci': Ci,'attributes': attr_list }
    def decrypt_range(self, start, end, param, kac, msk):
        leaves = iter([])
        kac_ct = []
        ct = []
        plain = []
        kac_p = []
        S = []

        kac_nodes = sorted(self.lookup_range(start, end),
                           key=lambda node: node.kac_index)
        for n in kac_nodes:
            S.append(n.kac_index)
            kac_ct.append(n.kac_cipher)

        K_s = kac.extract(msk, S, param)
        start_time = time.clock()
        kac_plain = kac.decrypt_general(K_s, S, S, kac_ct, param)

        ct = (i.cipher for i in kac_nodes)
        decrypted = (SymmetricCryptoAbstraction(extractor(k)).decrypt(c)
                     for k, c in itertools.izip(kac_plain, ct))

        for n, m in itertools.izip(kac_nodes, decrypted):
            leaves = itertools.chain(
                leaves,
                HashTree(m, n.min_val, n.max_val).generate_tree())
        end_time = time.clock()
        return leaves, end_time - start_time
예제 #11
0
    def decrypt(self, C, D):
        policy = util.createPolicy(D['policy'])
        attrs = util.prune(policy, C['attributes'])
        if attrs == False:
            return False
        coeff = util.getCoefficients(policy)

        Z = {}
        prodT = 1
        for i in range(len(attrs)):
            x = attrs[i].getAttribute()
            y = attrs[i].getAttributeAndIndex()
            Z[y] = C['Ci'][x]**D['Du'][x]
            prodT *= Z[y]**coeff[y]

        symcrypt = SymmetricCryptoAbstraction(extractor(prodT))

        return symcrypt.decrypt(C['C'])
예제 #12
0
def test2():
    client = UdpEndPoint()
    p = UdpEndPoint()
    group_object = PairingGroup('SS512')
    key_client = group_object.random(GT)
    key_p = group_object.random(GT)
    nonce = OpenSSLRand().getRandomBits(128)
    server_crypter_a = SymmetricCryptoAbstraction(extractor(key_client))
    server_crypter_b = SymmetricCryptoAbstraction(extractor(key_p))
    c_package_a = test1(client, p, nonce,
                        objectToBytes(key_client, group_object),
                        objectToBytes(key_p, group_object))
    print('===========================================================')
    print(c_package_a)
    key_package_a = server_crypter_a.decrypt(c_package_a)
    key_package_a = bytesToObject(key_package_a, group_object)
    key_package_b = server_crypter_b.decrypt(key_package_a[3])
    key_package_b = bytesToObject(key_package_b, group_object)
    print('===========================================================')
    i = 1
    for thing in key_package_a:
        print(str(i) + '.', thing)
        i += 1
    print('===========================================================')
    j = 1
    for thing in key_package_b:
        print(str(j) + '.', thing)
        j += 1
    print('===========================================================')
예제 #13
0
def insert(user, data, record, type_attribute):
    """
    Insert data into a public health record.

    :param user:            User that wants to insert data
    :param data:            Data to be inserted
    :param record:          Public health record in which data is inserted.
    :param type_attribute:  The type for this record

    """

    # Check if some arguments are correct
    if record is None:
        sys.exit("Please provide the record")
    if SYMKEY() in data:
        sys.exit("Data contains the key {}, please use a different key".format(
            SYMKEY()))

    # Load the users key
    user_key = load_user_key(user)

    # Create new symmetric key
    sym_crypto_key = group.random(GT)
    sym_crypto = SymmetricCryptoAbstraction(extract_key(sym_crypto_key))
    # Encrypt symmetric key with TIPRE
    # and the data using the symmetric key
    encrypted_sym_key = pre.encrypt(get_params(), user, sym_crypto_key,
                                    user_key, type_attribute)
    encrypted_data = {k: sym_crypto.encrypt(v) for k, v in data.items()}
    encrypted_data[SYMKEY()] = encrypted_sym_key

    # Store the data
    try:
        data_helper.save(user, type_attribute, encrypted_data, record)
        print("Data is inserted into record \'{}\' by \'{}\'".format(
            record, user))
        print("Data to insert into record:\n{}".format(data))
    except RecordAlreadyExists as e:
        print(e)
예제 #14
0
 def MsgTestAESCBCSeperate(self, msg):
     groupObj = PairingGroup('SS512')
     ran = groupObj.random(GT)
     a = SymmetricCryptoAbstraction(sha1(ran))
     ct = a.encrypt(msg)
     b = SymmetricCryptoAbstraction(sha1(ran))
     dmsg = b.decrypt(ct)
     assert msg == dmsg, 'o: =>%s\nm: =>%s' % (msg, dmsg)
예제 #15
0
파일: ible.py 프로젝트: zzbin2000/IB-PRE
def ible(pre, ID, msg, k, master_key, params, log_file):

    if type(msg) != bytes: raise "Message type error: msg should be bytes."

    # switch for display
    #debug = True
    debug = False

    if debug:
        print("\nThe original message is: \n", msg)

    # Generate the Sym Cipher initilized by k
    symCipher = SymmetricCryptoAbstraction(k)

    # Symmetric Encrypt: AES(CTR) default
    t1 = time.time()
    ct = symCipher.encrypt(msg)
    t2 = time.time()
    t_aes = (t2 - t1) * 1000
    log = '{0:.4f}'.format(t_aes) + "\t"

    # Generate private keys for ID
    sk1 = pre.keyGen(master_key, ID)

    # Encrypt 'Sym k' using ID
    t1 = time.time()
    ck = pre.encrypt_jet(params, ID, k)
    t2 = time.time()
    t_ibe = (t2 - t1) * 1000
    log += '{0:.4f}'.format(t_ibe) + "\t"

    # decryption using sk1
    t1 = time.time()
    dk = pre.decrypt_jet(params, sk1, ck)
    t2 = time.time()
    t_ibd = (t2 - t1) * 1000
    log += '{0:.4f}'.format(t_ibd) + "\t"

    if debug:
        print("\nThe decrypted key is:\n", dk)

    # Transmit dk and ct to the receipt
    # ........

    # Sym decrypt using the IBD output
    decipher = SymmetricCryptoAbstraction(dk)

    t1 = time.time()
    dmsg = decipher.decrypt(ct)
    t2 = time.time()
    t_aes2 = (t2 - t1) * 1000
    log += '{0:.4f}'.format(t_aes2) + "\n"

    if debug:
        print("\nThe decrypted message is:\n", dmsg)
    assert dmsg == msg, 'o: =>%s\nm: =>%s' % (msg, dmsg)
    # output log
    log_file.write(log)
예제 #16
0
    def requestIdentityBasedPrivateKey(self):
        """
        Setup a local PKG only for this Device to be able to do initialization with a PKG.

        Set the KeyLocator to the ID of the requesting Device.
        Append the TemporaryMasterPublicKey to the Interest.

        Interest:
            Name: /ndn/no/ntnu/initDevice/<nonce>/<tempMasterPublicKey>
            Selector: KeyLocator = ID

        Send the Interest
        """
        self.initRequestStart = time.clock()

        ID = self.deviceName.toUri()
        # Make each init unique with a session
        self.initSession = str(int(round(util.getNowMilliseconds() / 1000.0)))

        a = SymmetricCryptoAbstraction(self.presharedKey)
        message = {"ID": ID, "nonce": self.initSession}
        cipher = a.encrypt(str(message))
        cipherEncoded = base64.b64encode(cipher)
        logging.info("Cipher encoded: " + str(cipherEncoded))

        name = Name(self.baseName).append("pkg").append("initDevice").append(
            self.initSession)
        interest = Interest(name)
        # interest.setMinSuffixComponents(6)
        keyLocator = KeyLocator()
        keyLocator.setType(KeyLocatorType.KEYNAME)
        keyLocator.setKeyName(Name(self.deviceName).append(cipherEncoded))
        interest.setKeyLocator(keyLocator)

        logging.info("Expressing interest name: " + name.toUri())
        self.face.expressInterest(interest, self.onInitData, self.onTimeout)
예제 #17
0
def test1(client, p, nonce, key_client, key_p):
    group_object = PairingGroup('SS512')
    shared_key = group_object.random(GT)
    crypter_a = SymmetricCryptoAbstraction(
        extractor(bytesToObject(key_client, group_object)))
    crypter_b = SymmetricCryptoAbstraction(
        extractor(bytesToObject(key_p, group_object)))
    package_b = crypter_b.encrypt(
        objectToBytes([shared_key, serialize_endpoint(client)], group_object))
    package_a = crypter_a.encrypt(
        objectToBytes([
            Conversion.OS2IP(nonce), shared_key,
            serialize_endpoint(p), package_b
        ], group_object))
    return package_a
    def bfs_encrypt(self, pk, param, kac):
        queue = [self]
        index = 1
        while len(queue) > 0:
            current = queue.pop(0)

            current.kac_index = index

            # print current.kac_index, current.data, current.min_val, current.max_val

            index += 1
            # use kac plaintext to encrypt message
            m = group.random(GT)
            current.kac_cipher = kac.encrypt(pk, current.kac_index, m, param)
            current.cipher = SymmetricCryptoAbstraction(extractor(m)).encrypt(
                current.data)

            if current.left is not None:
                queue.append(current.left)
            if current.right is not None:
                queue.append(current.right)
    def derive_keys(self, aggregate_key, param, min_val, max_val, l,
                    encrypted_leaves):
        # inclusive of layer 0
        top_layer = list(self.multi_layers[l].derive_keys(
            aggregate_key, param, min_val, max_val))
        yield top_layer

        for i in reversed(xrange(l)):
            cipher_iter = iter(encrypted_leaves[i])
            next_layer = []
            # skip 0th frame
            cipher_iter.next()
            for plain in top_layer:
                # print 'lol', len(top_layer)
                sym_key = plain.data
                # print i, sym_key
                cipher = cipher_iter.next()
                next_layer.append(
                    pickle.loads(
                        SymmetricCryptoAbstraction(sym_key).decrypt(cipher)))
            top_layer = next_layer
            yield top_layer
    def encrypt(self, pk, param):
        pk_iter = iter(pk)
        param_iter = iter(param)
        # return
        self.ct = [
            i.encrypt(pk_iter.next(), param_iter.next())
            for i in self.multi_layers
        ]
        self.encrypted_leaves = []
        unencrypted_leaves = []
        for kac_layer in self.multi_layers:
            unencrypted_leaves.append(list(kac_layer.generate_keys()))

        # sym_key = pickle.dumps(unencrypted_leaves[3][2])
        # plain = pickle.dumps(unencrypted_leaves[2][2])
        # cipher = SymmetricCryptoAbstraction(sym_key).encrypt(plain)
        # print unencrypted_leaves[2][2].data
        # print pickle.loads(SymmetricCryptoAbstraction(sym_key).decrypt(cipher)).data

        for i in xrange(1, len(unencrypted_leaves)):
            self.encrypted_leaves.append([None])
            for j in xrange(1, len(unencrypted_leaves[i])):
                sym_key = unencrypted_leaves[i][j].data
                plain = pickle.dumps(unencrypted_leaves[i - 1][j])
                self.encrypted_leaves[i - 1].append(
                    SymmetricCryptoAbstraction(sym_key).encrypt(plain))

        # decryption_plain = []
        # for i in xrange(len(self.encrypted_leaves)):
        # 	for j in xrange(1, len(self.encrypted_leaves[i])):
        # 		# print i,j
        # 		sym_key = unencrypted_leaves[i+1][j].data
        # 		# print i, j, sym_key
        # 		cipher = self.encrypted_leaves[i][j]
        # 		decryption_plain.append(pickle.loads(SymmetricCryptoAbstraction(sym_key).decrypt(cipher)))

        return self.encrypted_leaves, unencrypted_leaves
예제 #21
0
def dec(k1, k2, ct):
    a1 = SymmetricCryptoAbstraction(k1)
    a2 = SymmetricCryptoAbstraction(k2)
    m0 = a2.decrypt(ct)
    m1 = a1.decrypt(m0)
    return m1
예제 #22
0
파일: decrypto.py 프로젝트: nemare/Rbac-abe
# print pk+"\n"
# print cipher+"\n"

mk = bytesToObject(mk, groupObj)
pk = bytesToObject(pk, groupObj)
cipher = bytesToObject(cipher, groupObj)

sk = cpabe.keygen(pk, mk, asl)

print sk

try:
    plaintext = cpabe.decrypt(pk, sk, cipher)
except:
    print "Error"

if plaintext != False:
    a = SymmetricCryptoAbstraction(sha1(plaintext))

    with open(fileUrl, "rb") as f:
        cloudfile = f.read()
    file = a.decrypt(cloudfile)

    with open(fileUrl, "wb") as re:
        re.write(file)
else:
    print "Dcrypto Fail!"

del groupObj

#os.remove(configUrl)
예제 #23
0
파일: cpabe.py 프로젝트: nemare/Rbac-abe
from charm.toolbox.pairinggroup import PairingGroup,GT
from charm.core.math.pairing import hashPair as sha1
from charm.schemes.abenc.abenc_waters09 import CPabe09
from charm.toolbox.symcrypto import SymmetricCryptoAbstraction,AuthenticatedCryptoAbstraction, MessageAuthenticator

groupObj = PairingGroup('SS512')
symKey = groupObj.random(GT)
a1 =  SymmetricCryptoAbstraction(sha1(symKey))
with open('/Users/cirnotxm/down/pk','rb') as f:
    msg1 = f.read() 
ct = a1.encrypt(msg1)
cpabe = CPabe09(groupObj)
(msk, pk) = cpabe.setup()
pol = '((ONE or THREE) and (TWO or FOUR))'

with open('/Users/cirnotxm/down/msk','wb') as fm:
    fm.write(str(msk))
    
with open('/Users/cirnotxm/down/mpk','wb') as fp:
    fp.write(str(pk))


with open('/Users/cirnotxm/down/info','wb') as fi:
    fi.write(ct)

print('Acces Policy: %s' % pol)
        
cipher = cpabe.encrypt(pk, symKey, pol)
print("\nCiphertext...")

print cipher
예제 #24
0
from charm.toolbox.symcrypto import SymmetricCryptoAbstraction, AuthenticatedCryptoAbstraction, MessageAuthenticator
from charm.toolbox.pairinggroup import PairingGroup, GT
from charm.core.math.pairing import hashPair as sha1

debug = 0

groupObj = PairingGroup('SS512')

pk = groupObj.random(GT)

if debug: print pk

a = SymmetricCryptoAbstraction(sha1(pk))

try:

    f = open('/Users/cirnotxm/down/charm.dmg', 'rb')
    ff = f.read()
    ct = a.encrypt(ff)

    if debug: print ct

    ffe = open('/Users/cirnotxm/down/jiami', 'wb')

    ffe.write(ct)

    fpk = open('/Users/cirnotxm/down/pk', 'wb')

    fpk.write(groupObj.serialize(pk))

finally:
예제 #25
0
파일: abe-de.py 프로젝트: nemare/Rbac-abe
from charm.toolbox.pairinggroup import PairingGroup, GT
from charm.core.math.pairing import hashPair as sha1
from charm.schemes.abenc.abenc_waters09 import CPabe09
from charm.toolbox.symcrypto import SymmetricCryptoAbstraction, AuthenticatedCryptoAbstraction, MessageAuthenticator

asl = ['ONE', 'TWO']
groupObj = PairingGroup('SS512')
cpabe = CPabe09(groupObj)

with open('/Users/cirnotxm/down/info', 'rb') as f:
    info = f.read()

cpkey = cpabe.keygen(pk, msk, asl)

with open('/Users/cirnotxm/down/cipk', 'r') as f2:
    ciphertext = f2.read()

ciphertext = eval(ciphertext)

print ciphertext

prig_msg = cpabe.decrypt(pk, cpkey, ciphertext)

a2 = SymmetricCryptoAbstraction(sha1(orig_symKey))

plaintext = a2.decrypt(info)

print plaintext
예제 #26
0
def SE_Encrypt (key, data):
	#crypto = AES.new(os.urandom(32), AES.MODE_CTR, counter = lambda : os.urandom(16))
	#crypto.encrypt(data)
	SE=SymmetricCryptoAbstraction (key, AES, MODE_CBC)
	SE.encrypt (data)
예제 #27
0
    def onData(self, interest, data):
        """
        Data:
            Content: 
                master_public_key to PKG
                ibeKey = ibe(randomKey)
                cipher = encrypt(PrivateKey, randomKey)

        Decode the master_public_key and compare it to the device.master_public_key (if they match, they trust the same PKG)
        Decrypt the symmetric key, and decrypt the cipher

        Sensor Data reveiced! 

        :param Interest interest:
        :param Data data:
        """
        self.ibs_scheme.verifyData(self.signature_master_public_key, data,
                                   self.onVerifiedData,
                                   self.onVerifyDataFailed)

        message = messageBuf_pb2.Message()
        message.ParseFromString(data.getContent().toRawStr())

        # TODO: compare nonce
        session = message.nonce

        if (message.type == messageBuf_pb2.Message.SENSOR_DATA):
            if (message.encAlgorithm == messageBuf_pb2.Message.AES):

                # Check if IBS algorithm is the same
                if not (self.ibs_scheme.algorithm == message.ibsAlgorithm):
                    logging.error("IBS algorithm doesnt match! Receiver: " +
                                  self.ibs_scheme.algorithm + ", Sender: " +
                                  message.ibsAlgorithm)

                #Compare signature_master_public_key
                signatureMasterPublicKeyDict = ast.literal_eval(
                    message.identityBasedSignatureMasterPublicKey)
                messageSignatureMPK = deserializeObject(
                    signatureMasterPublicKeyDict, self.ibs_scheme.group)
                if not (self.signature_master_public_key
                        == messageSignatureMPK):
                    logging.error("SignatureMasterPulicKey does not match!")

                # Check if IBE algorithm is the same
                if not (self.ibe_scheme.algorithm == message.ibeAlgorithm):
                    logging.error("IBE algorithm doesnt match! Receiver: " +
                                  self.ibe_scheme.algorithm + ", Sender: " +
                                  message.ibeAlgorithm)

                #Compare master_public_key
                masterPublicKeyDict = ast.literal_eval(
                    message.identityBasedMasterPublicKey)
                messageMPK = deserializeObject(masterPublicKeyDict,
                                               self.ibe_scheme.group)
                if not (self.master_public_key == messageMPK):
                    logging.error("MasterPulicKey does not match!")

                #Decrypt identityBasedEncrypedKey
                identityBasedEncryptedKeyDict = ast.literal_eval(
                    message.identityBasedEncryptedKey)
                identityBasedEncryptedKey = deserializeObject(
                    identityBasedEncryptedKeyDict, self.ibe_scheme.group)
                key = self.ibe_scheme.decryptKey(self.master_public_key,
                                                 self.private_key,
                                                 identityBasedEncryptedKey)

                #Decrypt encryptedMessage
                a = SymmetricCryptoAbstraction(extractor(key))
                data = a.decrypt(message.encryptedMessage)

                # Use data from device to something ..
                logging.info("Data received: " + str(data))
                self.dataRequestEnd = time.clock()
                logging.info("Request and receive data time: " +
                             str(self.dataRequestEnd - self.dataRequestStart))
예제 #28
0
파일: decrypto.py 프로젝트: aietxm/Rbac-abe
# print pk+"\n"
# print cipher+"\n"

mk = bytesToObject(mk,groupObj)
pk = bytesToObject(pk,groupObj)
cipher = bytesToObject(cipher,groupObj)

sk = cpabe.keygen(pk,mk,asl)

print sk

try:
    plaintext = cpabe.decrypt(pk,sk,cipher)
except:
    print "Error"

if plaintext!=False :
    a = SymmetricCryptoAbstraction(sha1(plaintext))

    with open(fileUrl,"rb") as f:
        cloudfile = f.read()
    file = a.decrypt(cloudfile)

    with open(fileUrl,"wb") as re:
        re.write(file)
else:
    print "Dcrypto Fail!"

del groupObj

#os.remove(configUrl)
예제 #29
0
 def MsgtestAESCBC(self,msg):
     groupObj = PairingGroup('SS512')
     a =  SymmetricCryptoAbstraction(sha1(groupObj.random(GT)))
     ct = a.encrypt(msg)
     dmsg = a.decrypt(ct);
     assert msg == dmsg , 'o: =>%s\nm: =>%s' % (msg, dmsg)
예제 #30
0
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        """
        Interest:
            Name: /ndn/no/ntnu/<device>/sensorPull/<nonce>
            Selector: KeyLocator = ID

        The ID of the requesting Device is stored in KeyLocator in the Interest, 
        and the TemporaryMasterPublicKey to the device is sent in the Interest Name as shown above.

        Encrypt a symmetric key with the MasterPublicKey and the ID.
        Encrypt the SensorData with symmetric encryption, using the symmetric key.
        
        Data:
            Content: 
                master_public_key to PKG
                ibeKey = ibe(randomKey)
                cipher = encrypt(sensorData, randomKey)

        Sign the Data and send.

        :param Name prefix:
        :param Interest interest:
        :param Transport transport: An object of a subclass of Transport to use for communication.
        :param Name registeredPrefixId:
        """
        self.ibs_scheme.verifyInterest(self.signature_master_public_key,
                                       interest, self.onVerifiedInterest,
                                       self.onVerifyInterestFailed)

        ID = ""
        if interest.getKeyLocator().getType() == KeyLocatorType.KEYNAME:
            ID = interest.getKeyLocator().getKeyName().toUri()

        keyName = interest.getName()
        session = keyName.get(keyName.size() - 1).toEscapedString()

        data = Data(interest.getName())
        contentData = "This should be sensordata blablabla"

        # Symmetric key for encryption
        self.key = self.ibe_scheme.getRandomKey()
        # Identity-Based Encryption of symmetric key
        identityBasedEncryptedKey = self.ibe_scheme.encryptKey(
            self.master_public_key, ID, self.key)
        identityBasedEncryptedKey = str(
            serializeObject(identityBasedEncryptedKey, self.ibe_scheme.group))
        # Master Public Key
        identityBasedMasterPublicKey = str(
            serializeObject(self.master_public_key, self.ibe_scheme.group))
        # Signature Master Public Key
        identityBasedSignatureMasterPublicKey = str(
            serializeObject(self.signature_master_public_key,
                            self.ibs_scheme.group))
        # Symmetric AES encryption of contentData
        a = SymmetricCryptoAbstraction(extractor(self.key))
        encryptedMessage = a.encrypt(contentData)

        message = messageBuf_pb2.Message()
        message.identityBasedMasterPublicKey = identityBasedMasterPublicKey
        message.identityBasedSignatureMasterPublicKey = identityBasedSignatureMasterPublicKey
        message.identityBasedEncryptedKey = identityBasedEncryptedKey
        message.encryptedMessage = encryptedMessage
        message.encAlgorithm = messageBuf_pb2.Message.AES
        message.ibeAlgorithm = self.ibe_scheme.algorithm
        message.ibsAlgorithm = self.ibs_scheme.algorithm
        message.nonce = session
        message.timestamp = int(round(util.getNowMilliseconds() / 1000.0))
        message.type = messageBuf_pb2.Message.SENSOR_DATA

        content = message.SerializeToString()
        metaInfo = MetaInfo()
        metaInfo.setFreshnessPeriod(30000)  # 30 seconds
        data.setContent(Blob(content))
        data.setMetaInfo(metaInfo)

        self.ibs_scheme.signData(self.signature_master_public_key,
                                 self.signature_private_key, self.deviceName,
                                 data)
        #self.keyChain.sign(data, self.certificateName)
        encodedData = data.wireEncode()

        logging.info("Encrypting with ID: " + ID)
        transport.send(encodedData.toBuffer())
        logging.info("Sent encrypted Data")
예제 #31
0
from charm.toolbox.symcrypto import SymmetricCryptoAbstraction,AuthenticatedCryptoAbstraction, MessageAuthenticator
from charm.toolbox.pairinggroup import PairingGroup,GT
from charm.core.math.pairing import hashPair as sha1

debug = 0

groupObj = PairingGroup('SS512')

pk = groupObj.random(GT)

if debug :print pk

a = SymmetricCryptoAbstraction(sha1(pk))

try:
    

    f = open('/Users/cirnotxm/down/charm.dmg','rb')
    ff = f.read()
    ct = a.encrypt(ff)

    if debug :print ct

    ffe = open('/Users/cirnotxm/down/jiami','wb')

    ffe.write(ct)
    
    fpk = open('/Users/cirnotxm/down/pk','wb')
    
    fpk.write(groupObj.serialize(pk))
예제 #32
0
    def onInitData(self, interest, data):
        """
        Data:
            Content: 
                master_public_key to PKG
                ibeKey = ibe(randomKey)
                cipher = encrypt(PrivateKey, randomKey)

        Decrypt the symmetric key with the TemporaryMasterPublicKey and the device ID.
        Use the symmetric key to decrypt the PrivateKey.

        Device is now added to the PKG        
        
        :param Interest interest:
        :param Data data:
        """
        message = messageBuf_pb2.Message()
        message.ParseFromString(data.getContent().toRawStr())

        # TODO: Compare session
        if not self.initSession == message.nonce:
            logging.warning("Nonce is not equal!")

        # SignatureMasterPublicKey
        signatureMasterPublicKeyDict = ast.literal_eval(
            message.identityBasedSignatureMasterPublicKey)
        self.signature_master_public_key = deserializeObject(
            signatureMasterPublicKeyDict, self.ibs_scheme.group)
        # Verify signature
        self.ibs_scheme.verifyData(self.signature_master_public_key, data,
                                   self.onVerifiedData,
                                   self.onVerifyDataFailed)

        if (message.type == messageBuf_pb2.Message.INIT):
            if (message.encAlgorithm == messageBuf_pb2.Message.AES):
                # Check if IBS algorithm is the same
                if not (self.ibs_scheme.algorithm == message.ibsAlgorithm):
                    logging.error("IBS algorithm doesnt match! Receiver: " +
                                  self.ibs_scheme.algorithm + ", Sender: " +
                                  message.ibsAlgorithm)

                # Check if IBE algorithm is the same
                if not (self.ibe_scheme.algorithm == message.ibeAlgorithm):
                    logging.error("IBE algorithm doesnt match! Receiver: " +
                                  self.ibe_scheme.algorithm + ", Sender: " +
                                  message.ibeAlgorithm)

                #Decrypt encryptedMessage
                # PrivateKeys
                a = SymmetricCryptoAbstraction(self.presharedKey)
                privateKeyEncoded = a.decrypt(message.encryptedPK)
                signaturePrivateKeyEncoded = a.decrypt(message.encryptedSPK)
                self.private_key = bytesToObject(privateKeyEncoded,
                                                 self.ibe_scheme.group)
                self.signature_private_key = bytesToObject(
                    signaturePrivateKeyEncoded, self.ibs_scheme.group)

                # MasterPublicKey
                masterPublicKeyDict = ast.literal_eval(
                    message.identityBasedMasterPublicKey)
                self.master_public_key = deserializeObject(
                    masterPublicKeyDict, self.ibe_scheme.group)

                logging.info(
                    "Initialization success! PrivateKeys, MasterPublicKeys received."
                )
                self.initRequestEnd = time.clock()
                logging.info("Initialization time: " +
                             str(self.initRequestEnd - self.initRequestStart))
예제 #33
0
from charm.toolbox.pairinggroup import PairingGroup, ZR, G1, G2, GT, pair, extract_key
from charm.toolbox.symcrypto import AuthenticatedCryptoAbstraction, SymmetricCryptoAbstraction
from charm.core.math.pairing import hashPair as extractor

group = PairingGroup("SS512")

msg = b"This is a secret message that is larger than the group elements and has to be encrypted symmetrically"
print("original msg\n", msg)

r = group.random(G1)
print("random num\n", r)

# key = extractor(r)
key = extract_key(r)
print("symmetric key\n", key)

symcrypt = SymmetricCryptoAbstraction(
    key)  # or SymmetricCryptoAbstraction without authentication
# by default algo is AES in CBC mode

# encryption
ciphertext = symcrypt.encrypt(msg)
print("ciphertext\n", ciphertext)

# decryption
recoveredMsg = symcrypt.decrypt(ciphertext)
print("recovered msg\n", recoveredMsg)

assert msg == recoveredMsg
예제 #34
0
 def MsgtestAESCBC(self, msg):
     groupObj = PairingGroup('SS512')
     a = SymmetricCryptoAbstraction(sha1(groupObj.random(GT)))
     ct = a.encrypt(msg)
     dmsg = a.decrypt(ct)
     assert msg == dmsg, 'o: =>%s\nm: =>%s' % (msg, dmsg)
예제 #35
0
파일: abe-de.py 프로젝트: aietxm/Rbac-abe
from charm.core.math.pairing import hashPair as sha1
from charm.schemes.abenc.abenc_waters09 import CPabe09
from charm.toolbox.symcrypto import SymmetricCryptoAbstraction,AuthenticatedCryptoAbstraction, MessageAuthenticator

asl= ['ONE','TWO']
groupObj = PairingGroup('SS512')
cpabe = CPabe09(groupObj)


with open('/Users/cirnotxm/down/info','rb') as f:
    info = f.read()


cpkey = cpabe.keygen(pk,msk,asl)

with open('/Users/cirnotxm/down/cipk','r') as f2:
    ciphertext = f2.read()


ciphertext = eval(ciphertext)

print ciphertext

prig_msg = cpabe.decrypt(pk,cpkey,ciphertext)

a2 =  SymmetricCryptoAbstraction(sha1(orig_symKey))

plaintext = a2.decrypt(info)

print plaintext
예제 #36
0
def enc(k1, k2, msg):
    a1 = SymmetricCryptoAbstraction(k1)
    a2 = SymmetricCryptoAbstraction(k2)
    c0 = a1.encrypt(msg)
    c1 = a2.encrypt(c0)
    return c1
예제 #37
0
파일: docrypto.py 프로젝트: aietxm/Rbac-abe
fileUrl= s[0]
fileName= s[1]
pol = s[2]

if debug :
    print fileName
    print fileUrl
    print pol

groupObj = PairingGroup('SS512')

AES_pk = groupObj.random(GT)

if debug: print AES_pk

a = SymmetricCryptoAbstraction(sha1(AES_pk))
try:
    f = open(fileUrl, "rb")
    ptext = f.read()
    ct = a.encrypt(ptext)
    ctf = tempUrl + fileName;
    if debug: print  ctf
    fr = open(ctf, "wb")
    fr.write(ct)
except:
    print "Error"
finally:
    f.close()
    fr.close()

cpabe = CPabe09(groupObj)