def run(self):
     """run when our device driver thread is started"""
     enc = SettingsBase.get_setting(self, "encryption")
     if enc:
         enc_key = '%016x' % 0x1234
         kSize = len(enc_key)
         aes = AES(enc_key, keySize=kSize, padding=padWithPadLen())
         
     self.sd = socket(AF_INET, SOCK_DGRAM)
     self.sd.bind((self.ip, self.port))
     self.sd.setblocking(0)
     
     while self.__stopevent.isSet()==False:
         while self.__stopevent.isSet()==False:
             try:
                 buf, addr = self.sd.recvfrom(255)
                 break
             except:
                 time.sleep(0.01)
         try:
             data=str(buf)
         except:
             data='data error'
         if enc:
             data=aes.decrypt(data)
         
         self.property_set(self.ch_name, Sample(0, str(data), self.ch_unit))
             
             
     self.__stopevent.clear()
Example #2
0
def decrypt_file(file, key):
    from crypto.cipher.aes import AES
    from crypto.cipher.base import noPadding

    cipher = AES(key, keySize=len(key), padding=noPadding())

    data = ''
    with open(file, "rb") as f:
        data = f.read()

    with open(file, "wb") as f:
        offset = 0
        while True:
            for enc in [True, False]:
                if enc:
                    chunk = data[offset:offset + len(key)]
                    offset += len(key)
                else:
                    chunk = data[offset:offset + len(key) * 1000]
                    offset += len(key) * 1000

                if len(chunk) == len(key):
                    chunk = cipher.decrypt(chunk)

                f.write(chunk)
            if not chunk:
                break
    f.close()
    def decrypt_subs(self, encsubs):
        encdata = binascii.unhexlify(encsubs)

        for key in subdeckeys[:]:
            subs=""
            out=[0,0,0,0]
            ecb = AES(binascii.unhexlify(key[0]))
            unaes = ecb.decrypt(encdata)
            xorkey = array('i',key[1])

            for i in range(0, len(encdata)/16):
                x = unaes[i*16:i*16+16]
                res = array('i',x)
                for j in range(0,4):
                    out[j] = res[j] ^ xorkey[j]
                x = encdata[i*16:i*16+16]
                xorkey = array('i',x)
                a=array('i',out)
                x=a.tostring()
                subs += x

            substart = subs.find("<P")

            if (substart > -1):
                print key
                i = subs.rfind("</P>")
                subs = subs[substart:i+4]
                return subs
    def decrypt_SMIL(self, encsmil):
        encdata = binascii.unhexlify(encsmil)

        for key in smildeckeys[:]:
            smil=""
            out=[0,0,0,0]
            ecb = AES(binascii.unhexlify(key[0]))
            unaes = ecb.decrypt(encdata)

            xorkey = array('i',key[1])

            for i in range(0, len(encdata)/16):
                x = unaes[i*16:i*16+16]
                res = array('i',x)
                for j in range(0,4):
                    out[j] = res[j] ^ xorkey[j]
                x = encdata[i*16:i*16+16]
                xorkey = array('i',x)
                a=array('i',out)
                x=a.tostring()
                smil = smil + x

            if (smil.find("<smil") == 0):
                print key
                i = smil.rfind("</smil>")
                smil = smil[0:i+7]
                return smil
 def decrypt_cid(self, p):
     cidkey = '48555bbbe9f41981df49895f44c83993a09334d02d17e7a76b237d04c084e342'
     v3 = binascii.unhexlify(p)
     print v3
     ecb = AES(binascii.unhexlify(cidkey))
     print ecb
     print ecb.decrypt(v3)
     return ecb.decrypt(v3).split("~")[0]
        def CCMtestVector(testCase, macSize, key, nonce, addAuth, pt, kct):
            """ CCM test vectors using AES algorithm """
            print '%s %s %s' % ('=' *
                                ((54 - len(testCase)) / 2), testCase, '=' *
                                ((54 - len(testCase)) / 2))
            key, nonce, pt, addAuth, kct = a2b_p(key), a2b_p(nonce), a2b_p(
                pt), a2b_p(addAuth), a2b_p(kct)

            alg = CCM(AES(key, keySize=len(key)),
                      macSize=macSize,
                      nonceSize=len(nonce))

            print 'alg=%s%skeySize=%3d   blockSize=%3d   M=%2d    L=%2d' % (
                alg.baseCipher.name, ' ' * (10 - len(alg.baseCipher.name)),
                alg.keySize, alg.blockSize, alg.M, alg.L)
            print 'key:    %s' % b2a_p(key)[9:]
            print 'nonce:  %s' % b2a_p(nonce)[9:]
            print 'addAuth:%s' % b2a_p(addAuth)[9:]
            print 'pt:     %s' % b2a_p(pt)[9:]
            ct = alg.encrypt(pt, nonce=nonce, addAuthData=addAuth)
            print 'ct:     %s' % b2a_p(ct)[9:]
            print 'kct:    %s' % b2a_p(kct)[9:]
            print '========================================================'
            self.assertEqual(ct, kct)
            dct = alg.decrypt(ct, nonce=nonce, addAuthData=addAuth)
            self.assertEqual(dct, pt)
