Esempio n. 1
0
def digest (password):
	"""This method returns the LM hash of a password in a binary string.
	
	@param password The password to calculate the LM hash.
	@return A binary string with the LM value"""
	
	# Get the PASSWORD (uppercase)
	upperPass = password.upper()
	
	# Get a list with each character of upperPass in hex format
	mPass = map(hex,map(ord,upperPass))
	
	# Pad with NULLs
	mPass.extend (['0x00']*(14-len(mPass)))
	
	# Split in 2 7-bytes parts and get the 2 related keys
	key1 = __getKey ( ['0x00'] + mPass[:7] )
	key2 = __getKey ( ['0x00'] + mPass[7:14] )
	
	# Get the LM hash
	BASESTRING = 'KGS!@#$%'
	
	des = pyDes.des ( key1, mode=pyDes.ECB, pad='\x00' )
	lmhash = des.encrypt( BASESTRING )
	
	des = pyDes.des ( key2, mode=pyDes.ECB, pad='\x00' )
	lmhash += des.encrypt( BASESTRING )
	
	# Return the LM hash
	return lmhash
Esempio n. 2
0
 def __desencrypt(self, data, key):
     """ DES encrypt algorithm, to generate signature. """
     ph = '--------'
     key = (key + ph)[:8]  # 8 digits
     des = pyDes.des(key, pyDes.CBC, key, pad=None, padmode=pyDes.PAD_PKCS5)
     d = des.encrypt(data)
     return binascii.hexlify(d)
Esempio n. 3
0
def get_sid_token(encrypt_string):
	k=pyDes.des('e5571054', pyDes.ECB, "\0\0\0\0\0\0\0\0", pad='\32', padmode=pyDes.PAD_NORMAL)
	enh=base64.decodestring(encrypt_string)
	data = k.decrypt(enh)
	data = data.split('\0')[0]
	print data
	return data
Esempio n. 4
0
def get_ep(fileid, sid, token):
	src = sid+'_'+fileid+'_'+token
	k=pyDes.des('bf09f477', pyDes.ECB, "\0\0\0\0\0\0\0\0", pad='\0', padmode=pyDes.PAD_NORMAL)
	print src
	d = k.encrypt(str(src))
	ep = base64.b64encode(d)
	return urllib.quote_plus(ep)
 def change_unix_pwd(self):
     """Change password at unix level after password expiration at website
        Level.Uses secret passphrase, old password and new password while
        changing password.Returns True on success and False on failure.Also,
        logs the error message incase of failure.
     """
     old_pwd        = self.config['COMMON.OLD_PASSWORD']
     new_pwd        = self.config['COMMON.PASSWORD']
     home           = self.config['COMMON.DEFAULT_HOME']
     enc_pwd_file   = self.config['COMMON.ENC_PASS_FILE']
     secret_pphrase = self.config['pass_phrase']
     
     if old_pwd == new_pwd:
         self.data['UNIX_MSG'] = "Password change failed : old pwd = new pwd"
         return False
        
     try:
         key     = pyDes.des(secret_pphrase, pad=None, padmode=PAD_PKCS5)
         enc_pwd = key.encrypt(new_pwd)    
         
         enc_file_loc = home + '/' +  enc_pwd_file
         fhandle = open(enc_file_loc, "w")
         fhandle.write(enc_pwd)
     except IOError, err:
         logger.error("Password change failed :ERROR: "+str(err))
         return False
Esempio n. 6
0
def encrypt(text):
	if isinstance(text, str) == False:
		raise TypeError
	key = generateKey()
	text = DecryptionIdentifier + text
	des = pyDes.des(key, padmode = pyDes.PAD_PKCS5)
	return des.encrypt(text)
Esempio n. 7
0
def encode(str):
    if type(str) == types.UnicodeType:
        str = str.encode("utf-8")
    key = pyDes.des("12312312", pyDes.CBC, "12312312", pad=None, padmode=pyDes.PAD_PKCS5)
    des_data = key.encrypt(str)
    b_data = base64.b64encode(des_data)
    return b_data
def decrypt(cipherHex, db_system_id):
    cipherText = binascii.unhexlify(cipherHex)
    assert cipherText[0] == 5
    key = cipherText[1:9]
    cipher = pyDes.des(key, mode=pyDes.CBC, IV='\0' * 8, padmode=pyDes.PAD_PKCS5)
    plainText = cipher.decrypt(cipherText[9:]).decode('utf-8')
    return plainText
