Exemple #1
0
    def test_spec(self):
        for version in _versions.keys():
            compatibility = version in {1, 3}
            path = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
            with open(os.path.join(path, "spec/triplesec_v{}.json".format(version))) as specfile:
                vectors = json.load(specfile)
                for v in vectors['vectors']:
                    key = unhex(v['key'])
                    pt = unhex(v['pt'])
                    ct = unhex(v['ct'])
                    rndstream = six.BytesIO(unhex(v['r']))

                    # Self-consistency
                    got_self_compat = triplesec.encrypt(pt, key, compatibility=compatibility)
                    self.assertEqual(pt, triplesec.decrypt(got_self_compat, key, compatibility=compatibility))

                    # Self-consistency for reverse compatibility
                    got_self_rev_compat = triplesec.encrypt(pt, key, compatibility=not compatibility)
                    self.assertEqual(pt, triplesec.decrypt(got_self_rev_compat, key, compatibility=not compatibility))

                    # Able to decrypt spec
                    self.assertEqual(pt, triplesec.decrypt(ct, key, compatibility=compatibility))

                    # Correct encryption with fixed random tape
                    T = TripleSec(key, rndstream=rndstream)
                    got = T.encrypt(pt, v=version, compatibility=compatibility)
                    self.assertEqual(hexlify(got), hexlify(ct))
Exemple #2
0
 def _VerifyMerchant(self,merchantCode):
     MODEL = "获取令牌";        
     pak = {Constants.PROJECT_ID:Config.projectId}
     param = {Constants.MERCHANTCODE:merchantCode}        
     twk = self._getRandomNumAndLetterAF(32)                
     rsaKey = self._createRSAPublicKey(Config.tmk)        
     param[Constants.TWK] = hexlify(rsa.encrypt(unhex(twk), rsaKey))
     pak["param"] = param
     pak_sort = json.dumps(pak,sort_keys=True)
     print "请求报文:%s"%pak_sort
     retStr = requests.post("http://192.168.6.34:10086/verify/verify.do",data=pak_sort)
     print "响应报文:%s"%retStr.text
     dict_results = json.loads(retStr.text)
     code = dict_results[Constants.CODE]
     #获取令牌失败
     if  not "00" == code:
         print "失败 code=%s;msg=%s;"%(code, dict_results[Constants.MSG])
     data = dict_results[Constants.DATA]
     token = data[Constants.TOKEN]
     wk = data[Constants.WK]
     t_des = triple_des(unhex(twk))
     wk = hexlify(t_des.decrypt(unhex(wk.encode('ascii'))))
     tokens = [token, twk, wk.strip()]
     print "返回数据:%s"%str(tokens)
     return tokens
    def test_signatures_v1(self):
        inp = unhex('1c94d7de000000019f1d6915ca8035e207292f3f4f88237da9876505dee100dfbda9fd1cd278d3590840109465e5ed347fdeb6fc2ca8c25fa5cf6e317d977f6c5209f46c30055f5c531c')
        key = unhex('1ee5eec12cfbf3cc311b855ddfddf913cff40b3a7dce058c4e46b5ba9026ba971a973144cbf180ceca7d35e1600048d414f7d5399b4ae46732c34d898fa68fbb0dbcea10d84201734e83c824d0f66207cf6f1b6a2ba13b9285329707facbc060')
        out = unhex('aa761d7d39c1503e3f4601f1e331787dca67794357650d76f6408fb9ea37f9eede1f45fcc741a3ec06e9d23be97eb1fbbcbe64bc6b2c010827469a8a0abbb008b11effefe95ddd558026dd2ce83838d7a087e71d8a98e5cbee59f9f788e99dbe7f9032912a4384af760c56da8d7a40ab057796ded052be17a69a6d14e703a621')

        version = TripleSec.VERSIONS[1]

        self.assertEqual(out, b''.join(TripleSec._generate_macs(inp, [key[:48], key[48:]], version)))