Example #7
0
        def CBCtestVector(key, iv, pt, kct):
            """ CBC test vectors using AES algorithm """
            key, iv, pt, kct = a2b_p(key), a2b_p(iv), a2b_p(pt), a2b_p(kct)
            alg = CBC(AES(key), padding=noPadding())

            self.assertEqual(alg.encrypt(pt, iv=iv), kct)
            self.assertEqual(alg.decrypt(iv + kct), pt)
    def decrypt_pid(self, p):
        cp_strings = [
            '6fe8131ca9b01ba011e9b0f5bc08c1c9ebaf65f039e1592d53a30def7fced26c',
            'd3802c10649503a60619b709d1278ffff84c1856dfd4097541d55c6740442d8b',
            'c402fb2f70c89a0df112c5e38583f9202a96c6de3fa1aa3da6849bb317a983b3',
            'e1a28374f5562768c061f22394a556a75860f132432415d67768e0c112c31495',
            'd3802c10649503a60619b709d1278efef84c1856dfd4097541d55c6740442d8b'
        ]

        v3 = p.split("~")
        v3a = binascii.unhexlify(v3[0])
        v3b = binascii.unhexlify(v3[1])

        ecb = AES(v3b)
        tmp = ecb.decrypt(v3a)

        for v1 in cp_strings[:]:
            ecb = AES(binascii.unhexlify(v1))
            v2 = ecb.decrypt(tmp)
            if (re.match("[0-9A-Za-z_-]{32}", v2)):
                return v2
def generate_mic(data):
    '''
    \brief Generate a Message Integrity Code (MIC) over some given data.
    
    \param[in] data The data to calculate the MIC over, a binary string.
    
    \returns The 32-bit MIC, an integer.
    '''
    #alg       = AES_CBC(key=OTAP_KEY, keySize=len(OTAP_KEY), padding=padWithZeros())
    #outdata   = alg.encrypt(data, iv=OTAP_NONCE)
    alg = CCM(AES(OTAP_KEY), macSize=OTAP_MIC_LEN)
    outdata = alg.encrypt('', OTAP_NONCE, addAuthData=data)

    # the 32-bit MIC is the first 4 bytes of the CBC-MAC result (per CCM spec)
    #return struct.unpack('!L', outdata[-16:-12])[0]
    return struct.unpack('!L', outdata[-OTAP_MIC_LEN:])[0]
Example #10
0
def decrypt(encrypted, key):
	pes = AES(key.decode('base64'))
	decrypted = pes.decrypt(encrypted.decode('base64'))
	return decrypted