Esempio n. 9
0
def crypt(key, data, method):
    cipher = pyDes.des(key, padmode=pyDes.PAD_PKCS5)
    if method == 'e':
        value = cipher.encrypt(data).encode('hex')
    if method == 'd':
        value = cipher.decrypt(data.decode('hex'))
    return value
def decryptFile(inputFilePath, outputFilePath):
	file = open(inputFilePath)
	data = file.read()
	k = pyDes.des("DESCRYPT", pyDes.CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=pyDes.PAD_PKCS5)
	decrypted_content = k.decrypt(data)
	with open(outputFilePath, 'w') as file_handle:
		file_handle.write(decrypted_content)
Esempio n. 11
0
def tweet(request):
    import base64
    import pyDes
    import re
    import json

    api = create_api(request)
    tweet = request.GET["tweet"]

    tweetbin = base64.b64decode(tweet)
    k = pyDes.des(request.session.session_key[:8], pyDes.ECB)
    tweetdec = k.decrypt(tweetbin)
    tweetrep = re.compile("\x05*$").sub("", tweetdec)

    content_type = "application/json;charset=UTF-8"
    try:
        api.status_update(tweetrep)
        pass
    except:
        result = {"result": "fail"}
        response = django.http.HttpResponseServerError(content=json.dumps(result), content_type=content_type)
    else:
        result = {"result": "success"}
        response = django.http.HttpResponse(content=json.dumps(result), content_type=content_type)

    return response
Esempio n. 12
0
def read_pm25():
    service = RemotingService(config.AMF_GATEWAY).getService('FlashRemotingServiceLibrary.Sample.getSurvyValue')
    extract = lambda s: int(s[8: s.find(u'微克')]) if s[9] != u'—' else None
    key = pyDes.des(config.DES_KEY, pyDes.CBC, config.DES_IV)
    return map(extract,
        [key.decrypt(b64decode(service("PM25", scode))).decode("UTF-8")
            for scode in config.STATION.iterkeys()]
        )  # I'm too lazy...
Esempio n. 13
0
def acctDecrypt(AcctArray, pwkey):
    #decrypt accounts
    d = pyDes.des(pwkey)
    for acct in AcctArray:
       acct[1] = d.decrypt(acct[1],' ')
       acct[3] = d.decrypt(acct[3],' ')
       acct[4] = d.decrypt(acct[4],' ')
    return AcctArray
Esempio n. 14
0
 def encrypt(self, data):
     k = pyDes.des(self.key, pyDes.CBC, self.iv, pad=None, padmode=pyDes.PAD_PKCS5)
     d = k.encrypt(data)
     print("xxxxoriginxxxxxxxxxx")
     print(d)
     print('...............................')
     print "Encrypt00000000000000000ed:%r" % binascii.hexlify(d)
     #d = base64.encodestring(d)
     return d
Esempio n. 15
0
def CalcMac3DES(data,initdata,key):
    datalen = len(data)
    k = pyDes.des(key[:8],pad=None, padmode=pyDes.PAD_NORMAL)

    for i in range(datalen/8):
        m = ""
        for j in range(len(initdata)):
            m = m + chr(ord(initdata[j]) ^ ord(data[i*8+j]))

        initdata = m
        x = k.encrypt(initdata)
        initdata = x


    k1 = pyDes.des(key[8:],pad=None, padmode=pyDes.PAD_NORMAL)
    n = k1.decrypt(initdata)
    initdata = k.encrypt(n)
    return initdata
Esempio n. 16
0
def decrypt(cipher):
	key = generateKey()
	des = pyDes.des(key)
	dcyIDLen = len(DecryptionIdentifier)
	text = des.decrypt(cipher, padmode = pyDes.PAD_PKCS5)
	if len(text) < dcyIDLen or text[0:dcyIDLen] != DecryptionIdentifier:
		raise DecryptionError
	else:
		text = text[dcyIDLen:]
		return text
Esempio n. 17
0
 def __init__(self, IV):
     '''
     :param IV: initial value, length must be 8 bytes
     '''
     
     assert isinstance(IV, str)
     assert len(IV) == 8
     
     self.IV = IV
     self.des = pyDes.des("DESCRYPT", pyDes.CBC, self.IV, pad=None, padmode=pyDes.PAD_PKCS5)
Esempio n. 18
0
def decryptKey():
    key='1122334455667788'
    data='5B4A94494D94CCAEB823A0302D789E5DA0EE5C28AF05D1354EFF59C3C3EDD44A'
    data2='3CF5F19CFE622E70D1BBF719A6D29CCE229A3AB5C502C90C37EC16E8C7962B53'
    k = pyDes.des(codecs.decode(key,'hex'), pad=None, padmode=pyDes.PAD_NORMAL)
    e = k.decrypt(codecs.decode(data,'hex')) 
    print 'load key[%s]' %  codecs.encode(e,'hex')
    
    e = k.decrypt(codecs.decode(data2,'hex')) 
    print 'main key[%s]' %  codecs.encode(e,'hex')
