Ejemplo n.º 1
0
    def encrypt(self, pk, m):
        (k, ID, x) = encap.S(pk['pub'])
        if type(m) != bytes:
           m = bytes(m, 'utf8')	
        if type(x) != bytes:
           x = bytes(x, 'utf8')	

        ID2 = group.hash(ID, ZR)

        m2 = m + b':' + x

        kprime = group.random(GT)
        kprimeStr = self.elmtToString(kprime, len(m2))

        C1 = ibenc.encrypt(pk['PK'], ID2, kprime)

        C2 = self.str_XOR(m2, kprimeStr)
        C2 = C2.encode('utf8')
        
        C1prime = pickleObject(serializeObject(C1, group))
        
        tag = hmac.new(k, C1prime+C2, hashlib.sha1).digest()
        
        cipher = { 'ID':ID, 'C1':C1, 'C2':C2, 'tag':tag }
        return cipher
 def serialize(self):
     d = self.__dict__.copy()
     if 'group' in d:
         del d['group']
         return {'param': self.group.param, 'rest': serializeObject(d, self.group)}
     else:
         return d
Ejemplo n.º 3
0
    def decrypt(self, pk, sk, c):
        ID2 = group.hash(c['ID'], ZR)
        SK = ibenc.extract(sk['msk'], ID2)
        kprime = ibenc.decrypt(pk, SK, c['C1'])

        kprimeStr = self.elmtToString(kprime, len(c['C2']))

        m2 = self.str_XOR(c['C2'], kprimeStr)

        x = m2.split(':')[1]
        k = encap.R(pk['pub'], c['ID'], x)

        C1prime = pickleObject(serializeObject(c['C1'], group))
        
        if(c['tag'] == hmac.new(k, C1prime+c['C2'], hashlib.sha1).digest()):
            return bytes(m2.split(':')[0], 'utf8')
        else:
            return b'FALSE'
Ejemplo n.º 4
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")
Ejemplo n.º 5
0
 def correctedObjectToBytes(self, object, group):
     object_ser = serializeObject(object, group)
     result = getBytes(
         json.dumps(object_ser, default=to_json, sort_keys=True))
     return base64.b64encode(zlib.compress(result))
Ejemplo n.º 6
0
 if method == 1:
     raise StartingError('Не был выбран метод работы программы')
 elif method == 2:
     raise StartingError(
         'Был выбран больше, чем один метод работы программы')
 elif method == 'k':
     (pk, sk) = bls.keygen()
     try:
         os.mkdir(namespace.directory)
     except IOError:
         pass
     f1 = open(namespace.directory + namespace.public_key, 'wb')
     f1.write(str(serializeDict(pk, bls.group)))
     f1.close()
     f2 = open(namespace.directory + namespace.secret_key, 'wb')
     f2.write(str(serializeObject(sk, bls.group)))
     f2.close()
 elif method == 's':
     try:
         f1 = open(namespace.directory + namespace.secret_key, 'rb')
         sk = deserializeObject(f1.read(), bls.group)
     except IOError:
         raise ApplicationError(
             'Файла с закрытым ключом по указанному пути не существует')
     f1.close()
     if namespace.message == None and namespace.file == None:
         raise StartingError(
             'Не было указано сообщение или путь файла с сообщением')
     elif namespace.message != None and namespace.file != None:
         raise StartingError('Были указаны 2 вида сообщений')
     elif namespace.message != None:
Ejemplo n.º 7
0
def serialize(Object, group):
    serializedDictWithBase64 = serializeObject(Object, group)
    serializedDict = reDecodeBase64Dict(serializedDictWithBase64)
    return pickle.dumps(serializedDict)