Example #11
0
 def __init__(self, key=None, padding=padWithPadLen(), keySize=16):
     CBC.__init__(self, AES(key, noPadding(), keySize), padding)
     self.name = 'AES_CBC'
 def TX(self):
     try:
         if self.rand:
             self.random_data_generator()
         else:
             self.bin_file_data_extractor()
         
         SAMPLES=int(self.samples_textctrl.GetValue())
         self.progress_bar.SetRange(SAMPLES)
         
         #Check Sample Rate mode and calculate Sleep in seconds
         sample_rate=self.sample_rate_textctrl.GetValue()
         if sample_rate in ['0','']:
             sample_rate=1
             self.sample_rate_textctrl.SetValue('1')
         else:
             sample_rate=float(sample_rate)
         choice=self.sample_rate_rb.GetStringSelection()
         if choice=='[Hz]':
             SLEEP=1.0/float(sample_rate)
         else:
             SLEEP=float(sample_rate)
         
         choice=self.addressing_type_rb.GetStringSelection()
         if choice.startswith('XBee'):
             #PAN Change
             #self.ser.Open()
             PAN = self.pan_id_textctrl.GetValue()
             frame_data="0801"+hexlify("ID")+PAN
             length = self.length_calc(frame_data)
             check_sum = self.check_sum_calc(frame_data)
             command="7E" + length + frame_data + check_sum
             self.ser.write(unhexlify(command))
             #response=hexlify(self.ser.readall())
             
             #Encryption Disable (if not set)
             if self.encryption_enabled:
                 AT_cmd=hexlify('KY')
                 AT_par=self.encryption_key
                 if len(AT_par) % 2:
                     AT_par='0'+AT_par
                 frame_data="0801"+AT_cmd+AT_par #AT command send
                 length = self.length_calc(frame_data)   
                 check_sum = self.check_sum_calc(frame_data)
                 command="7E" + length + frame_data + check_sum
                 self.ser.write(unhexlify(command))
                 #response=(hexlify(self.ser.readall()))
                 
                 AT_cmd=hexlify('EE')
                 AT_par='01'
                 frame_data="0801"+AT_cmd+AT_par #AT command send
                 length = self.length_calc(frame_data)   
                 check_sum = self.check_sum_calc(frame_data)
                 command="7E" + length + frame_data + check_sum
                 self.ser.write(unhexlify(command))
                 #response=(hexlify(self.ser.readall()))
             else:
                 AT_cmd=hexlify('EE')
                 AT_par='00'
                 frame_data="0801"+AT_cmd+AT_par #AT command send
                 length = self.length_calc(frame_data)   
                 check_sum = self.check_sum_calc(frame_data)
                 command="7E" + length + frame_data + check_sum
                 self.ser.write(unhexlify(command))
                 #response=(hexlify(self.ser.readall()))
         else:
             if self.encryption_enabled: #UDP AES Encryption calrulation here!
                 key = '%016x' % int(self.encryption_key, 16)
                 kSize = len(key)
                 
                 alg = AES(key, keySize=kSize, padding=padWithPadLen())
                 
                 for i in range(0, SAMPLES):
                     self.data_arr[i]=alg.encrypt(self.data_arr[i])
                 
         '''
         XBee S2     - we will use Radios Series2 (ZigBee) Module with explicit addressing (64bit & 16bit) data Transmission
         XBee short  - we will use Radios Series1 (XBee) Module with short addressing (16bit) data Transmission
         XBee long   - we will use Radios Series1 (XBee) Module with long addressing (64bit) data Transmission
         UDP         - we will use standard UDP data Transmission (no Digi Modules involved here)
         '''
         if choice=="XBee S2":
             #self.ser.Open()
             self.S2_TX(SLEEP, SAMPLES)
             #self.ser.Close()
         elif choice=="XBee short":
             #self.ser.Open()
             self.S1_TX_short(SLEEP, SAMPLES)
             #self.ser.Close()
         elif choice=="XBee long":
             #self.ser.Open()
             self.S1_TX_long(SLEEP, SAMPLES)
             #self.ser.Close()
         elif choice=="UDP":
             #self.udp.Open()
             self.UDP_TX(SLEEP, SAMPLES)
             #self.udp.Close()
             
     except KeyboardInterrupt:
         return
Example #13
0
 def test(self):
     aes_cbc = CBC(AES())
     aes_cbc.setKey('aaaaaaaaaaaaaaaa')
     ct1 = aes_cbc.encrypt('test')
     ct2 = aes_cbc.encrypt(
         'test')  # note - auto iv, reslt is different ths time
from crypto.cipher.aes  import AES
from crypto.cipher.base import padWithPadLen
from binascii           import a2b_hex, b2a_hex, hexlify, unhexlify

key = '%016x' % 0x1234
kSize = len(key)

data = 'Data goes here! Is that a surprize?'

alg = AES(key, keySize=kSize, padding=padWithPadLen())

enc_data=alg.encrypt(data)
dec_data=alg.decrypt(enc_data)