Esempio n. 19
0
def encrypt(encrypt_str):
    '''加密字符串'''
    key="llgmgpyw"
    k=pyDes.des(key,pyDes.CBC,"\0\0\0\0\0\0\0\0",pad=None,padmode=pyDes.PAD_PKCS5)
    encrypt_str=encrypt_str.encode("base64")
    ret=k.encrypt(encrypt_str)
    ret=ret.encode("base64")
    if ret[-1:]=="\n":
        ret=ret[:-1]
    return ret
Esempio n. 20
0
def decipher_bloomberg_file(key_as_str, in_filename, out_filename):
    # Instanciate the DES decryptor
    decrypt = des(str(des_string_to_key(key_as_str)),CBC,BLOOMBERG_PADDING, pad=None, padmode=PAD_NORMAL)
    in_file = open(in_filename,'rb')
    uubuffer = in_file.read()
    in_file.close()
    out_file = open(out_filename,'wb')
    uudecode = codecs.getdecoder('uu')
    payload, size = uudecode(uubuffer)
    out_file.write(decrypt.decrypt(payload))
    out_file.close()
Esempio n. 21
0
def iproxy(url):
    if isinstance(url, unicode):
        url = url.encode('utf-8')
    try:
        url = urlparse(url)
    except Exception:
        return url
    src = url.netloc + url.path
    cipher = pyDes.des(URL_CRYPT_KEY, padmode=pyDes.PAD_PKCS5)
    dst = cipher.encrypt(src, padmode=pyDes.PAD_PKCS5)
    return 'http://img{}.zhinsta.com:8000/{}'.format(random.choice([1, 2]), base64.urlsafe_b64encode(dst).strip())
Esempio n. 22
0
def des_decryption_module(key_data,config_data):
  
  try:
    
    des_decryption = des(key_data)
    decrypted_data = des_decryption.decrypt(config_data)
    return decrypted_data
  
  except Exception as e:
    print e
    pass    
Esempio n. 23
0
def calcmac(key,data,random):
	p = codecs.decode(data,'hex')
	datalen = len(p)
	keytext = codecs.decode(key,'hex')
	k = pyDes.des(keytext[:8],pad=None, padmode=pyDes.PAD_NORMAL)
	initdata = codecs.decode(random,'hex')
	
	for i in range(datalen/8):
		#print "calc mac [%d] " % i
		m = ""
		for j in range(len(initdata)):
			m = m + chr(ord(initdata[j]) ^ ord(p[i*8+j]))
		initdata = m
		x = k.encrypt(initdata)
		initdata = x
		
	
	k1 = pyDes.des(keytext[8:],pad=None, padmode=pyDes.PAD_NORMAL)
	n = k1.decrypt(initdata)
	initdata = k.encrypt(n)
	return initdata
	def desencriptaFichero(self, contrasena, ruta, nombreArchivo):
	    # abrimos el arhivo, lo guardamos en memoria y cerramos.
	    f = open(ruta+nombreArchivo, 'rb')
	    d = f.read()
	    f.close()

	    # convertimos la clave string en objeto clave
	    k = des(contrasena)

	    #desencriptamos el fichero-objeto en memoria con el
	    #objeto clave y lo grabamos en memoria
	    d = k.decrypt(d, ' ')
	    return d
Esempio n. 25
0
    def test_des_encrypt(self):
        import pyDes
        key = '_abcdef_'
        ivec = key
        sinput = 'testtes'

        k = pyDes.des(key, pyDes.CBC, ivec, pad=None, padmode=pyDes.PAD_PKCS5)
        expected = bin2hex(k.encrypt(sinput))

        from ctypes_des import des_encrypt
        real = des_encrypt(sinput, key, ivec)

        self.assertEqual(real, expected)
Esempio n. 26
0
def calc_resp(password_hash, server_challenge):
    """calc_resp generates the LM response given a 16-byte password hash and the
        challenge from the Type-2 message.
        @param password_hash
            16-byte password hash
        @param server_challenge
            8-byte challenge from Type-2 message
        returns
            24-byte buffer to contain the LM response upon return
    """
    # padding with zeros to make the hash 21 bytes long
    password_hash = password_hash + b'\0' * (21 - len(password_hash))
    res = b''
    dobj = pyDes.des(key56_to_key64(password_hash[0:7]))
    res = res + dobj.encrypt(server_challenge[0:8])

    dobj = pyDes.des(key56_to_key64(password_hash[7:14]))
    res = res + dobj.encrypt(server_challenge[0:8])

    dobj = pyDes.des(key56_to_key64(password_hash[14:21]))
    res = res + dobj.encrypt(server_challenge[0:8])
    return res