def __fulltest__():
    # This should not produce any unexpected errors or exceptions
    from binascii import unhexlify as unhex
    from binascii import hexlify as dohex
    __test__()
    print ""
    k = des("\0\0\0\0\0\0\0\0", CBC, "\0\0\0\0\0\0\0\0")
    d = k.encrypt("DES encryption algorithm")
    if k.decrypt(d) != "DES encryption algorithm":
        print "Test 1 Error: Unencypted data block does not match start data"
    k = des("\0\0\0\0\0\0\0\0", CBC, "\0\0\0\0\0\0\0\0")
    d = k.encrypt("Default string of text", '*')
    if k.decrypt(d, "*") != "Default string of text":
        print "Test 2 Error: Unencypted data block does not match start data"
    k = des("\r\n\tABC\r\n")
    d = k.encrypt("String to Pad", '*')
    if k.decrypt(d) != "String to Pad***":
        print "'%s'" % k.decrypt(d)
        print "Test 3 Error: Unencypted data block does not match start data"
    k = des("\r\n\tABC\r\n")
    d = k.encrypt(unhex("000102030405060708FF8FDCB04080"), unhex("44"))
    if k.decrypt(d, unhex("44")) != unhex("000102030405060708FF8FDCB04080"):
        print "Test 4a Error: Unencypted data block does not match start data"
    if k.decrypt(d) != unhex("000102030405060708FF8FDCB0408044"):
        print "Test 4b Error: Unencypted data block does not match start data"
    k = triple_des("MyDesKey\r\n\tABC\r\n0987*543")
    d = k.encrypt(unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"))
    if k.decrypt(d) != unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"):
        print "Test 5 Error: Unencypted data block does not match start data"
    k = triple_des("\r\n\tABC\r\n0987*543")
    d = k.encrypt(unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"))
    if k.decrypt(d) != unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"):
        print "Test 6 Error: Unencypted data block does not match start data"
Exemple #5
0
 def _payment(self, projectId, merchantCode, merPriKey, outUserId, outOrderId, 
             totalAmount, intoCardNo, intoCardName, intoCardType, bankCode, bankName,k):
     param={
             Constants.MERCHANTCODE:merchantCode,
             Constants.NONCESTR:self._getRandomLetterAndNum(32),
             Constants.OUTUSERID:outUserId,
             Constants.OUTORDERID:outOrderId,
             Constants.TOTALAMOUNT:totalAmount,
             Constants.INTOCARDNO:intoCardNo,
             Constants.INTOCARDNAME:intoCardName,
             Constants.INTOCARDTYPE:intoCardType,
             Constants.BANKCODE:bankCode,
             Constants.BANKNAME:bankName
            }
     #验证签名
     signFields = [Constants.MERCHANTCODE, Constants.NONCESTR, Constants.OUTORDERID,
     Constants.TOTALAMOUNT, Constants.INTOCARDNO, Constants.INTOCARDNAME, Constants.INTOCARDTYPE,
     Constants.BANKCODE, Constants.BANKNAME, Constants.OUTUSERID]
     #签名
     signFields.sort()
     signSrc = self._orgSignSrc(signFields, param)   
     #load java生成的 prikey失败,貌似是因为pyasn1 库有bug      
     priKey = self._createRSAPrivateKey(merPriKey)      
     param[Constants.SIGN] = hexlify(rsa.sign(signSrc,priKey,'MD5'))
     print "验证商户签名:%s"%str(rsa.verify(signSrc,unhex(param[Constants.SIGN]),self._createRSAPublicKey(Config.merPubKey)))
     print "商户 订单号 " + outOrderId
     src_json = json.dumps(param,sort_keys=True)
     print len(src_json)
     print  "3des加密数据:%s"%src_json
     #k[1]是16进制字串,需要转化为byte传入才能正确处理,python里3des key长度为16或24,接口服务不是按照python默认的解密来解析,这里需要手动增加长度
     #t_des = triple_des(unhex(k[1]),pad='0')#pad='0',padmode=PAD_PKCS5
     t_des = triple_des(unhex(k[1]))
     #转换成二进制数据的16进制表示再调用接口post传入
     src_byte = hexlify(src_json)
     if len(src_byte)%16 != 0:
         pad_len = 16 - len(src_byte)%16
         print "byte_len:%s"%str(len(src_byte))
         print "pad_len:%s"%str(pad_len)
         src_byte=src_byte+pad_len/2*hexlify('\x00')
         print len(src_byte)
         src_json=unhex(src_byte) 
     print len(src_byte)
     packChiper = hexlify(t_des.encrypt(src_json)) 
     #print "3des加密后密文%s"%packChiper
     print "3des解密数据:%s"%t_des.decrypt(t_des.encrypt(src_json)) 
     reqPak = {Constants.PROJECT_ID:projectId, 'param':json.dumps({Constants.TOKEN:k[0], Constants.MERCHANTCODE:merchantCode,Constants.PACKCHIPER:packChiper},sort_keys=True)}
     reqPak_sort = json.dumps(reqPak,sort_keys=True)
     print "出款 请求报文:" + reqPak_sort
     chukuan_ret = requests.post("http://192.168.6.34:10086/payment/payment.do",data=reqPak_sort)
     print "出款 应答报文:" + chukuan_ret.text        
Exemple #6
0
    def test_ciphers(self):
        s = triplesec.rndfile.read(100)
        k = triplesec.rndfile.read(32)
        for c in (triplesec.crypto.XSalsa20, triplesec.crypto.AES, triplesec.crypto.Twofish):
            self.assertEqual(s, c.decrypt(c.encrypt(s, k, c.generate_iv_data(triplesec.rndfile)), k), c.__name__)

        ciphertext = b'24-byte nonce for xsalsa' + unhex('002d4513843fc240c401e541')
        self.assertEqual(b'Hello world!', triplesec.crypto.XSalsa20.decrypt(ciphertext,
            b'this is 32-byte key for xsalsa20'))

        ciphertext = b'24-byte nonce for xsalsa' + unhex(
            '4848297feb1fb52fb66d81609bd547fabcbe7026edc8b5e5e449d088bfa69c088f5d8da1d791267c2c195a7f8cae9c4b4050d08ce6d3a151ec265f3a58e47648')
        self.assertEqual(b'\x00' * 64, triplesec.crypto.XSalsa20.decrypt(ciphertext,
            b'this is 32-byte key for xsalsa20'))
Exemple #7
0
def example_triple_des():
    from time import time

    # Utility module
    from binascii import unhexlify as unhex

    # example shows triple-des encryption using the des class
    print "Example of triple DES encryption in default ECB mode (DES-EDE3)\n"

    print "Triple des using the des class (3 times)"
    t = time()
    k1 = des(unhex("133457799BBCDFF1"))
    k2 = des(unhex("1122334455667788"))
    k3 = des(unhex("77661100DD223311"))
    d = "Triple DES test string, to be encrypted and decrypted..."
    print "Key1:      %s" % repr(k1.getKey())
    print "Key2:      %s" % repr(k2.getKey())
    print "Key3:      %s" % repr(k3.getKey())
    print "Data:      %s" % d

    e1 = k1.encrypt(d)
    e2 = k2.decrypt(e1)
    e3 = k3.encrypt(e2)
    print "Encrypted: " + repr(e3)

    d3 = k3.decrypt(e3)
    d2 = k2.encrypt(d3)
    d1 = k1.decrypt(d2)
    print "Decrypted: " + d1
    print "DES time taken: %f (%d crypt operations)" % (time() - t, 6 *
                                                        (len(d) / 8))
    print ""

    # Example below uses the triple-des class to achieve the same as above
    print "Now using triple des class"
    t = time()
    t1 = triple_des(unhex("133457799BBCDFF1112233445566778877661100DD223311"))
    print "Key:       %s" % repr(t1.getKey())
    print "Data:      %s" % d

    td1 = t1.encrypt(d)
    print "Encrypted: " + repr(td1)

    td2 = t1.decrypt(td1)
    print "Decrypted: " + td2

    print "Triple DES time taken: %f (%d crypt operations)" % (time() - t, 6 *
                                                               (len(d) / 8))
Exemple #8
0
 def decode(self, data: str, depth: int=0, tag: str=None):
     self._items.append(data if tag is None else _TaggedData(tag, data))
     data = bytearray(unhex(data))
     self._decode_func[depth](data)
     if len(data) > 0:
         print(data.hex())
     return self
Exemple #9
0
    def test_signatures_v1(self):
        inp = unhex(
            '1c94d7de000000019f1d6915ca8035e207292f3f4f88237da9876505dee100dfbda9fd1cd278d3590840109465e5ed347fdeb6fc2ca8c25fa5cf6e317d977f6c5209f46c30055f5c531c'
        )
        key = unhex(
            '1ee5eec12cfbf3cc311b855ddfddf913cff40b3a7dce058c4e46b5ba9026ba971a973144cbf180ceca7d35e1600048d414f7d5399b4ae46732c34d898fa68fbb0dbcea10d84201734e83c824d0f66207cf6f1b6a2ba13b9285329707facbc060'
        )
        out = unhex(
            'aa761d7d39c1503e3f4601f1e331787dca67794357650d76f6408fb9ea37f9eede1f45fcc741a3ec06e9d23be97eb1fbbcbe64bc6b2c010827469a8a0abbb008b11effefe95ddd558026dd2ce83838d7a087e71d8a98e5cbee59f9f788e99dbe7f9032912a4384af760c56da8d7a40ab057796ded052be17a69a6d14e703a621'
        )

        version = TripleSec.VERSIONS[1]

        self.assertEqual(
            out, b''.join(
                TripleSec._generate_macs(inp, [key[:48], key[48:]], version)))
Exemple #10
0
def tripleDesEncrypt(sourceData='',tripleDesKey = '1234567890ABCDEF1234567890ABCDEF'):
	result = ''
	print('source len = ',len(sourceData))	
	if(len(sourceData) <= 0 ):
		print('input data len error')
		return -1
	#将数据分成8个字节进行3DES加密,不足8个字节填充0x00补齐8个字节
	t1 = triple_des(unhex(tripleDesKey),CBC,b'\0\0\0\0\0\0\0\0',pad=None ,padmode=PAD_NORMAL)
	n = len(sourceData) / 8
	m = len(sourceData) % 8
	for i in range(0,int(n)+1):
		#result = t1.encrypt(tmp)
		#print(i,n)
		if int(n) == i:
			tmp = sourceData[i * 8 : ]
			tmp += '\0' * (8 - m) 
		else:
			tmp = sourceData[i * 8 : (i + 1)*8]
		#print('tmp len : ',len(tmp))
		d = t1.encrypt(tmp)
		result += bcdhexToaschex(d)
		print('d = %r' % d)
		print(t1.decrypt(d))
		#result += bcdhexToaschex(t1.encrypt(tmp))
		#print('result = %s' % result)
	return result
Exemple #11
0
 def replace_packet_attributes():
     # noinspection PyArgumentList
     data = self._data_producer(addr)
     if data:
         self._analyzer.decode_on(visitor, unhex(data))
     else:
         self._analyzer.create(visitor)
     self._analyzer.encode_on(visitor)
Exemple #12
0
def _example_triple_des_():
    from time import time

    # Utility module
    from binascii import unhexlify as unhex

    # example shows triple-des encryption using the des class
    print ("Example of triple DES encryption in default ECB mode (DES-EDE3)\n")

    print ("Triple des using the des class (3 times)")
    t = time()
    k1 = des(unhex("133457799BBCDFF1"))
    k2 = des(unhex("1122334455667788"))
    k3 = des(unhex("77661100DD223311"))
    d = "Triple DES test string, to be encrypted and decrypted..."
    print ("Key1:      %r" % k1.getKey())
    print ("Key2:      %r" % k2.getKey())
    print ("Key3:      %r" % k3.getKey())
    print ("Data:      %r" % d)

    e1 = k1.encrypt(d)
    e2 = k2.decrypt(e1)
    e3 = k3.encrypt(e2)
    print ("Encrypted: %r" % e3)

    d3 = k3.decrypt(e3)
    d2 = k2.encrypt(d3)
    d1 = k1.decrypt(d2)
    print ("Decrypted: %r" % d1)
    print ("DES time taken: %f (%d crypt operations)" % (time() - t, 6 * (len(d) / 8)))
    print ("")

    # Example below uses the triple-des class to achieve the same as above
    print ("Now using triple des class")
    t = time()
    t1 = triple_des(unhex("133457799BBCDFF1112233445566778877661100DD223311"))
    print ("Key:       %r" % t1.getKey())
    print ("Data:      %r" % d)

    td1 = t1.encrypt(d)
    print ("Encrypted: %r" % td1)

    td2 = t1.decrypt(td1)
    print ("Decrypted: %r" % td2)

    print ("Triple DES time taken: %f (%d crypt operations)" % (time() - t, 6 * (len(d) / 8)))
Exemple #13
0
def __fulltest__():
    # This should not produce any unexpected errors or exceptions
    from binascii import unhexlify as unhex
    from binascii import hexlify as dohex

    __test__()
    print ""

    k = des("\0\0\0\0\0\0\0\0", CBC, "\0\0\0\0\0\0\0\0")
    d = k.encrypt("DES encryption algorithm")
    if k.decrypt(d) != "DES encryption algorithm":
        print "Test 1 Error: Unencypted data block does not match start data"

    k = des("\0\0\0\0\0\0\0\0", CBC, "\0\0\0\0\0\0\0\0")
    d = k.encrypt("Default string of text", '*')
    if k.decrypt(d, "*") != "Default string of text":
        print "Test 2 Error: Unencypted data block does not match start data"

    k = des("\r\n\tABC\r\n")
    d = k.encrypt("String to Pad", '*')
    if k.decrypt(d) != "String to Pad***":
        print "'%s'" % k.decrypt(d)
        print "Test 3 Error: Unencypted data block does not match start data"

    k = des("\r\n\tABC\r\n")
    d = k.encrypt(unhex("000102030405060708FF8FDCB04080"), unhex("44"))
    if k.decrypt(d, unhex("44")) != unhex("000102030405060708FF8FDCB04080"):
        print "Test 4a Error: Unencypted data block does not match start data"
    if k.decrypt(d) != unhex("000102030405060708FF8FDCB0408044"):
        print "Test 4b Error: Unencypted data block does not match start data"

    k = triple_des("MyDesKey\r\n\tABC\r\n0987*543")
    d = k.encrypt(
        unhex(
            "000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"
        ))
    if k.decrypt(d) != unhex(
            "000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"
    ):
        print "Test 5 Error: Unencypted data block does not match start data"

    k = triple_des("\r\n\tABC\r\n0987*543")
    d = k.encrypt(
        unhex(
            "000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"
        ))
    if k.decrypt(d) != unhex(
            "000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"
    ):
        print "Test 6 Error: Unencypted data block does not match start data"
 def enbutttr(self):
     self.txt12.configure(state="normal")
     self.txt12.delete("1.0", "end")
     self.txt12.configure(state="disabled")
     self.trueorfalse.get()
     data = self.txt1.get("1.0", "end-1c")
     #Triple DES werkt alleen als de data een lengte heeft van 8 of een meerdere daarvan characters.
     #Dus als er de data dat niet heeft worden er puntkomma's achter geplakt.
     print(len(data))
     if len(data) % 8 != 0:
         n = 8 - (len(data) % 8)
         s = ";"
         i = 0
         while i < n:
             data += s
             i += 1
     else:
         pass
     if self.trueorfalse.get() == 0:
         try:
             #Bijna alles is het zelfde als bij normale DES alleen moet de key nu geschreven worden in hexadecimals.
             #Voor de hexadecimals moet wel unhex zodat de sleutel niet meer in hexadecimals staat.
             #Met hexadecimals zijn er veel meer mogelijkheden voor de sleutel.
             #Ook kan er dan voor worden gekozen om 3 keer DES te gebruiken.
             key = tripledes(
                 unhex("1231231231234567FACEAABBCCDDFACE5E1001005E890098"),
                 CBC)
             ed = key.encrypt(data)
             print(ed)
             self.txt12.configure(state="normal")
             self.txt12.insert("1.0", ed)
             self.txt12.configure(state="disabled")
         except ValueError:
             raise ValueError("Data cannot be used")
     else:
         try:
             key = tripledes(
                 unhex("1231231231234567FACEAABBCCDDFACE5E1001005E890098"),
                 ECB)
             ed = key.encrypt(data)
             self.txt12.configure(state="normal")
             self.txt12.insert("1.0", ed)
             self.txt12.configure(state="disabled")
         except ValueError:
             raise ValueError("Data cannot be used")
Exemple #15
0
 def test_bip32_derivation(self):
     for v, vector in enumerate(bip32_vectors):
         mk = hd.bip32.PrivateKey.from_seed(unhex(vector['seed']))
         for chain in vector['chain']:
             child = mk.child_path(chain['path'])
             self.assertEqual(child.serialize(), chain['xprv'],
                              '{} / {} / xprv'.format(v + 1, chain['path']))
             self.assertEqual(child.public().serialize(), chain['xpub'],
                              '{} / {} / xpub'.format(v + 1, chain['path']))
 def unpack_smart(self, device, timestamp, data):
     self.logger.debug("Unpacked %d bytes of smart data", len(data) / 2) #It's hex so each digit is only a nibble
     if len(data) == 0:
         self.logger.error("Length of data = 0, unable to proceed")
         return None
     RS485 = rs485_message.Rs485()
     try:
         RS485.ParseFromString(unhex(data))
     except DecodeError as e:
         self.logger.error("Unpacking buffer gave error %s", e)
         return None
     if RS485.type == rs485_message.Rs485.DATA:
         #this is the type we are expecting
         if RS485.sensor == rs485_message.Rs485.OW:
             self.logger.debug("One wire data")
             for S in RS485.ow:
                 SID = S.id
                 SV = S.value
                 if(248 < SV):          # It should be negative due to bug
                                         # AVR code
                     SV = -float(((int(SV * 16) ^ 0xFFFF)+1))/16
                 self.database.save_onewire_reading(device, timestamp, SID, SV)
                 self.logger.debug("Saved onewire reading to db %s, %s, %s", device, timestamp, SID)
         elif RS485.sensor == rs485_message.Rs485.TA_CHAIN:
             chain = RS485.tad
             self.logger.debug("Chain data")
             self.database.save_chain_reading(
                 device, timestamp, 
                 chain[0].temp, chain[0].pitch, chain[0].roll,
                 chain[1].temp, chain[1].pitch, chain[1].roll,
                 chain[2].temp, chain[2].pitch, chain[2].roll,
                 chain[3].temp, chain[3].pitch, chain[3].roll)
         elif RS485.sensor == rs485_message.Rs485.WP:
             self.logger.debug("WP data")
             if len(RS485.ad) < 2:
                 self.logger.error("Not enough data from waterpressure sensor")
                 return None
             ADC1 = RS485.ad[0].value
             ADC2 = RS485.ad[1].value
             if len(RS485.ad) >=3:
                 ADC3 = RS485.ad[2].value
                 if len(RS485.ad) >= 4:
                     ADC4 = RS485.ad[3].value
                 else:
                     ADC4 = None
             else:
                 ADC3 = None
                 ADC4 = None
             self.database.save_analog_smart_sensor_reading(device, timestamp, ADC1, ADC2, ADC3, ADC4)
             self.logger.debug("Saved analog smart sensor value to db %s %s", device, timestamp)
         else:
             self.logger.error("Unknown sensor type %d", RS485.sensor)
             return None
     else:
         self.logger.error("Unexpected message type %d". RS485.type)
         return None
     return True
Exemple #17
0
def load_inventory_content(file_name: str) -> Tuple[Item, ...]:
    factory = {
        'Item': Item,
        'ItemType': ItemType,
        'bytes': lambda value: unhex(value)
    }
    with open(file_name, 'r') as file:
        d = json.load(file)
        return _convert_to_namedtuple(d, factory)
Exemple #18
0
def tripleDesDecrypt(data,tripleDesKey = '1234567890ABCDEF1234567890ABCDEF' ):
	t1 = triple_des(unhex(tripleDesKey),CBC,b'\0\0\0\0\0\0\0\0',pad=None ,padmode=PAD_NORMAL)
	#print('input :', data)
	#bcd =  ascTobcdhex(data[0:16])
	bcd = bytes(data.encode())
	print('bdc = %r' % bcd)
	#print(bcd)
	result =  t1.decrypt(bcd)
	print(result)
	pass
Exemple #19
0
 def getTorrents(self):
     d = {}
     for f in os.listdir(self.dir_torrentcache):
         f = os.path.basename(f)
         try:
             f, garbage = f.split('.')
         except:
             pass
         d[unhex(f)] = 1
     return d.keys()
Exemple #20
0
 def getTorrents(self):
     d = {}
     for f in os.listdir(self.dir_torrentcache):
         f = os.path.basename(f)
         try:
             f, garbage = f.split('.')
         except:
             pass
         d[unhex(f)] = 1
     return d.keys()
Exemple #21
0
 def test_decrypt_invalid_data(self):
     regex = r'does not look like a TripleSec ciphertext'
     self.assertRaisesRegexp(TripleSecError, regex,
                             lambda: triplesec.decrypt(b'foo', b'xxx'))
     self.assertRaisesRegexp(
         TripleSecError, regex, lambda: triplesec.decrypt(
             unhex(b'1c94d7de00000003abcdef'), b'xxx'))
     self.assertRaisesRegexp(
         TripleSecError, regex,
         lambda: triplesec.decrypt(b'12345678901235' * 100, b'xxx'))
 def detrfile(self):
     filename = askopenfilename()
     f = open(filename, "rb+")
     data = f.read()
     f.close()
     key = tripledes(
         unhex("1231231231234567FACEAABBCCDDFACE5E1001005E890098"))
     data = key.decrypt(data, " ")
     f = open("TripleDESdecryptedfile.dec", "wb+")
     f.write(data)
     f.close()
    def _example_triple_des_(file_name):
        k1 = des(unhex("133457799BBCDFF1"))
        k2 = des(unhex("1122334455667788"))
        k3 = des(unhex("77661100DD223311"))
        with open(file_name, 'rb') as fo:
            d = fo.read()
        

        e1 = k1.encrypt(d,padmode=PAD_PKCS5)
        e2 = k2.decrypt(e1,padmode=PAD_PKCS5)
        e3 = k3.encrypt(e2,padmode=PAD_PKCS5)
        

    
        directory1="encrypted files"
        if not os.path.exists(directory1):
            os.makedirs(directory1)
        directory1=directory1+'/'
        with open(directory1+file_name+'.enc', 'wb') as fo:
            fo.write(e3)
Exemple #24
0
 def UnjumbleString(s):
     try:
         #bData = create_string_buffer(s)
         #bDataLen = c_int(len(s)
         #CryptDecrypt(keys[0][0], 0, True, 0, bData, byref(bDataLen))
         #dec_s = bData.raw[:bDataLen.value] #decrypted string may be shorter, but not longer
         #decr = DES3.new(unhex("ba64b0087ac48920529183d3572f806bae5715375bb59185"), DES3.MODE_CBC, unhex("0000000000000000"))
         key = hexlify(keys[0][2][12:])
         #print("Key: " + key)
         decr = DES3.new(unhex(key), DES3.MODE_CBC,
                         unhex("0000000000000000"))
         d = decr.decrypt(s)
         return zlib.decompress(d)
     except zlib.error:
         print 'Key failed. Attempting key switch.'
         del keys[0]
         if not keys:
             print >> sys.stderr, '!!! All keys failed. Exiting.'
             sys.exit(-1)
         return UnjumbleString(s)
Exemple #25
0
    def test_ciphers(self):
        s = triplesec.rndfile.read(100)
        k = triplesec.rndfile.read(32)
        for c in (triplesec.crypto.XSalsa20, triplesec.crypto.AES,
                  triplesec.crypto.Twofish):
            self.assertEqual(s, c.decrypt(c.encrypt(s, k), k), c.__name__)

        ciphertext = b'24-byte nonce for xsalsa' + unhex(
            '002d4513843fc240c401e541')
        self.assertEqual(
            b'Hello world!',
            triplesec.crypto.XSalsa20.decrypt(
                ciphertext, b'this is 32-byte key for xsalsa20'))

        ciphertext = b'24-byte nonce for xsalsa' + unhex(
            '4848297feb1fb52fb66d81609bd547fabcbe7026edc8b5e5e449d088bfa69c088f5d8da1d791267c2c195a7f8cae9c4b4050d08ce6d3a151ec265f3a58e47648'
        )
        self.assertEqual(
            b'\x00' * 64,
            triplesec.crypto.XSalsa20.decrypt(
                ciphertext, b'this is 32-byte key for xsalsa20'))
Exemple #26
0
    def get_support_data_item(self, support_data):
        if isinstance(support_data, str):
            support_data = SAPDiagSupportBits(unhex(support_data))

        if isinstance(support_data, SAPDiagSupportBits):
            support_data = SAPDiagItem(
                item_type="APPL", item_id="ST_USER", item_sid="SUPPORTDATA", item_value=support_data
            )

        if isinstance(support_data, SAPDiagItem):
            return support_data

        return None
Exemple #27
0
def load_packets(raknet_raw_file_name: str) -> DecodeAgent:
    import struct
    _agent = DecodeAgent(verbose=False)
    with open(raknet_raw_file_name, 'r') as file:
        for i, line in enumerate(file.readlines()):
            try:
                port_raw, data_raw = line.split()
                port, = struct.unpack('!H', unhex(port_raw))  # Don't remove comma, to get first one
                _agent.decode(data_raw, tag='L{}:{}'.format(i+1, port))
            except Exception as exc:
                exc.args = ('{}, line {}, in {}'.format(exc.args[0], i + 1, raknet_raw_file_name), )
                import traceback
                traceback.print_exc()
    return _agent
 def unpackall(self):
     unprocessed_data = self.database.get_all_unprocessed()
     no_records = len(unprocessed_data)
     self.logger.info("%d Records to process", no_records)
     for record in unprocessed_data:
         node = record.node
         self.logger.info("Processing node %s " % node)
         sample = readings.Sample()
         try:
             sample.ParseFromString(unhex(record.data[2:]))
         except DecodeError as e:
             self.logger.error(
                 "Unpacking %s gave error %s",
                 record.id, e)
             self.database.mark_processed(record.id)
             self.database.mark_corrupt(record.id)
             continue
         timestamp = datetime.utcfromtimestamp(sample.time)
         self.logger.info("Timestamp = %s" % timestamp)
         temperature = sample.temp
         if temperature < -100:
             temperature =  float((((int(temperature *4) ) ^ 0x1FF) +1))/4
         self.database.save_temperature(node, timestamp, temperature)
         power_mode = sample.WhichOneof("battery")
         self.logger.info("Got power mode %s" % power_mode)
         if "power" == power_mode:
             self.logger.info("Unpacking Power board")
             self.database.save_soc(node, timestamp, sample.power.soc)
             self.database.save_mppt(node, timestamp, float(sample.power.mppt)/10)
             self.database.save_solar_current(node, timestamp, float(sample.power.current)/1000)
             self.database.save_voltage(node, timestamp, float(sample.power.batt)/1000)
         elif "batt" == power_mode:
             self.logger.info("Using onboard ADC value for battery reading")
             self.database.save_voltage(node, timestamp, sample.batt)
         else:
             self.logger.warn("No voltage measurement type set (%s)" % node)
         # No longer have the accelerometer so no need to even bother storing data
         #self.database.save_accelerometer(
         #    node, timestamp,
         #    sample.accX, sample.accY, sample.accZ)
         if sample.HasField("ADC1"):
             self.database.save_adc(node, timestamp, 1, sample.ADC1)
         if sample.HasField("ADC2"):
             self.database.save_adc(node, timestamp, 2, sample.ADC2)
         if sample.HasField("rain"):
             self.database.save_rain(node, timestamp, sample.rain)
         if sample.HasField("AVR"):
             self.database.save_smart_reading(node, timestamp, sample.AVR)
         self.database.mark_processed(record.id)
         self.logger.info("Processed %d %s %s", record.id, node, timestamp)
Exemple #29
0
    def get_support_data_item(self, support_data):
        if isinstance(support_data, str):
            support_data = SAPDiagSupportBits(unhex(support_data))

        if isinstance(support_data, SAPDiagSupportBits):
            support_data = SAPDiagItem(item_type="APPL",
                                       item_id="ST_USER",
                                       item_sid="SUPPORTDATA",
                                       item_value=support_data)

        if isinstance(support_data, SAPDiagItem):
            return support_data

        return None
def _example_triple_des_():
    from time import time

    # Utility module
    from binascii import unhexlify as unhex
    from binascii import hexlify as hexe

    # example shows triple-des encryption using the des class
    print("Example of triple DES encryption in default ECB mode (DES-EDE3)\n")

    print("Triple des using the des class (3 times)")
    t = time()
    k1 = des(unhex("CA3A3E989AA7AE58"))
    k2 = des(unhex("EB806D4E20A6C744"))
    k3 = des(unhex("21735514632D155D"))
    d = b"9999999999999999"
    print("Key1:      %r" % k1.getKey())
    print("Key2:      %r" % k2.getKey())
    print("Key3:      %r" % k3.getKey())
    print("Data:      %r" % d)

    e1 = k1.encrypt(d)
    e2 = k2.decrypt(e1)
    e3 = k3.encrypt(e2)
    print("Encrypted: %r" % e3)

    print(type(d))
    print(hex(15))

    d3 = k3.decrypt(e3)
    d2 = k2.encrypt(d3)
    d1 = k1.decrypt(d2)
    print("Decrypted: %r" % d1)
    print((d1))
    print("DES time taken: %f (%d crypt operations)" % (time() - t, 6 *
                                                        (len(d) / 8)))
    print("")
Exemple #31
0
def generateKey():
	import uuid
	import sys
	from binascii import unhexlify as unhex
	if sys.platform == 'win32':
		mac = _ipconfig_getnode()
	else:
		mac = _ifconfig_getnode()
	if mac == None:
		mac = hex(_random_getnode())[2:-1]
	ud = uuid.uuid1()
	ud = ud.hex
	hi_time = ud[12:16]
	key = hi_time + mac
	return unhex(key)
Exemple #32
0
def load_recipe(file_name: str) -> Tuple[Recipe, ...]:
    factory = {
        'Recipe': Recipe,
        'RecipeType': RecipeType,
        'RecipeForNormal': RecipeForNormal,
        'RecipeForFurnace': RecipeForFurnace,
        'RecipeForMulti': RecipeForMulti,
        'Item': Item,
        'ItemType': ItemType,
        'UUID': lambda value: UUID(hex=value),
        'bytes': lambda value: unhex(value)
    }
    with open(file_name, 'r') as file:
        d = json.load(file)
        return _convert_to_namedtuple(d, factory)
Exemple #33
0
def generateKey():
    import uuid
    import sys
    from binascii import unhexlify as unhex
    if sys.platform == 'win32':
        mac = _ipconfig_getnode()
    else:
        mac = _ifconfig_getnode()
    if mac == None:
        mac = hex(_random_getnode())[2:-1]
    ud = uuid.uuid1()
    ud = ud.hex
    hi_time = ud[12:16]
    key = hi_time + mac
    return unhex(key)
Exemple #34
0
 def collect_packet(
         self, actual_data: bytes,
         addr: Address) -> Tuple[List[ValueObject], List[ValueObject]]:
     context = self._data_producer.get_context()
     collector_for_expected = _ExpectedPacketCollector(context)
     collector_for_actual = _ActualPacketCollector(context)
     # noinspection PyArgumentList
     data = self._data_producer(addr)
     if data:
         self._analyzer.decode_on(collector_for_expected, unhex(data))
     else:
         self._analyzer.create(collector_for_expected)
     self._analyzer.decode_on(collector_for_actual, actual_data)
     return list(collector_for_expected.get_packets()), list(
         collector_for_actual.get_packets())
Exemple #35
0
def unpacklatest(DB_CONFIG, LOG_LEVEL):
    logger = logging.getLogger("Latest unpacker")
    logger.setLevel(LOG_LEVEL)
    DB = FeshieDb(DB_CONFIG)
    RAW = DB.get_latest_unprocessed()
    SAMPLE = readings.Sample()
    print "node: %s" % RAW.node
    print "Recieved time: %s" % RAW.recieved_time
    print "Processed: %s" % RAW.processed
    print "Raw data:%s" % RAW.data
    #try:
    SAMPLE.ParseFromString(unhex(RAW.data[2:]))
    #except DecodeError:
     #   print("Unable to decode protocol buffer")
      #  return
    printReading(SAMPLE)
Exemple #36
0
    def changePIN(self):
        ##fpr is a global variable
        fpr = self.fpr
        challenge = json.dumps({'fingerprint': fpr})

        headers = {"Content-type": "application/json"}
        c = httplib.HTTPConnection('192.168.7.1:5000')
        c.request("POST", "/start_pin_change", challenge, headers)
        r = c.getresponse()

        if r.status == 200:
            d = r.read()
            data = json.loads(d)
            from binascii import unhexlify as unhex
            challenge = data['challenge']
            challenge = [ord(x) for x in list(unhex(challenge))]
            self.avr.sendPinChal(challenge)
            # AVR creates HMAC(key, challenge + pin) and sends it to ARM

            from time import sleep
            sleep(0.5)
            hmac = []
            while self.avr.get_status() != 0xA7:
                # read in hmac
                pass
            for i in range(64):
                hmac.append(self.avr.get_status())
            #hmac.append(self.avr.getByte())

            hmac = "".join([
                hex(x)[2:] if len(hex(x)) == 4 else "0" + hex(x)[2]
                for x in hmac
            ])
            data = json.dumps({'hash': hmac})
            headers = {"Content-type": "application/json"}
            c = httplib.HTTPConnection('192.168.7.1:5000')
            pin_change = json.dumps({'hash': hmac, 'fingerprint': fpr})
            c.request("POST", '/pin_change', pin_change, headers)

            r = c.getresponse()
            if r.status == 200:  #Server verifies the signature
                return True  #changePIN Complete
            else:
                return False
        else:
            return False
Exemple #37
0
def example_triple_des():
	from time import time

	# Utility module
	from binascii import unhexlify as unhex

	# example shows triple-des encryption using the des class
	#print "Example of triple DES encryption in default ECB mode (DES-EDE3)\n"

	#print "Triple des using the des class (3 times)"
	t = time()
	k1 = des(open("./key/16Key", "r").read())
	k2 = des(open("./key/16Key", "r").read())
	k3 = des(open("./key/16Key", "r").read())
	d = open("./text/10240Text", "r").read()
	#print "Key1:      %s" % k1.getKey()
	#print "Key2:      %s" % k2.getKey()
	#print "Key3:      %s" % k3.getKey()
	#print "Data:      %s" % d

	e1 = k1.encrypt(d)
	e2 = k2.decrypt(e1)
	e3 = k3.encrypt(e2)
	#print "Encrypted: " + e3

	d3 = k3.decrypt(e3)
	d2 = k2.encrypt(d3)
	d1 = k1.decrypt(d2)
	#print "Decrypted: " + d1
	#print "DES time taken: %f (%d crypt operations)" % (time() - t, 6 * (len(d) / 8))
	#print ""

	# Example below uses the triple-des class to achieve the same as above
	#print "Now using triple des class"
	t = time()
	t1 = triple_des(unhex("133457799BBCDFF1112233445566778877661100DD223311"))
	#print "Key:       %s" % t1.getKey()
	#print "Data:      %s" % d

	td1 = t1.encrypt(d)
	#print "Encrypted: " + td1

	td2 = t1.decrypt(td1)
	#print "Decrypted: " + td2

	print "Triple DES time taken: %f (%d crypt operations)" % (time() - t, 6 * (len(d) / 8))
Exemple #38
0
    def changePIN(self):
        ##fpr is a global variable
        fpr = self.fpr
        challenge = json.dumps({'fingerprint': fpr})
    
        headers = {"Content-type": "application/json"}
        c = httplib.HTTPConnection('192.168.7.1:5000')
        c.request("POST", "/start_pin_change", challenge, headers)
        r = c.getresponse()
    
        if r.status == 200: 
            d = r.read()
            data = json.loads(d)
            from binascii import unhexlify as unhex
            challenge = data['challenge']
            challenge = [ord(x) for x in list(unhex(challenge))]
            self.avr.sendPinChal(challenge)
            # AVR creates HMAC(key, challenge + pin) and sends it to ARM
            
            from time import sleep
            sleep(0.5) 
            hmac = []
            while self.avr.get_status() != 0xA7:
                # read in hmac    
                pass
            for i in range(64):
		        hmac.append(self.avr.get_status())
            #hmac.append(self.avr.getByte())
            
            hmac = "".join([ hex(x)[2:] if len(hex(x)) == 4 else "0"+hex(x)[2] for x in hmac])
            data = json.dumps({'hash': hmac})
            headers = {"Content-type": "application/json"}
            c = httplib.HTTPConnection('192.168.7.1:5000')
            pin_change = json.dumps({'hash': hmac, 'fingerprint': fpr})
            c.request("POST", '/pin_change', pin_change, headers)

            r = c.getresponse() 
            if r.status == 200:                #Server verifies the signature
                return True                 #changePIN Complete
            else:
                return False                 
        else:
            return False             
Exemple #39
0
    def unlock(self):
        fpr = self.fpr
        challenge = json.dumps({'fingerprint': fpr})
        headers = {"Content-type": "application/json"}
        c = httplib.HTTPConnection('192.168.7.1:5000')
        c.request("POST", "/start_unlock", challenge, headers)
        r = c.getresponse()
        if r.status == 200:  # Making sure communication with the server is performed correctly
            d = r.read()
            data = json.loads(d)
            challenge = data['challenge']
            from binascii import unhexlify as unhex
            challenge = [ord(x) for x in list(unhex(challenge))]
            self.avr.sendUnlockChal(challenge)
            # AVR creates HMAC(key, challenge + pin) and sends it to ARM

            hmac = []
            while self.avr.get_status() != 0xA4:
                pass
            for i in range(32):
                hmac.append(self.avr.getByte())

            hmac = "".join([
                hex(x)[2:] if len(hex(x)) == 4 else "0" + hex(x)[2]
                for x in hmac
            ])

            #  POST /unlock
            unlocking = json.dumps({'hash': hmac, 'fingerprint': fpr})
            c = httplib.HTTPConnection('192.168.7.1:5000')
            c.request("POST", "/unlock", unlocking, headers)
            r = c.getresponse()
            if r.status == 200:  #Server validates the request
                d = r.read()
                data = json.loads(d)
                flag = data['flag']
                return flag  #Unlock Complete
            else:
                return False
        else:
            return False
Exemple #40
0
 def unlock(self):
     fpr = self.fpr
     challenge = json.dumps({'fingerprint': fpr})
     headers = {"Content-type": "application/json"}
     c = httplib.HTTPConnection('192.168.7.1:5000')
     c.request("POST", "/start_unlock", challenge, headers)
     r = c.getresponse()
     if r.status == 200:  # Making sure communication with the server is performed correctly
         d = r.read()
         data = json.loads(d)
         challenge = data['challenge']
         from binascii import unhexlify as unhex
         challenge = [ord(x) for x in list(unhex(challenge))]
         self.avr.sendUnlockChal(challenge)
         # AVR creates HMAC(key, challenge + pin) and sends it to ARM
         
         hmac = []
         while self.avr.get_status() != 0xA4:
             pass
         for i in range(32):
             hmac.append(self.avr.getByte())
         
         hmac = "".join([ hex(x)[2:] if len(hex(x)) == 4 else "0"+hex(x)[2] for x in hmac])
         
         #  POST /unlock
         unlocking = json.dumps({'hash': hmac, 'fingerprint': fpr}) 
         c = httplib.HTTPConnection('192.168.7.1:5000')
         c.request("POST", "/unlock", unlocking, headers)
         r = c.getresponse()  
         if r.status == 200:        #Server validates the request
             d = r.read()
             data = json.loads(d)
             flag = data['flag']
             return flag            #Unlock Complete
         else:
             return False  
     else:
         return False 
Exemple #41
0
class _MagicData(DataCodec[bool]):
    """Check MAGIC data that is '00:ff:ff:00:fe:fe:fe:fe:fd:fd:fd:fd:12:34:56:78'.

    >>> c = _MagicData()
    >>> data = bytearray()
    >>> context = DataCodecContext()
    >>> c.write(data, True, context)
    >>> context.length
    16
    >>> hexlify(data)
    b'00ffff00fefefefefdfdfdfd12345678'
    >>> context.clear()
    >>> c.read(data, context)
    True
    >>> context.length
    16
    >>> hexlify(data)
    b''
    >>> c.read(bytearray(b'ffffff00fefefefefdfdfdfd12345678'), context)
    False
    """

    BYTES = unhex(b'00ffff00fefefefefdfdfdfd12345678')

    _LENGTH = len(BYTES)

    def read(self, data: bytearray, context: DataCodecContext) -> bool:
        d = pop_first(data, self._LENGTH)
        context.length += self._LENGTH
        return d == _MagicData.BYTES

    def write(self, data: bytearray, is_valid: bool,
              context: DataCodecContext) -> None:
        assert is_valid
        data += _MagicData.BYTES
        context.length += self._LENGTH
Exemple #42
0
 def send(self, data_producer: Callable[[Address], str],
          from_: Address) -> None:
     self._protocol.datagram_received(unhex(data_producer(from_)), from_)
Exemple #43
0
# Support Bits for common SAP Software versions
#
# SAPGUI 7.02 Java rev 5:           ff7ffe2ddab737d674087e1305971597eff23f8d0770ff0f0000000000000000
# SAPGUI 7.02 Java rev 2:           ff7ffe2ddab737d674087e1305971597eff23f8d0770ff030000000000000000
# SAPGUI 7.40 Java rev 8:           ff7ffe2ddab737f674087e9305971597eff2bf8f4f71ff9f8606000000000000
# SAPGUI 7.02 Windows:              ff7ffa0d78b737def6196e9325bf1593ef73feebdb51ed010000000000000000
# SAPGUI 7.01 Windows:              ff7ffa0d78b737def6196e9325bf1593ef73feebdb5501000000000000000000
# SAPGUI 7.30 Windows:              ff7ffa0d78b737def6196e9325bf1597ef73feebdb51ed910200000000000000
# SAPGUI 7.40 Windows:              ff7ffa0d78b737def6196e9325bf1597ef73feebdb51ed91ca00000000000000
#
# SAP EHP 1 for SAP Netweaver 7.0:  ff7ffe2dd8b737d674087e1305971597ebf22f8d03300f000000000000000000
# SAP EHP 2 for SAP NetWeaver 7.0:  ff7ffe2dd8b737d674087e1305971597ebf23f8d0370ff0f0000000000000000
# SAP NetWeaver AS ABAP 7.50 SP02:  ff7ffe2dd8b737f674087e9305971597ebf2bf8f4b71ff9f8606000000000000

support_data_sapgui_701_win = SAPDiagSupportBits(
    unhex("ff7ffa0d78b737def6196e9325bf1593ef73feebdb5501000000000000000000")
)
support_data_sapgui_702_win = SAPDiagSupportBits(
    unhex("ff7ffa0d78b737def6196e9325bf1593ef73feebdb51ed010000000000000000")
)
support_data_sapgui_730_win = SAPDiagSupportBits(
    unhex("ff7ffa0d78b737def6196e9325bf1597ef73feebdb51ed910200000000000000")
)
support_data_sapgui_740_win = SAPDiagSupportBits(
    unhex("ff7ffa0d78b737def6196e9325bf1597ef73feebdb51ed91ca00000000000000")
)
support_data_sapgui_702_java2 = SAPDiagSupportBits(
    unhex("ff7ffe2ddab737d674087e1305971597eff23f8d0770ff030000000000000000")
)
support_data_sapgui_702_java5 = SAPDiagSupportBits(
    unhex("ff7ffe2ddab737d674087e1305971597eff23f8d0770ff0f0000000000000000")
Exemple #44
0
bind_diagitem(SAPDiagSupportBits, "APPL", 0x06, 0x11)

# Support Bits for common SAP Software versions
#
# SAPGUI 7.02 Java rev 5:           ff7ffe2ddab737d674087e1305971597eff23f8d0770ff0f0000000000000000
# SAPGUI 7.02 Java rev 2:           ff7ffe2ddab737d674087e1305971597eff23f8d0770ff030000000000000000
# SAPGUI 7.02 Windows:              ff7ffa0d78b737def6196e9325bf1593ef73feebdb51ed010000000000000000
# SAPGUI 7.01 Windows:              ff7ffa0d78b737def6196e9325bf1593ef73feebdb5501000000000000000000
# SAPGUI 7.30 Windows:              ff7ffa0d78b737def6196e9325bf1597ef73feebdb51ed910200000000000000
#
# SAP EHP 1 for SAP Netweaver 7.0:  ff7ffe2dd8b737d674087e1305971597ebf22f8d03300f000000000000000000
# SAP EHP 2 for SAP NetWeaver 7.0:  ff7ffe2dd8b737d674087e1305971597ebf23f8d0370ff0f0000000000000000
#

support_data_sapgui_701_win = SAPDiagSupportBits(
    unhex("ff7ffa0d78b737def6196e9325bf1593ef73feebdb5501000000000000000000"))
support_data_sapgui_702_win = SAPDiagSupportBits(
    unhex("ff7ffa0d78b737def6196e9325bf1593ef73feebdb51ed010000000000000000"))
support_data_sapgui_730_win = SAPDiagSupportBits(
    unhex("ff7ffa0d78b737def6196e9325bf1597ef73feebdb51ed910200000000000000"))
support_data_sapgui_702_java2 = SAPDiagSupportBits(
    unhex("ff7ffe2ddab737d674087e1305971597eff23f8d0770ff030000000000000000"))
support_data_sapgui_702_java5 = SAPDiagSupportBits(
    unhex("ff7ffe2ddab737d674087e1305971597eff23f8d0770ff0f0000000000000000"))
support_data_sapnw_701 = SAPDiagSupportBits(
    unhex("ff7ffe2dd8b737d674087e1305971597ebf22f8d03300f000000000000000000"))
support_data_sapnw_702 = SAPDiagSupportBits(
    unhex("ff7ffe2dd8b737d674087e1305971597ebf23f8d0370ff0f0000000000000000"))

support_data = SAPDiagItem(item_type="APPL",
                           item_id="ST_USER",
Exemple #45
0
def TDES_Encrypt (the_stream):
    tdes = triple_des(unhex(shared_key))
    return tdes.encrypt(the_stream,pad="\0")
Exemple #46
0
def postprocess_value(tokens, property, line=0, col=0):
    """
    """
    tokens = trim_extra(tokens)
    
    if len(tokens) >= 2 and (tokens[-2] == ('CHAR', '!')) and (tokens[-1] == ('IDENT', 'important')):
        important = True
        tokens = trim_extra(tokens[:-2])

    else:
        important = False
    
    if properties[property.name] in (int, float) and len(tokens) == 2 and tokens[0] == ('CHAR', '-') and tokens[1][0] == 'NUMBER':
        # put the negative sign on the number
        tokens = [(tokens[1][0], '-' + tokens[1][1])]
    
    value = tokens
    
    if properties[property.name] in (int, float, str, color, uri, boolean) or type(properties[property.name]) is tuple:
        if len(tokens) != 1:
            raise ParseException('Single value only for property "%(property)s"' % locals(), line, col)

    if properties[property.name] is int:
        if tokens[0][0] != 'NUMBER':
            raise ParseException('Number value only for property "%(property)s"' % locals(), line, col)

        value = int(tokens[0][1])

    elif properties[property.name] is float:
        if tokens[0][0] != 'NUMBER':
            raise ParseException('Number value only for property "%(property)s"' % locals(), line, col)

        value = float(tokens[0][1])

    elif properties[property.name] is str:
        if tokens[0][0] != 'STRING':
            raise ParseException('String value only for property "%(property)s"' % locals(), line, col)

        value = str(tokens[0][1][1:-1])

    elif properties[property.name] is color_transparent:
        if tokens[0][0] != 'HASH' and (tokens[0][0] != 'IDENT' or tokens[0][1] != 'transparent'):
            raise ParseException('Hash or transparent value only for property "%(property)s"' % locals(), line, col)

        if tokens[0][0] == 'HASH':
            if not re.match(r'^#([0-9a-f]{3}){1,2}$', tokens[0][1], re.I):
                raise ParseException('Unrecognized color value for property "%(property)s"' % locals(), line, col)
    
            hex = tokens[0][1][1:]
            
            if len(hex) == 3:
                hex = hex[0]+hex[0] + hex[1]+hex[1] + hex[2]+hex[2]
            
            rgb = (ord(unhex(h)) for h in (hex[0:2], hex[2:4], hex[4:6]))
            
            value = color(*rgb)

        else:
            value = 'transparent'

    elif properties[property.name] is color:
        if tokens[0][0] != 'HASH':
            raise ParseException('Hash value only for property "%(property)s"' % locals(), line, col)

        if not re.match(r'^#([0-9a-f]{3}){1,2}$', tokens[0][1], re.I):
            raise ParseException('Unrecognized color value for property "%(property)s"' % locals(), line, col)

        hex = tokens[0][1][1:]
        
        if len(hex) == 3:
            hex = hex[0]+hex[0] + hex[1]+hex[1] + hex[2]+hex[2]
        
        rgb = (ord(unhex(h)) for h in (hex[0:2], hex[2:4], hex[4:6]))
        
        value = color(*rgb)

    elif properties[property.name] is uri:
        if tokens[0][0] != 'URI':
            raise ParseException('URI value only for property "%(property)s"' % locals(), line, col)

        raw = str(tokens[0][1])

        if raw.startswith('url("') and raw.endswith('")'):
            raw = raw[5:-2]
            
        elif raw.startswith("url('") and raw.endswith("')"):
            raw = raw[5:-2]
            
        elif raw.startswith('url(') and raw.endswith(')'):
            raw = raw[4:-1]

        value = uri(raw)
            
    elif properties[property.name] is boolean:
        if tokens[0][0] != 'IDENT' or tokens[0][1] not in ('true', 'false'):
            raise ParseException('true/false value only for property "%(property)s"' % locals(), line, col)

        value = boolean(tokens[0][1] == 'true')
            
    elif type(properties[property.name]) is tuple:
        if tokens[0][0] != 'IDENT':
            raise ParseException('Identifier value only for property "%(property)s"' % locals(), line, col)

        if tokens[0][1] not in properties[property.name]:
            raise ParseException('Unrecognized value for property "%(property)s"' % locals(), line, col)

        value = str(tokens[0][1])
            
    elif properties[property.name] is numbers:
        values = []
        
        # strip the list down to what we think goes number, comma, number, etc.
        relevant_tokens = [token for token in tokens
                           if token[0] == 'NUMBER' or token == ('CHAR', ',')]
        
        for (i, token) in enumerate(relevant_tokens):
            if (i % 2) == 0 and token[0] == 'NUMBER':
                try:
                    value = int(token[1])
                except ValueError:
                    value = float(token[1])

                values.append(value)

            elif (i % 2) == 1 and token[0] == 'CHAR':
                # fine, it's a comma
                continue

            else:
                raise ParseException('Value for property "%(property)s" should be a comma-delimited list of numbers' % locals(), line, col)

        value = numbers(*values)

    return Value(value, important)
Exemple #47
0
def postprocess_value(property, tokens, important, line, col):
    """ Convert a list of property value tokens into a single Value instance.
    
        Values can be numbers, strings, colors, uris, or booleans:
        http://www.w3.org/TR/CSS2/syndata.html#values
    """
    #
    # Helper function.
    #
    
    def combine_negative_numbers(tokens, line, col):
        """ Find negative numbers in a list of tokens, return a new list.
        
            Negative numbers come as two tokens, a minus sign and a number.
        """
        tokens, original_tokens = [], iter(tokens)
        
        while True:
            try:
                tname, tvalue = original_tokens.next()[:2]
                
                if (tname, tvalue) == ('CHAR', '-'):
                    tname, tvalue = original_tokens.next()[:2]
    
                    if tname == 'NUMBER':
                        # minus sign with a number is a negative number
                        tokens.append(('NUMBER', '-'+tvalue))
                    else:
                        raise ParseException('Unexpected non-number after a minus sign', line, col)
    
                else:
                    tokens.append((tname, tvalue))
    
            except StopIteration:
                break
        
        return tokens
    
    #
    # The work.
    #
    
    tokens = combine_negative_numbers(tokens, line, col)
    
    if properties[property.name] in (int, float, str, color, uri, boolean) or type(properties[property.name]) is tuple:
        if len(tokens) != 1:
            raise ParseException('Single value only for property "%(property)s"' % locals(), line, col)

    if properties[property.name] is int:
        if tokens[0][0] != 'NUMBER':
            raise ParseException('Number value only for property "%(property)s"' % locals(), line, col)

        value = int(tokens[0][1])

    elif properties[property.name] is float:
        if tokens[0][0] != 'NUMBER':
            raise ParseException('Number value only for property "%(property)s"' % locals(), line, col)

        value = float(tokens[0][1])

    elif properties[property.name] is str:
        if tokens[0][0] != 'STRING':
            raise ParseException('String value only for property "%(property)s"' % locals(), line, col)

        value = str(tokens[0][1][1:-1])

    elif properties[property.name] is color_transparent:
        if tokens[0][0] != 'HASH' and (tokens[0][0] != 'IDENT' or tokens[0][1] != 'transparent'):
            raise ParseException('Hash or transparent value only for property "%(property)s"' % locals(), line, col)

        if tokens[0][0] == 'HASH':
            if not re.match(r'^#([0-9a-f]{3}){1,2}$', tokens[0][1], re.I):
                raise ParseException('Unrecognized color value for property "%(property)s"' % locals(), line, col)
    
            hex = tokens[0][1][1:]
            
            if len(hex) == 3:
                hex = hex[0]+hex[0] + hex[1]+hex[1] + hex[2]+hex[2]
            
            rgb = (ord(unhex(h)) for h in (hex[0:2], hex[2:4], hex[4:6]))
            
            value = color(*rgb)

        else:
            value = 'transparent'

    elif properties[property.name] is color:
        if tokens[0][0] != 'HASH':
            raise ParseException('Hash value only for property "%(property)s"' % locals(), line, col)

        if not re.match(r'^#([0-9a-f]{3}){1,2}$', tokens[0][1], re.I):
            raise ParseException('Unrecognized color value for property "%(property)s"' % locals(), line, col)

        hex = tokens[0][1][1:]
        
        if len(hex) == 3:
            hex = hex[0]+hex[0] + hex[1]+hex[1] + hex[2]+hex[2]
        
        rgb = (ord(unhex(h)) for h in (hex[0:2], hex[2:4], hex[4:6]))
        
        value = color(*rgb)

    elif properties[property.name] is uri:
        if tokens[0][0] != 'URI':
            raise ParseException('URI value only for property "%(property)s"' % locals(), line, col)

        raw = str(tokens[0][1])

        if raw.startswith('url("') and raw.endswith('")'):
            raw = raw[5:-2]
            
        elif raw.startswith("url('") and raw.endswith("')"):
            raw = raw[5:-2]
            
        elif raw.startswith('url(') and raw.endswith(')'):
            raw = raw[4:-1]

        value = uri(raw)
            
    elif properties[property.name] is boolean:
        if tokens[0][0] != 'IDENT' or tokens[0][1] not in ('true', 'false'):
            raise ParseException('true/false value only for property "%(property)s"' % locals(), line, col)

        value = boolean(tokens[0][1] == 'true')
            
    elif type(properties[property.name]) is tuple:
        if tokens[0][0] != 'IDENT':
            raise ParseException('Identifier value only for property "%(property)s"' % locals(), line, col)

        if tokens[0][1] not in properties[property.name]:
            raise ParseException('Unrecognized value for property "%(property)s"' % locals(), line, col)

        value = str(tokens[0][1])
            
    elif properties[property.name] is numbers:
        values = []
        
        # strip spaces from the list
        relevant_tokens = [token for token in tokens if token[0] != 'S']
        
        for (i, token) in enumerate(relevant_tokens):
            if (i % 2) == 0 and token[0] == 'NUMBER':
                try:
                    value = int(token[1])
                except ValueError:
                    value = float(token[1])

                values.append(value)

            elif (i % 2) == 1 and token[0] == 'CHAR':
                # fine, it's a comma
                continue

            else:
                raise ParseException('Value for property "%(property)s" should be a comma-delimited list of numbers' % locals(), line, col)

        value = numbers(*values)

    elif properties[property.name] is strings:
        values = []
    
        # strip spaces from the list
        relevant_tokens = [token for token in tokens if token[0] != 'S']
        
        for (i, token) in enumerate(relevant_tokens):
            if (i % 2) == 0 and token[0] == 'STRING':
                values.append(str(token[1][1:-1]))
            
            elif (i % 2) == 1 and token == ('CHAR', ','):
                # fine, it's a comma
                continue
            
            else:
                raise ParseException('Value for property "%(property)s" should be a comma-delimited list of strings' % locals(), line, col)
    
        value = strings(*values)

    return Value(value, important)
Exemple #48
0
def _fulltest_():
    # This should not produce any unexpected errors or exceptions
    from time import time
    from binascii import unhexlify as unhex
    from binascii import hexlify as dohex

    t = time()

    data = "DES encryption algorithm".encode('ascii')
    k = des("\0\0\0\0\0\0\0\0", CBC, "\0\0\0\0\0\0\0\0")
    d = k.encrypt(data)
    if k.decrypt(d) != data:
        print ("Test 1:  Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 1:  Successful")

    data = "Default string of text".encode('ascii')
    k = des("\0\0\0\0\0\0\0\0", CBC, "\0\0\0\0\0\0\0\0")
    d = k.encrypt(data, "*")
    if k.decrypt(d, "*") != data:
        print ("Test 2:  Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 2:  Successful")

    data = "String to Pad".encode('ascii')
    k = des("\r\n\tABC\r\n")
    d = k.encrypt(data, "*")
    if k.decrypt(d, "*") != data:
        print ("Test 3:  Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 3:  Successful")

    k = des("\r\n\tABC\r\n")
    d = k.encrypt(unhex("000102030405060708FF8FDCB04080"), unhex("44"))
    if k.decrypt(d, unhex("44")) != unhex("000102030405060708FF8FDCB04080"):
        print ("Test 4a: Error: Unencypted data block does not match start data")
    elif k.decrypt(d) != unhex("000102030405060708FF8FDCB0408044"):
        print ("Test 4b: Error: Unencypted data block does not match start data")
    else:
        print ("Test 4:  Successful")

    data = "String to Pad".encode('ascii')
    k = des("\r\n\tkey\r\n")
    d = k.encrypt(data, padmode=PAD_PKCS5)
    if k.decrypt(d, padmode=PAD_PKCS5) != data:
        print ("Test 5a: Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    # Try same with padmode set on the class instance.
    k = des("\r\n\tkey\r\n", padmode=PAD_PKCS5)
    d = k.encrypt(data)
    if k.decrypt(d) != data:
        print ("Test 5b: Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 5:  Successful")

    k = triple_des("MyDesKey\r\n\tABC\r\n0987*543")
    d = k.encrypt(unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"))
    if k.decrypt(d) != unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"):
        print ("Test 6:  Error: Unencypted data block does not match start data")
    else:
        print ("Test 6:  Successful")

    k = triple_des("\r\n\tABC\r\n0987*543")
    d = k.encrypt(unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"))
    if k.decrypt(d) != unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"):
        print ("Test 7:  Error: Unencypted data block does not match start data")
    else:
        print ("Test 7:  Successful")

    k = triple_des("MyDesKey\r\n\tABC\r\n0987*54B", CBC, "12341234")
    d = k.encrypt(unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"))
    if k.decrypt(d) != unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"):
        print ("Test 8:  Error: Triple DES CBC failed.")
    else:
        print ("Test 8:  Successful")

    k = triple_des("MyDesKey\r\n\tABC\r\n0987*54B", CBC, "12341234")
    d = k.encrypt(unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDC"), '.')
    if k.decrypt(d, '.') != unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDC"):
        print ("Test 9:  Error: Triple DES CBC with padding failed.")
    else:
        print ("Test 9:  Successful")

    k = triple_des("\r\n\tkey\rIsGoodKey")
    data = "String to Pad".encode('ascii')
    d = k.encrypt(data, padmode=PAD_PKCS5)
    if k.decrypt(d, padmode=PAD_PKCS5) != data:
        print ("Test 10: Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 10: Successful")

    k = triple_des("\r\n\tkey\rIsGoodKey")
    data = "String not need Padding.".encode('ascii')
    d = k.encrypt(data, padmode=PAD_PKCS5)
    if k.decrypt(d, padmode=PAD_PKCS5) != data:
        print ("Test 11: Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 11: Successful")

    # Test PAD_PKCS5 with CBC encryption mode.

    k = des("IGoodKey", mode=CBC, IV="\0\1\2\3\4\5\6\7")
    data = "String to Pad".encode('ascii')
    d = k.encrypt(data, padmode=PAD_PKCS5)
    if k.decrypt(d, padmode=PAD_PKCS5) != data:
        print ("Test 12: Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 12: Successful")

    k = des("IGoodKey", mode=CBC, IV="\0\1\2\3\4\5\6\7")
    data = "String not need Padding.".encode('ascii')
    d = k.encrypt(data, padmode=PAD_PKCS5)
    if k.decrypt(d, padmode=PAD_PKCS5) != data:
        print ("Test 13: Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 13: Successful")

    k = triple_des("\r\n\tkey\rIsGoodKey", mode=CBC, IV="\0\1\2\3\4\5\6\7")
    data = "String to Pad".encode('ascii')
    d = k.encrypt(data, padmode=PAD_PKCS5)
    if k.decrypt(d, padmode=PAD_PKCS5) != data:
        print ("Test 14: Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 14: Successful")

    k = triple_des("\r\n\tkey\rIsGoodKey", mode=CBC, IV="\0\1\2\3\4\5\6\7")
    data = "String not need Padding.".encode('ascii')
    d = k.encrypt(data, padmode=PAD_PKCS5)
    if k.decrypt(d, padmode=PAD_PKCS5) != data:
        print ("Test 15: Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 15: Successful")

    k = triple_des("\r\n\tkey\rIsGoodKey", mode=CBC, IV="\0\1\2\3\4\5\6\7", padmode=PAD_PKCS5)
    data = "String to Pad".encode('ascii')
    d = k.encrypt(data)
    if k.decrypt(d) != data:
        print ("Test 16: Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 16: Successful")

    # Ensure no error occurs when creating an instance with no IV yet set,
    # test supplied by "Yoav Aner".
    k = triple_des("\0" * 24, mode=CBC, pad=None, padmode=PAD_PKCS5)
    data = "String to Pad".encode('ascii')
    d = k.encrypt(data)
    if k.decrypt(d) != data:
        print ("Test 17: Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 17: Successful")

    print ("")
    print ("Total time taken: %f" % (time() - t))
Exemple #49
0
bind_diagitem(SAPDiagSupportBits, "APPL", 0x06, 0x11)


# Support Bits for common SAP Software versions
#
# SAPGUI 7.02 Java rev 5:           ff7ffe2ddab737d674087e1305971597eff23f8d0770ff0f0000000000000000
# SAPGUI 7.02 Java rev 2:           ff7ffe2ddab737d674087e1305971597eff23f8d0770ff030000000000000000
# SAPGUI 7.02 Windows:              ff7ffa0d78b737def6196e9325bf1593ef73feebdb51ed010000000000000000
# SAPGUI 7.01 Windows:              ff7ffa0d78b737def6196e9325bf1593ef73feebdb5501000000000000000000
# SAPGUI 7.30 Windows:              ff7ffa0d78b737def6196e9325bf1597ef73feebdb51ed910200000000000000
#
# SAP EHP 1 for SAP Netweaver 7.0:  ff7ffe2dd8b737d674087e1305971597ebf22f8d03300f000000000000000000
# SAP EHP 2 for SAP NetWeaver 7.0:  ff7ffe2dd8b737d674087e1305971597ebf23f8d0370ff0f0000000000000000
#

support_data_sapgui_701_win = SAPDiagSupportBits(unhex("ff7ffa0d78b737def6196e9325bf1593ef73feebdb5501000000000000000000"))
support_data_sapgui_702_win = SAPDiagSupportBits(unhex("ff7ffa0d78b737def6196e9325bf1593ef73feebdb51ed010000000000000000"))
support_data_sapgui_730_win = SAPDiagSupportBits(unhex("ff7ffa0d78b737def6196e9325bf1597ef73feebdb51ed910200000000000000"))
support_data_sapgui_702_java2 = SAPDiagSupportBits(unhex("ff7ffe2ddab737d674087e1305971597eff23f8d0770ff030000000000000000"))
support_data_sapgui_702_java5 = SAPDiagSupportBits(unhex("ff7ffe2ddab737d674087e1305971597eff23f8d0770ff0f0000000000000000"))
support_data_sapnw_701 = SAPDiagSupportBits(unhex("ff7ffe2dd8b737d674087e1305971597ebf22f8d03300f000000000000000000"))
support_data_sapnw_702 = SAPDiagSupportBits(unhex("ff7ffe2dd8b737d674087e1305971597ebf23f8d0370ff0f0000000000000000"))

support_data = SAPDiagItem(item_type="APPL",
                           item_id="ST_USER",
                           item_sid="SUPPORTDATA",
                           item_value=support_data_sapgui_702_java5)


# Dynt Atom item types
diag_atom_etypes = {
Exemple #50
0
 def test_decrypt_invalid_data(self):
     regex = r'does not look like a TripleSec ciphertext'
     self.assertRaisesRegexp(TripleSecError, regex, lambda: triplesec.decrypt(b'foo', b'xxx'))
     self.assertRaisesRegexp(TripleSecError, regex, lambda: triplesec.decrypt(unhex(b'1c94d7de00000003abcdef'), b'xxx'))
     self.assertRaisesRegexp(TripleSecError, regex, lambda: triplesec.decrypt(b'12345678901235'*100, b'xxx'))
Exemple #51
0
	def fuzzer(self,host,port,minim,maxm,salt,timeout):
		fuzzUDP(host,port,minim,maxm,salt,timeout,"TFTP")
		# Stage 1
		for opcode in stage_1:
			printCommand(opcode[0])
			for length in range(minim, maxm+1, salt):
				payloadCount(minim,maxm,length)
				pattern = createPattern(length)
				payload = unhex(opcode[1][2:]) + pattern + unhex(null[1][2:]) + mode[1] + unhex(null[1][2:])
				spattern = opcode[1] + opcode[0] + " + " + pattern + somefile[0] + " + " + null[1] + null[0] + " + " + mode[1] + mode[0] +  " + " + null[1] + null[0]
				sock = createSocketUDP(host,port,"TFTP",spattern,length,timeout)
				sendDataUDP(sock,host,port,"TFTP",payload,spattern,length,timeout,1)
			printCommand("(Mode) with" + opcode[0])
			for length in range(minim, maxm+1, salt):
				payloadCount(minim,maxm,length)
				pattern = createPattern(length)
				payload = unhex(opcode[1][2:]) + somefile[1] + unhex(null[1][2:]) + pattern + unhex(null[1][2:])
				spattern = opcode[1] + opcode[0] + " + " + somefile[1] + somefile[0] +  " + " + null[1] + null[0] + " + " + pattern + mode[0] + " + " + null[1] + null[0]
				sock = createSocketUDP(host,port,"TFTP",spattern,length,timeout)
				sendDataUDP(sock,host,port,"TFTP",payload,spattern,length,timeout,1)
		# Stage 2
		for opcode in stage_2:
			printCommand(opcode[0])
			for length in range(minim, maxm+1, salt):
				payloadCount(minim,maxm,length)
				pattern = createPattern(length)
				payload = unhex(opcode[1][2:]) + unhex(block[1][2:]) + pattern + unhex(null[1][2:])
				spattern = opcode[1] + opcode[0] + " + " + block[1] + block[0] + " + " + pattern + opcode[0] + " + " + null[1] + null[0]
				sock = createSocketUDP(host,port,"TFTP",spattern,length,timeout)
				sendDataUDP(sock,host,port,"TFTP",payload,spattern,length,timeout,1)

		# Stage 3
		for opcode in stage_3:
			for error_opcode in error_opcodes:
				printCommand(opcode[0] + " with" + error_opcode[0])
				for length in range(minim, maxm+1, salt):
					payloadCount(minim,maxm,length)
					pattern = createPattern(length)
					payload = unhex(opcode[1][2:]) + unhex(error_opcode[1][2:]) + pattern + unhex(null[1][2:])
					spattern = opcode[1] + opcode[0] + " + " + error_opcode[1] + error_opcode[0] + " + " + pattern + " (Error String)" + " + " + null[1] + null[0]
					sock = createSocketUDP(host,port,"TFTP",spattern,length,timeout)
					sendDataUDP(sock,host,port,"TFTP",payload,spattern,length,timeout,1)
		exitProgram(2)
Exemple #52
0
import socket
import os
import uuid
import time
import xlwt

import base64
from icon import img

from pyDes import *
from binascii import unhexlify as unhex
from binascii import b2a_hex, a2b_hex

import paramiko

kk = triple_des(unhex("201809229378ABCDEF9921ABCDEF9921"))
hostname = socket.gethostname()
uid = str(uuid.uuid3(uuid.NAMESPACE_DNS, hostname).hex[-12:])

#http://www.network-science.de/ascii/
#standard
figlet = '''
 ____  _____    _             _ _       
|  _ \|  ___|__| |_ _   _  __| (_) ___  
| | | | |_ / __| __| | | |/ _` | |/ _ \ 
| |_| |  _|\__ \ |_| |_| | (_| | | (_) |
|____/|_|  |___/\__|\__,_|\__,_|_|\___/ 
    
'''

Exemple #53
0
				result.append(block)
				i += 8
			if _pythonMajorVersion < 3:
				data = ''.join(result)
			else:
				data = bytes.fromhex('').join(result)
		else:
			data = self.__key3.crypt(data, DECRYPT)
			data = self.__key2.crypt(data, ENCRYPT)
			data = self.__key1.crypt(data, DECRYPT)
		return self._unpadData(data, pad, padmode)

data = "Please encrypt my data"
k = des("DESCRYPT", CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5)
d = k.encrypt(data)
print "Using Des, msg:", data
print "Encrypted: %r" % d
print "Decrypted: %r" % k.decrypt(d)
assert k.decrypt(d, padmode=PAD_PKCS5) == data

# Triple-des
print ("Now using triple des class")
from binascii import unhexlify as unhex
t1 = triple_des(unhex("133457799BBCDFF1112233445566778877661100DD223311"))
print ("Key:       %r" % t1.getKey())
print ("Data:      %r" % d)
td1 = t1.encrypt(d)
print ("Encrypted: %r" % td1)
td2 = t1.decrypt(td1)
print ("Decrypted: %r" % td2)
Exemple #54
0
def _fulltest_():
    # This should not produce any unexpected errors or exceptions
    from time import time
    from binascii import unhexlify as unhex
    from binascii import hexlify as dohex

    t = time()

    data = "DES encryption algorithm".encode('ascii')
    k = des("\0\0\0\0\0\0\0\0", CBC, "\0\0\0\0\0\0\0\0")
    d = k.encrypt(data)
    if k.decrypt(d) != data:
        print ("Test 1:  Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 1:  Successful")

    data = "Default string of text".encode('ascii')
    k = des("\0\0\0\0\0\0\0\0", CBC, "\0\0\0\0\0\0\0\0")
    d = k.encrypt(data, "*")
    if k.decrypt(d, "*") != data:
        print ("Test 2:  Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 2:  Successful")

    data = "String to Pad".encode('ascii')
    k = des("\r\n\tABC\r\n")
    d = k.encrypt(data, "*")
    if k.decrypt(d, "*") != data:
        print ("Test 3:  Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 3:  Successful")

    k = des("\r\n\tABC\r\n")
    d = k.encrypt(unhex("000102030405060708FF8FDCB04080"), unhex("44"))
    if k.decrypt(d, unhex("44")) != unhex("000102030405060708FF8FDCB04080"):
        print ("Test 4a: Error: Unencypted data block does not match start data")
    elif k.decrypt(d) != unhex("000102030405060708FF8FDCB0408044"):
        print ("Test 4b: Error: Unencypted data block does not match start data")
    else:
        print ("Test 4:  Successful")

    data = "String to Pad".encode('ascii')
    k = des("\r\n\tkey\r\n")
    d = k.encrypt(data, padmode=PAD_PKCS5)
    if k.decrypt(d, padmode=PAD_PKCS5) != data:
        print ("Test 5a: Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    # Try same with padmode set on the class instance.
    k = des("\r\n\tkey\r\n", padmode=PAD_PKCS5)
    d = k.encrypt(data)
    if k.decrypt(d) != data:
        print ("Test 5b: Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 5:  Successful")

    k = triple_des("MyDesKey\r\n\tABC\r\n0987*543")
    d = k.encrypt(unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"))
    if k.decrypt(d) != unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"):
        print ("Test 6:  Error: Unencypted data block does not match start data")
    else:
        print ("Test 6:  Successful")

    k = triple_des("\r\n\tABC\r\n0987*543")
    d = k.encrypt(unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"))
    if k.decrypt(d) != unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"):
        print ("Test 7:  Error: Unencypted data block does not match start data")
    else:
        print ("Test 7:  Successful")

    k = triple_des("MyDesKey\r\n\tABC\r\n0987*54B", CBC, "12341234")
    d = k.encrypt(unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"))
    if k.decrypt(d) != unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080"):
        print ("Test 8:  Error: Triple DES CBC failed.")
    else:
        print ("Test 8:  Successful")

    k = triple_des("MyDesKey\r\n\tABC\r\n0987*54B", CBC, "12341234")
    d = k.encrypt(unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDC"), '.')
    if k.decrypt(d, '.') != unhex("000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDCB04080000102030405060708FF8FDC"):
        print ("Test 9:  Error: Triple DES CBC with padding failed.")
    else:
        print ("Test 9:  Successful")

    k = triple_des("\r\n\tkey\rIsGoodKey")
    data = "String to Pad".encode('ascii')
    d = k.encrypt(data, padmode=PAD_PKCS5)
    if k.decrypt(d, padmode=PAD_PKCS5) != data:
        print ("Test 10: Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 10: Successful")

    k = triple_des("\r\n\tkey\rIsGoodKey")
    data = "String not need Padding.".encode('ascii')
    d = k.encrypt(data, padmode=PAD_PKCS5)
    if k.decrypt(d, padmode=PAD_PKCS5) != data:
        print ("Test 11: Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 11: Successful")

    # Test PAD_PKCS5 with CBC encryption mode.

    k = des("IGoodKey", mode=CBC, IV="\0\1\2\3\4\5\6\7")
    data = "String to Pad".encode('ascii')
    d = k.encrypt(data, padmode=PAD_PKCS5)
    if k.decrypt(d, padmode=PAD_PKCS5) != data:
        print ("Test 12: Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 12: Successful")

    k = des("IGoodKey", mode=CBC, IV="\0\1\2\3\4\5\6\7")
    data = "String not need Padding.".encode('ascii')
    d = k.encrypt(data, padmode=PAD_PKCS5)
    if k.decrypt(d, padmode=PAD_PKCS5) != data:
        print ("Test 13: Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 13: Successful")

    k = triple_des("\r\n\tkey\rIsGoodKey", mode=CBC, IV="\0\1\2\3\4\5\6\7")
    data = "String to Pad".encode('ascii')
    d = k.encrypt(data, padmode=PAD_PKCS5)
    if k.decrypt(d, padmode=PAD_PKCS5) != data:
        print ("Test 14: Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 14: Successful")

    k = triple_des("\r\n\tkey\rIsGoodKey", mode=CBC, IV="\0\1\2\3\4\5\6\7")
    data = "String not need Padding.".encode('ascii')
    d = k.encrypt(data, padmode=PAD_PKCS5)
    if k.decrypt(d, padmode=PAD_PKCS5) != data:
        print ("Test 15: Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 15: Successful")

    k = triple_des("\r\n\tkey\rIsGoodKey", mode=CBC, IV="\0\1\2\3\4\5\6\7", padmode=PAD_PKCS5)
    data = "String to Pad".encode('ascii')
    d = k.encrypt(data)
    if k.decrypt(d) != data:
        print ("Test 16: Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 16: Successful")

    # Ensure no error occurs when creating an instance with no IV yet set,
    # test supplied by "Yoav Aner".
    k = triple_des("\0" * 24, mode=CBC, pad=None, padmode=PAD_PKCS5)
    data = "String to Pad".encode('ascii')
    d = k.encrypt(data)
    if k.decrypt(d) != data:
        print ("Test 17: Error: decrypt does not match. %r != %r" % (data, k.decrypt(d)))
    else:
        print ("Test 17: Successful")

    print ("")
    print ("Total time taken: %f" % (time() - t))
Exemple #55
0
 def test_decrypt_invalid_version(self):
     regex = r'Unimplemented version'
     self.assertRaisesRegexp(TripleSecError, regex, lambda: triplesec.decrypt(unhex(b'1c94d7de01200000abcdef'), b'xxx'))
Exemple #56
0
def unhexl(h):
    """Convert hex to little endian bytecode"""
    return unhex(h)[::-1]
Exemple #57
0
def postprocess_value(tokens, property, base=None, line=0, col=0):
    """
    """
    tokens = trim_extra(tokens)

    if len(tokens) >= 2 and (tokens[-2] == ("CHAR", "!")) and (tokens[-1] == ("IDENT", "important")):
        important = True
        tokens = trim_extra(tokens[:-2])

    else:
        important = False

    if (
        properties[property.name] in (int, float)
        and len(tokens) == 2
        and tokens[0] == ("CHAR", "-")
        and tokens[1][0] == "NUMBER"
    ):
        # put the negative sign on the number
        tokens = [(tokens[1][0], "-" + tokens[1][1])]

    value = tokens

    if properties[property.name] in (int, float, str, color, uri, boolean) or type(properties[property.name]) is tuple:
        if len(tokens) != 1:
            raise ParseException('Single value only for property "%(property)s"' % locals(), line, col)

    if properties[property.name] is int:
        if tokens[0][0] != "NUMBER":
            raise ParseException('Number value only for property "%(property)s"' % locals(), line, col)

        value = int(tokens[0][1])

    elif properties[property.name] is float:
        if tokens[0][0] != "NUMBER":
            raise ParseException('Number value only for property "%(property)s"' % locals(), line, col)

        value = float(tokens[0][1])

    elif properties[property.name] is str:
        if tokens[0][0] != "STRING":
            raise ParseException('String value only for property "%(property)s"' % locals(), line, col)

        value = tokens[0][1][1:-1]

    elif properties[property.name] is color_transparent:
        if tokens[0][0] != "HASH" and (tokens[0][0] != "IDENT" or tokens[0][1] != "transparent"):
            raise ParseException('Hash or transparent value only for property "%(property)s"' % locals(), line, col)

        if tokens[0][0] == "HASH":
            if not re.match(r"^#([0-9a-f]{3}){1,2}$", tokens[0][1], re.I):
                raise ParseException('Unrecognized color value for property "%(property)s"' % locals(), line, col)

            hex = tokens[0][1][1:]

            if len(hex) == 3:
                hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]

            rgb = (ord(unhex(h)) for h in (hex[0:2], hex[2:4], hex[4:6]))

            value = color(*rgb)

        else:
            value = "transparent"

    elif properties[property.name] is color:
        if tokens[0][0] != "HASH":
            raise ParseException('Hash value only for property "%(property)s"' % locals(), line, col)

        if not re.match(r"^#([0-9a-f]{3}){1,2}$", tokens[0][1], re.I):
            raise ParseException('Unrecognized color value for property "%(property)s"' % locals(), line, col)

        hex = tokens[0][1][1:]

        if len(hex) == 3:
            hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]

        rgb = (ord(unhex(h)) for h in (hex[0:2], hex[2:4], hex[4:6]))

        value = color(*rgb)

    elif properties[property.name] is uri:
        if tokens[0][0] != "URI":
            raise ParseException('URI value only for property "%(property)s"' % locals(), line, col)

        raw = tokens[0][1]

        if raw.startswith('url("') and raw.endswith('")'):
            raw = raw[5:-2]

        elif raw.startswith("url('") and raw.endswith("')"):
            raw = raw[5:-2]

        elif raw.startswith("url(") and raw.endswith(")"):
            raw = raw[4:-1]

        value = uri(raw, base)

    elif properties[property.name] is boolean:
        if tokens[0][0] != "IDENT" or tokens[0][1] not in ("true", "false"):
            raise ParseException('true/false value only for property "%(property)s"' % locals(), line, col)

        value = boolean(tokens[0][1] == "true")

    elif type(properties[property.name]) is tuple:
        if tokens[0][0] != "IDENT":
            raise ParseException('Identifier value only for property "%(property)s"' % locals(), line, col)

        if tokens[0][1] not in properties[property.name]:
            raise ParseException('Unrecognized value for property "%(property)s"' % locals(), line, col)

        value = tokens[0][1]

    elif properties[property.name] is numbers:
        values = []

        # strip the list down to what we think goes number, comma, number, etc.
        relevant_tokens = [token for token in tokens if token[0] == "NUMBER" or token == ("CHAR", ",")]

        for (i, token) in enumerate(relevant_tokens):
            if (i % 2) == 0 and token[0] == "NUMBER":
                try:
                    value = int(token[1])
                except ValueError:
                    value = float(token[1])

                values.append(value)

            elif (i % 2) == 1 and token[0] == "CHAR":
                # fine, it's a comma
                continue

            else:
                raise ParseException(
                    'Value for property "%(property)s" should be a comma-delimited list of numbers' % locals(),
                    line,
                    col,
                )

        value = numbers(*values)

    return Value(value, important)
Exemple #58
0
import json
import os.path
import six
import struct

import triplesec
from triplesec import TripleSec, TripleSecError
from triplesec.versions import _versions


path = os.path.dirname(os.path.realpath(os.path.abspath(__file__)))
vectors = json.load(open(os.path.join(path, 'vectors.json')))
for v in vectors:
    for k in v:
        v[k] = v[k].encode('ascii') # JSON insists to decode the loaded objects
        if v[k].startswith(b'0x'): v[k] = unhex(v[k][2:])
    if 'extra' in v: v['extra'] = unhex(v['extra'])
    v['ciphertext'] = unhex(v['ciphertext'])

# A generic vector for various tests
VECTOR = vectors[0]
assert 'disabled' not in VECTOR


class TripleSec_tests(unittest.TestCase):
    def _test_encrypt(self, encrypt, plaintext, key, pass_key=True):
        if pass_key: ciphertext = encrypt(plaintext, key)
        else: ciphertext = encrypt(plaintext)

        self.assertEqual(plaintext, triplesec.decrypt(ciphertext, key))
Exemple #59
0
# SAPGUI 7.02 Java rev 5:           ff7ffe2ddab737d674087e1305971597eff23f8d0770ff0f0000000000000000
# SAPGUI 7.02 Java rev 2:           ff7ffe2ddab737d674087e1305971597eff23f8d0770ff030000000000000000
# SAPGUI 7.40 Java rev 8:           ff7ffe2ddab737f674087e9305971597eff2bf8f4f71ff9f8606000000000000
# SAPGUI 7.02 Windows:              ff7ffa0d78b737def6196e9325bf1593ef73feebdb51ed010000000000000000
# SAPGUI 7.01 Windows:              ff7ffa0d78b737def6196e9325bf1593ef73feebdb5501000000000000000000
# SAPGUI 7.30 Windows:              ff7ffa0d78b737def6196e9325bf1597ef73feebdb51ed910200000000000000
# SAPGUI 7.40 Windows:              ff7ffa0d78b737def6196e9325bf1597ef73feebdb51ed91ca00000000000000
# SAPGUI 7.50 Windows:              ff7ffa0d78b737def6196e9325bf1597ef73feebdb51fd91ce2c010000000000
#
# SAP EHP 1 for SAP Netweaver 7.0:  ff7ffe2dd8b737d674087e1305971597ebf22f8d03300f000000000000000000
# SAP EHP 2 for SAP NetWeaver 7.0:  ff7ffe2dd8b737d674087e1305971597ebf23f8d0370ff0f0000000000000000
# SAP NetWeaver AS ABAP 7.50 SP02:  ff7ffe2dd8b737f674087e9305971597ebf2bf8f4b71ff9f8606000000000000
# SAP NetWeaver AS ABAP 7.52 SP01:  ff7ffa0d78b737de76186e9325b71597eb73feebdb51fd91ce24010000000000

support_data_sapgui_701_win = SAPDiagSupportBits(
    unhex("ff7ffa0d78b737def6196e9325bf1593ef73feebdb5501000000000000000000"))
support_data_sapgui_702_win = SAPDiagSupportBits(
    unhex("ff7ffa0d78b737def6196e9325bf1593ef73feebdb51ed010000000000000000"))
support_data_sapgui_730_win = SAPDiagSupportBits(
    unhex("ff7ffa0d78b737def6196e9325bf1597ef73feebdb51ed910200000000000000"))
support_data_sapgui_740_win = SAPDiagSupportBits(
    unhex("ff7ffa0d78b737def6196e9325bf1597ef73feebdb51ed91ca00000000000000"))
support_data_sapgui_750_win = SAPDiagSupportBits(
    unhex("ff7ffa0d78b737def6196e9325bf1597ef73feebdb51fd91ce2c010000000000"))
support_data_sapgui_702_java2 = SAPDiagSupportBits(
    unhex("ff7ffe2ddab737d674087e1305971597eff23f8d0770ff030000000000000000"))
support_data_sapgui_702_java5 = SAPDiagSupportBits(
    unhex("ff7ffe2ddab737d674087e1305971597eff23f8d0770ff0f0000000000000000"))
support_data_sapgui_740_java8 = SAPDiagSupportBits(
    unhex("ff7ffe2ddab737f674087e9305971597eff2bf8f4f71ff9f8606000000000000"))
support_data_sapnw_701 = SAPDiagSupportBits(
Exemple #60
0
    def deleteOldCacheData(self, days, still_active = [], delete_torrents = False):
        if not days:
            return
        exptime = time() - (days*24*3600)
        names = {}
        times = {}

        for f in os.listdir(self.dir_torrentcache):
            p = os.path.join(self.dir_torrentcache, f)
            f = os.path.basename(f)
            try:
                f, garbage = f.split('.')
            except:
                pass
            try:
                f = unhex(f)
                assert len(f) == 20
            except:
                continue
            if delete_torrents:
                names.setdefault(f, []).append(p)
            try:
                t = os.path.getmtime(p)
            except:
                t = time()
            times.setdefault(f, []).append(t)
        
        for f in os.listdir(self.dir_datacache):
            p = os.path.join(self.dir_datacache, f)
            try:
                f = unhex(os.path.basename(f))
                assert len(f) == 20
            except:
                continue
            names.setdefault(f, []).append(p)
            try:
                t = os.path.getmtime(p)
            except:
                t = time()
            times.setdefault(f, []).append(t)

        for f in os.listdir(self.dir_piececache):
            p = os.path.join(self.dir_piececache, f)
            try:
                f = unhex(os.path.basename(f))
                assert len(f) == 20
            except:
                continue
            for f2 in os.listdir(p):
                p2 = os.path.join(p, f2)
                names.setdefault(f, []).append(p2)
                try:
                    t = os.path.getmtime(p2)
                except:
                    t = time()
                times.setdefault(f, []).append(t)
            names.setdefault(f, []).append(p)

        for k, v in times.items():
            if max(v) < exptime and not k in still_active:
                for f in names[k]:
                    try:
                        os.remove(f)
                    except:
                        try:
                            os.removedirs(f)
                        except:
                            pass