def calcmac(key,data,seedkey,random):
    """ 使用过程密钥计算 MAC """
    p = codecs.decode(data,'hex')
    datalen = len(p)
    #keytext = codecs.decode(key,'hex')
    keytext = codecs.decode(calc_mid_key(key,seedkey),'hex')
    k = pyDes.des(keytext[:8],pad=None, padmode=pyDes.PAD_NORMAL)
    initdata = codecs.decode(random,'hex')

    for i in range(datalen/8):
        m = ""
        for j in range(len(initdata)):
            m = m + chr(ord(initdata[j]) ^ ord(p[i*8+j]))

        initdata = m
        x = k.encrypt(initdata)
        initdata = x


    k1 = pyDes.des(keytext[8:],pad=None, padmode=pyDes.PAD_NORMAL)
    n = k1.decrypt(initdata)
    initdata = k.encrypt(n)
    return initdata
Esempio n. 28
0
def des_cbc_checksum(str_key, bytes_key, bytes_IV):
    padded_data = bytearray(((len(str_key)+7)/ 8)*8)
    for index in range(0,len(str_key)):
        padded_data[index] = str_key[index]
    # CBC encryption of the key
    cypher = des(str(bytes_key),CBC,str(bytes_IV), pad=None, padmode=PAD_NORMAL)
    key = cypher.encrypt(str_key)
    key = binary.to_bytes(key)
    
    checksum = bytearray(8)
    start_at = len(key) - 8
    for index in range(0,8):
        checksum[index] = key[start_at + index]
    return checksum
Esempio n. 29
0
def decrypt_pw(pwkey):
    #validate password if pwkey isn't null
    if pwkey <> '':
        #file encrypted... need password
        pw = pyDes.getDESpw()   #ask for password
        k = pyDes.des(pw)       #create encryption object using key
        pws = k.decrypt(pwkey,' ')  #decrypt
        if pws <> pw:               #comp to saved password
            print 'Invalid password.  Exiting.'
            sys.exit()
        else:
            #decrypt the encrypted fields
            pwkey = pws
    return pwkey
Esempio n. 30
0
def create_LM_hashed_password_v1(passwd):
    "setup LanManager password"
    "create LanManager hashed password"
    # if the passwd provided is already a hash, we just return the first half
    if re.match(r'^[\w]{32}:[\w]{32}$', passwd):
        return binascii.unhexlify(passwd.split(':')[0])

    # fix the password length to 14 bytes
    passwd = passwd.upper().encode('ascii')
    lm_pw = passwd + b'\0' * (14 - len(passwd))
    lm_pw = lm_pw[0:14]

    # do hash
    magic_str = b"KGS!@#$%"  # page 57 in [MS-NLMP]

    res = b''
    dobj = pyDes.des(key56_to_key64(lm_pw[0:7]))
    res = res + dobj.encrypt(magic_str)

    dobj = pyDes.des(key56_to_key64(lm_pw[7:14]))
    res = res + dobj.encrypt(magic_str)

    return res
Esempio n. 31
0
def encryptDES_ECB(data, key):
    data = data.encode()
    k = pyDes.des(key, pyDes.ECB, IV=None, pad=None, padmode=pyDes.PAD_PKCS5)
    d = k.encrypt(data)
    assert k.decrypt(d, padmode=pyDes.PAD_PKCS5) == data
    return d
#!/usr/bin/python

# Last modified: J. Montalvo-Urquizo (20210210)

import pyDes

# Punto 1
data = b"This is a small test for the DES Algorithm Implementation to be used at MA2002B"
print("\n\nOriginal Data: %r" % data)

# Punto 2
kAlice = pyDes.des("MONTALVO",
                   pyDes.CBC,
                   "\0\0\0\0\0\0\0\0",
                   pad=None,
                   padmode=pyDes.PAD_PKCS5)
print("Alice's key is: %r" % kAlice.getKey())

# Punto 3
dataTransfered = kAlice.encrypt(data)
print("Alice's Encrypted Message: %r\n" % dataTransfered)

# Punto 4
kBob = pyDes.des("MONTALVO",
                 pyDes.CBC,
                 "\0\0\0\0\0\0\0\0",
                 pad=None,
                 padmode=pyDes.PAD_PKCS5)
print("Bob's key is: %r" % kBob.getKey())

# Punto 5
Esempio n. 33
0
 def DESEncrypt(s, Key=DESKEY):
     iv = b"\x01\x02\x03\x04\x05\x06\x07\x08"
     k = des(Key, CBC, iv, pad=None, padmode=PAD_PKCS5)
     encrypt_str = k.encrypt(s)
     return base64.b64encode(encrypt_str).decode()
import pyDes
import rsa
(pubkey, privkey) = rsa.newkeys(512)
crypto = rsa.encrypt(b"DESCRYPT", pubkey)
#расшифровываем
rsakey = rsa.decrypt(crypto, privkey)
k = pyDes.des(rsakey, pyDes.CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=pyDes.PAD_PKCS5)

Esempio n. 35
0
def des_encrypt(s, KEY):
    secret_key = KEY
    iv = secret_key
    k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
    en = k.encrypt(s, padmode=PAD_PKCS5)
    return binascii.b2a_hex(en)
Esempio n. 36
0
def DES_encrypt(string):    #数据库加密函数
    k = pyDes.des(KEY, pyDes.CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=pyDes.PAD_PKCS5)
    return base64.b64encode(k.encrypt(string))
# install the pyDes package with pip install 
# e.g.
# pip install pyDes

import pyDes
import binascii

data = "Pleaseencrypt my data"
k = pyDes.des("12345678", pyDes.CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=pyDes.PAD_PKCS5)

d = k.encrypt(data)

print "Encrypted: %r" % binascii.hexlify(d)
print "Decrypted: %r" % k.decrypt(d)

assert k.decrypt(d) == data
Esempio n. 38
0
import pyDes
data = "DES Algorithm Implementation"
k = pyDes.des("DESCRYPT",
              pyDes.CBC,
              "\0\0\0\0\0\0\0\0",
              pad=None,
              padmode=pyDes.PAD_PKCS5)
d = k.encrypt(data)
print "Encrypted: %r" % d
print "Decrypted: %r" % k.decrypt(d)
assert k.decrypt(d) == data
Esempio n. 39
0
def pydes_test():
    import pyDes
    pyDes.des('ChangeIt')  # Noncompliant
Esempio n. 40
0
import pyDes

Rta = int(input("Bienvenido\n\n1. Cifrar\n2. Descifrar\n\nRta: "))
if Rta == 1:
    archivo = input("Ingrese el nombre del archivo a cifrar: ")
    with open(archivo, "rb") as img_file:
        b64image = base64.b64encode(img_file.read())

    key = input("Ingrese la clave (8 carácteres): ")
    print("Archivo en base64: ", b64image)

    #key = "DESCRYPT"

    k = pyDes.des(key.encode(),
                  pyDes.CBC,
                  b"\0\1\0\1\0\1\0\0",
                  pad=None,
                  padmode=pyDes.PAD_PKCS5)
    encriptada = k.encrypt(b64image)

    print("Archivo cifrado: ", encriptada)
    encriptada64 = base64.b64encode(encriptada)
    print("Archivo cifrado en base64: ", encriptada64)

    image = open("" + archivo, "wb")
    image.write(base64.b64decode(encriptada64))
    image.close()
    print("Guardado como ", "" + archivo)
else:
    archivo = input("Ingrese el nombre del archivo a descifrar: ")
    key = input("Ingrese la clave (8 carácteres): ")
Esempio n. 41
0
import pyDes
import os
import time

key = "my_key12"

# Create an instance of a DES encryption object
des = pyDes.des(key=key, mode=pyDes.ECB, pad=b'\0')

# ---------------text encryption-----------------

# Encrypt a text using DES
text = "this is some text\nI'm trying to show that text encryption\nis available in DES"
encrypted_text = des.encrypt(text)

# Decrypt the text using DES
decrypted_text = des.decrypt(encrypted_text).strip(b'\0')

print("\n\n---------------text encryption-----------------\n\n")
print(f"Original Text:\n\n{text}\n")
print(f"Encrypted Text:\n\n{encrypted_text}\n")
print(f"Decrypted Text:\n\n{decrypted_text.decode()}\n")
print("-----------------------------------------------\n\n")
# -----------------------------------------------

# ---------------image encryption----------------
print("---------------image encryption----------------\n\n")

# Create folder for the results
if not os.path.exists("results"):
    os.mkdir("results")
Esempio n. 42
0
def DESEncrypt(s, key='ST83=@XV'):
    key = key
    iv = b"\x01\x02\x03\x04\x05\x06\x07\x08"
    k = des(key, CBC, iv, pad=None, padmode=PAD_PKCS5)
    encrypt_str = k.encrypt(s)
    return base64.b64encode(encrypt_str).decode()
Esempio n. 43
0
def play(ch_id):
    # 31.220.41.86
    key = b"98221122"

    r = s.post(list_url,
               headers={"app-token": "9120163167c05aed85f30bf88495bd89"},
               data={"username": "******"},
               timeout=15)
    ch = r.json()
    for c in ch["msg"]["channels"]:
        if c["pk_id"] == ch_id:
            selected_channel = c
            break

    title = selected_channel.get("channel_name")
    image = "http://taptube.net/tvtap1/{0}|User-Agent={1}".format(
        quote(c.get("img"), "/"), quote(user_agent))

    with s.cache_disabled():
        r = s.post(token_url,
                   headers={"app-token": "9120163167c05aed85f30bf88495bd89"},
                   data={
                       "channel_id": ch_id,
                       "username": "******"
                   },
                   timeout=15)

    links = []
    for stream in r.json()["msg"]["channel"][0].keys():
        if "stream" in stream or "chrome_cast" in stream:
            d = des(key)
            link = d.decrypt(b64decode(r.json()["msg"]["channel"][0][stream]),
                             padmode=PAD_PKCS5)
            if link:
                link = link.decode("utf-8")
                if not link == "dummytext" and link not in links:
                    links.append(link)

    if addon.getSetting("autoplay") == "true":
        link = links[0]
    else:
        dialog = xbmcgui.Dialog()
        ret = dialog.select("Choose Stream", links)
        link = links[ret]

    if link.startswith("http"):
        media_url = "{0}|User-Agent={1}".format(link, quote(player_user_agent))
    else:
        media_url = link

    media_url = media_url.replace("stream.tvtap.net", "31.220.41.86")

    if "playlist.m3u8" in media_url:
        if addon.getSetting("inputstream") == "true":
            li = ListItem(title, path=media_url)
            li.setArt({"thumb": image, "icon": image})
            li.setMimeType("application/vnd.apple.mpegurl")
            li.setProperty("inputstreamaddon", "inputstream.adaptive")
            li.setProperty("inputstream.adaptive.manifest_type", "hls")
            li.setProperty("inputstream.adaptive.stream_headers",
                           media_url.split("|")[-1])
        elif addon.getSetting("livestreamer") == "true":
            serverPath = os.path.join(
                xbmc.translatePath(addon.getAddonInfo("path")),
                "livestreamerXBMCLocalProxy.py")
            runs = 0
            while not runs > 10:
                try:
                    requests.get("http://127.0.0.1:19001/version")
                    break
                except Exception:
                    xbmc.executebuiltin("RunScript(" + serverPath + ")")
                    runs += 1
                    xbmc.sleep(600)
            livestreamer_url = "http://127.0.0.1:19001/livestreamer/" + urlsafe_b64encode(
                "hlsvariant://" + media_url)
            li = ListItem(title, path=livestreamer_url)
            li.setArt({"thumb": image, "icon": image})
            li.setMimeType("video/x-mpegts")
        else:
            li = ListItem(title, path=media_url)
            li.setArt({"thumb": image, "icon": image})
            li.setMimeType("application/vnd.apple.mpegurl")
    else:
        li = ListItem(title, path=media_url)
        li.setArt({"thumb": image, "icon": image})

    try:
        li.setContentLookup(False)
    except AttributeError:
        pass

    xbmcplugin.setResolvedUrl(plugin.handle, True, li)
Esempio n. 44
0
import pyDes

data = b'Please encrypt my data'
k = pyDes.des(b'DESCRYPT',
              pyDes.CBC,
              b'\0\0\0\0\0\0\0\0',
              pad=None,
              padmode=pyDes.PAD_PKCS5)
d = k.encrypt(data)
print(d)
e = k.decrypt(d).decode()
print(e)

# class DES(object):
#
# 	def __init__(self):
# 		pass
#
# 	def encrypto(self):
# 		pass
#
#
# if __name__ == '__main__':
# 	des = DES()
# 	des.encrypto()
Esempio n. 45
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pyDes

if __name__ == '__main__':

    r = "\x95\x06\x0B\xD5\x4E\x0A\xA8\x2E\x2D\x78\x42\xE1\x36\xAA\x9B\xEA\x41\x4F\xA7\x1A\xF2\xA2\x82\x24"
    key = "XOFOOBAM"

    d = pyDes.des(key, pyDes.CBC, "\x00" * 8)
    print d.decrypt(r)
Esempio n. 46
0
def DESDecrypt(s, key='XCE927=='):
    s = base64.b64decode(s)
    iv = b"\x01\x02\x03\x04\x05\x06\x07\x08"
    k = des(key, CBC, iv, pad=None, padmode=PAD_PKCS5)
    return k.decrypt(s)
Esempio n. 47
0
def DES_decrypt(string):    #数据库解密函数
    k = pyDes.des(KEY, pyDes.CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=pyDes.PAD_PKCS5)
    return k.decrypt(base64.b64decode(string))
Esempio n. 48
0
 def decrypt(self, data):
     des = pyDes.des(self.key, mode=pyDes.CBC, IV=self.iv, pad=None, padmode=pyDes.PAD_PKCS5)
     if isinstance(data, six.string_types):
         data = bytes(data, 'utf-8')
     data = base64.decodebytes(data)
     return des.decrypt(data).decode('utf-8')
Esempio n. 49
0
def des_descrypt(s, KEY):
    secret_key = KEY
    iv = secret_key
    k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
    de = k.decrypt(binascii.a2b_hex(s), padmode=PAD_PKCS5)
    return de
Esempio n. 50
0
def des_encrypt(string, key):
    secret_key = key
    iv = secret_key
    k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
    en = k.encrypt(string, padmode=PAD_PKCS5)
    return binascii.b2a_hex(en)
Esempio n. 51
0
name = "Client"
print(" Connected to chat server")
# Send server the client's name and get the server's name.
client_socket.send(name.encode())
s_name = client_socket.recv(1024)
s_name = s_name.decode()
print("")
print(s_name, "has joined the chat room ")

# Open the text file containing the shared DES Key and store as a string variable.
with open("des_key.txt", "r") as f:
    des_key = f.read()
# Make sure that the key has 8 characters and store it to variable 'k'
des = pyDes.des(des_key,
                pyDes.CBC,
                "\0\0\0\0\0\0\0\0",
                pad=None,
                padmode=pyDes.PAD_PKCS5)

# Open the text file containing the shared HMAC key and store it as a string variable
with open("hmac_key.txt", "r") as f:
    hmac_key = f.read()
hmac_key_byte = hmac_key.encode("utf-8")
connection = True
# While connection is True.
while connection:
    # Enter a message to be encrypted and sent to server
    message = input(str("Please enter your message: "))

    str_message = message
Esempio n. 52
0
def des_decrypt(string, key):
    secret_key = key
    iv = secret_key
    k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
    de = k.decrypt(binascii.a2b_hex(string), padmode=PAD_PKCS5)
    return de
Esempio n. 53
0
def desencrypt(key, data):
    k = pyDes.des(codecs.decode(key, 'hex'),
                  pad=None,
                  padmode=pyDes.PAD_NORMAL)
    return k.encrypt(codecs.decode(data, 'hex'))
Esempio n. 54
0
def des_decrypt(s):
    encrypt_key = SA_ENCRYPT_KEY
    iv = encrypt_key
    k = des(encrypt_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
    de = k.decrypt(base64.b64decode(s), padmode=PAD_PKCS5)
    return de
Esempio n. 55
0
def decryptDES_ECB(data, key):
    data = data.decode('base-64')
    k = pyDes.des(key, pyDes.ECB, IV=None, pad=None, padmode=pyDes.PAD_PKCS5)
    return k.decrypt(data, padmode=pyDes.PAD_PKCS5)
Esempio n. 56
0
def des_decrypt(key, cipher_text):
    IV = "33333333"
    key_handler = pyDes.des(key, pyDes.CBC, IV, pad=None, padmode=pyDes.PAD_PKCS5)
    plain_text = key_handler.decrypt(cipher_text)
    # print("decrpted: {}".format(plain_text))
    return plain_text
Esempio n. 57
0
def twodes(plain, keyOne, keyTwo):
    cipherOne = des(binascii.unhexlify(keyOne), CBC, "5edcc504", pad=None)
    cipherTwo = des(binascii.unhexlify(keyTwo), CBC, "5edcc504", pad=None)
    return cipherTwo.encrypt(cipherOne.encrypt(plain))
Esempio n. 58
0
import pyDes

KEY = [232, 74, 214, 96, 196, 114, 26, 224]
CRYPT = pyDes.des(KEY)


def obfuscate_password(password):
    padded_raw = (password + '\0' * 8)[:8]
    return CRYPT.encrypt(padded_raw)


def decrypt_passwd(obfuscated):
    decrypted_bytes = CRYPT.decrypt(obfuscated)
    return decrypted_bytes.decode("ascii").rstrip('\0')


def vncpasswd(passwd_path, password=None):
    if password is None:
        obfuscated = read_password()
    else:
        obfuscated = obfuscate_password(password)

    with open(passwd_path, "wb") as passwd:
        passwd.write(obfuscated)

    return obfuscated


def vncpasswd2plain(passwd_path):
    with open(passwd_path, "rb") as passwd:
        return decrypt_passwd(passwd.readline())
Esempio n. 59
0
                    test_quotes()

        elif menu_option == 8:
            #About
            print("\n\n" + "*" * 70 + "\n")
            print(AboutTitle)
            print("-" * 70)
            print(
                "Retrieve online statements and stock quotes to Microsoft Money"
            )
            print("\tSource :", AboutSource)
            print("\tVersion:", AboutVersion)
            print("\n\n" + "*" * 70 + "\n")
            input('Press Enter to continue')

    #end_while (main menu)

    if len(pwkey):
        #encrypt the data
        rlib1.acctEncrypt(AcctArray, pwkey)
        #encrypt the passkey
        k = pyDes.des(pwkey)
        pwkey = k.encrypt(pwkey, ' ')

    #write the data
    f = open(cfgFile, 'wb')
    pickle.dump(pwkey, f)  #encrypted key (pw)
    pickle.dump(c_getquotes, f)  #get stock quotes?
    pickle.dump(AcctArray, f)  #account info
    f.close()
Esempio n. 60
0
def startTCPEncryptedChat(host, port, DES_key, clientserver):
    socket_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = (host, port)

    # "Client" Side
    if clientserver == "client":
        socket_.connect(server_address)

        while True:
            print("Waiting to receive message..")
            received = socket_.recv(CONNECTION_BUFFER_SIZE)

            print("Ciphertext: " + repr(received))
            key = pydes.des("DESCRYPT",
                            pydes.CBC,
                            DES_key,
                            pad=None,
                            padmode=pydes.PAD_PKCS5)
            received = key.decrypt(received, padmode=pydes.PAD_PKCS5)

            plaintext = received.decode("utf-8").split("|||||")[0]
            hash_check = received.decode("utf-8").split("|||||")[1]
            hash_computed = hashlib.sha224(plaintext.encode()).hexdigest()
            print("Received hash: " + str(hash_check))
            print("Computed hash: " + str(hash_computed))
            if hash_check == hash_computed:
                print("Match!")
            else:
                print("No match.")

            print("Plaintext: " + str(plaintext))

            message = input("Message to send: ").strip("\r\n")

            print("Plaintext: " + message)
            key = pydes.des("DESCRYPT",
                            pydes.CBC,
                            DES_key,
                            pad=None,
                            padmode=pydes.PAD_PKCS5)

            hmac = hashlib.sha224(message.encode()).hexdigest()
            print("Hash of plaintext is " + str(hmac))
            message = message + "|||||" + str(hmac)

            message = key.encrypt(message)
            print("Ciphertext: " + repr(message))

            socket_.send(message)

    # "Server" side
    else:
        socket_.bind(server_address)
        socket_.listen()
        connection, client_address = socket_.accept()

        while True:
            message = input("Message to send: ").strip("\r\n")

            print("Plaintext: " + message)
            key = pydes.des("DESCRYPT",
                            pydes.CBC,
                            DES_key,
                            pad=None,
                            padmode=pydes.PAD_PKCS5)

            hmac = hashlib.sha224(message.encode()).hexdigest()
            print("Hash of plaintext is " + str(hmac))
            message = message + "|||||" + str(hmac)

            message = key.encrypt(message)
            print("Ciphertext: " + repr(message))

            connection.send(message)

            print("Waiting to receive message..")
            received = connection.recv(CONNECTION_BUFFER_SIZE)

            print("Ciphertext: " + repr(received))
            key = pydes.des("DESCRYPT",
                            pydes.CBC,
                            DES_key,
                            pad=None,
                            padmode=pydes.PAD_PKCS5)
            received = key.decrypt(received, padmode=pydes.PAD_PKCS5)

            plaintext = received.decode("utf-8").split("|||||")[0]
            hash_check = received.decode("utf-8").split("|||||")[1]
            hash_computed = hashlib.sha224(plaintext.encode()).hexdigest()
            print("Received hash: " + str(hash_check))
            print("Computed hash: " + str(hash_computed))
            if hash_check == hash_computed:
                print("Match!")
            else:
                print("No match.")

            print("Plaintext: " + str(plaintext))

    return