예제 #1
0
파일: smtplib.py 프로젝트: Dieken/jff
        def encode_digest_md5(challenge, user, password):
            challenge = base64.decodestring(challenge)
            c = digest_md5_decode_challenge(challenge)

            realm = c["realm"]
            nonce = c["nonce"]
            qop = c["qop"]
            cnonce = generate_cnonce()
            if "realm" in c:
                digest_uri = "smtp/%s" % realm
                realmPair = ',realm="%s"' % realm
            else:
                digest_uri = "smtp/localhost"
                realmPair = ""

            credential = md5("%s:%s:%s" % (user, realm, password))
            # XXX: not support authorization ID
            a1 = "%s:%s:%s" % (credential, nonce, cnonce)
            if qop == "auth":
                a2 = "AUTHENTICATE:%s" % digest_uri
            else:
                # XXX: most servers and clients don't implement auth-int/auth-conf,
                # they use dummy MD5 digest for body.
                a2 = "AUTHENTICATE:%s:00000000000000000000000000000000" % digest_uri

            a1 = hexlify(md5(a1))
            a2 = hexlify(md5(a2))
            response = hexlify(md5("%s:%s:00000001:%s:%s:%s" %
                (a1, nonce, cnonce, qop, a2)))
            response = ( 'username="******"%s,nonce="%s",cnonce="%s",'
                'nc=00000001,qop=%s,digest-uri="%s",response=%s' %
                (user, realmPair, nonce, cnonce, qop, digest_uri, response))
            return encode_base64(response, eol="")
예제 #2
0
파일: digestmd5.py 프로젝트: code2u/jsb
def resp(username, realm, password, nonce, cnonce, digest_uri):
	"constructs a response string as defined in 2.1.2.1"
	urp = md5("%s:%s:%s" % (username,realm,password))
	a1 = "%s:%s:%s" % (urp, nonce, cnonce)
	a2 = "AUTHENTICATE:%s" % digest_uri
	return hexlify(md5("%s:%s:00000001:%s:auth:%s"
		 % (hexlify(md5(a1)), nonce, cnonce, hexlify(md5(a2)))))
def fanyi(text):
    sign = '%s%s%s%s' % (appid, str(text), salt, miyao)
    print sign
    sign = md5(sign)  #MD5加密
    text = str(text)
    print text
    url = 'http://api.fanyi.baidu.com/api/trans/vip/translate?q=%s&from=auto&to=en&appid=20160727000025884&salt=%s&sign=%s' % (
        text, salt, sign)
    html = requests.get(url).content
    text = re.findall('"dst":"([\s\S]*?)"', html)[0].decode('utf8')

    if text:
        sign = '%s%s%s%s' % (appid, str(text), salt, miyao)
        sign = md5(sign)
        url_fy = 'http://api.fanyi.baidu.com/api/trans/vip/translate?q=%s&from=auto&to=zh&appid=20160727000025884&salt=%s&sign=%s' % (
            text, salt, sign)
        html_fy = requests.get(url_fy).content.decode('utf8')
        result = re.findall('"dst":"([\s\S]*?)"}]}',
                            html_fy)[0].decode("unicode-escape")
        if result:
            contents2.AppendText(result + '\n')
            # print result
            # contents2.SetValue(result)   #设置contents里的内容
        else:
            wx.MessageBox(u"出错了,请确认网络连接是否正常")
    else:
        wx.MessageBox(u"出错了,请确认网络连接是否正常")
예제 #4
0
        def encode_digest_md5(challenge, user, password):
            challenge = base64.decodestring(challenge)
            c = digest_md5_decode_challenge(challenge)

            realm = c["realm"]
            nonce = c["nonce"]
            qop = c["qop"]
            cnonce = generate_cnonce()
            if "realm" in c:
                digest_uri = "smtp/%s" % realm
                realmPair = ',realm="%s"' % realm
            else:
                digest_uri = "smtp/localhost"
                realmPair = ""

            credential = md5("%s:%s:%s" % (user, realm, password))
            # XXX: not support authorization ID
            a1 = "%s:%s:%s" % (credential, nonce, cnonce)
            if qop == "auth":
                a2 = "AUTHENTICATE:%s" % digest_uri
            else:
                # XXX: most servers and clients don't implement auth-int/auth-conf,
                # they use dummy MD5 digest for body.
                a2 = "AUTHENTICATE:%s:00000000000000000000000000000000" % digest_uri

            a1 = hexlify(md5(a1))
            a2 = hexlify(md5(a2))
            response = hexlify(
                md5("%s:%s:00000001:%s:%s:%s" % (a1, nonce, cnonce, qop, a2)))
            response = (
                'username="******"%s,nonce="%s",cnonce="%s",'
                'nc=00000001,qop=%s,digest-uri="%s",response=%s' %
                (user, realmPair, nonce, cnonce, qop, digest_uri, response))
            return encode_base64(response, eol="")
예제 #5
0
def Digest(url,username,password):
	'''digest'''
	nonce = request(url)
	realm = 'Web Control Center'
	username = username.strip()
	password = password.strip()
	method = 'GET'
	uri = '/'
	A1 = username+':'+realm+':'+password
	HA1 = md5(A1).hexdigest()
	A2 = method+':'+uri
	HA2 = md5(A2).hexdigest()
	nc = '00000001'
	cnonce = md5(str(random())).hexdigest()
	qop = 'auth'
	response = md5(HA1+":"+nonce+":"+nc+":"+cnonce+":"+qop+":"+HA2).hexdigest()
	'''digest finish'''
	
	headers = {'Authorization':'Digest username="******",realm="'+realm+'",nonce="'+nonce+'",uri="'+uri+'",response="'+response+'",qop="'+qop+'",nc="'+nc+'",cnonce="'+cnonce+'"'}
	req = Request(url,None,headers)
	try:
		resp = urlopen(req)
		code = resp.code
	except HTTPError,e:
		code = e.code
예제 #6
0
def resp(username, realm, password, nonce, cnonce, digest_uri):
    "constructs a response string as defined in 2.1.2.1"
    urp = md5("%s:%s:%s" % (username, realm, password))
    a1 = "%s:%s:%s" % (urp, nonce, cnonce)
    a2 = "AUTHENTICATE:%s" % digest_uri
    return hexlify(
        md5("%s:%s:00000001:%s:auth:%s" %
            (hexlify(md5(a1)), nonce, cnonce, hexlify(md5(a2)))))
예제 #7
0
def Generate_Expected_Data(path):
    """
    Description:
        This Module generates some given string and file path that we use to create expected data for file verification.
        If MD5 folder does not exists, it will create one
        It will delete any previous output file from C:\MD5 folder
        It will opent the folder location of the output file at the end. 
                 
    Parameter Description:
        - path : folder path that you want to generate the MD5 of    
    Example: 
        - Generate_Expected_Data ('C:\Users\ihossain\Videos\yaseen')   
    Output:
        - it will output to C:\MD5\Output.txt 
            
    ======= End of Instruction: =========

"""

    MD5Path = "C:\MD5"
    OutputPath = "C:\MD5\Output.txt"
    if not os.path.exists(MD5Path):
        os.makedirs(MD5Path)

    if os.path.exists:
        os.remove(OutputPath)

    for root, dirs, files in os.walk(path):
        # print dirs
        for name in files:
            filename = os.path.join(root, name)
            print filename
            # print name

            print md5(filename)
            initial_string = "('~MKSID~','~SectionName~',E'"
            middle_string = "','"
            last_string = "'),"
            md5_of_file = md5(filename)

            trim_file_name_remove_original_path = filename.replace(path, "")
            trim_file_name_add_extra_quote = trim_file_name_remove_original_path.replace("'", "''")
            trim_file_name = trim_file_name_add_extra_quote.replace("\\", "\\\\")

            full_string = initial_string + trim_file_name + middle_string + md5_of_file + last_string
            file = codecs.open("C:\MD5\Output.txt", "a", "utf-8")
            # file.write(name)
            # file.write (" : ")
            # file.write(md5_of_file)
            file.write(full_string)
            file.write("\n")
            file.write(codecs.BOM_UTF8)
            file.close()
    subprocess.Popen("explorer " + MD5Path)
예제 #8
0
def demangle(muid, key, md5=md5.md5, otp=otp):
    """ Demangle a mangle()d UID string muid using the given key
        string.

    """
    akey = md5(key).digest()
    # First decode the counter and the noisy timestamp part
    tuid = otp(muid[:16], akey)
    # Next denoise the timestamp part to build the bkey
    ckey = 'ffff' + tuid[:4] * 7
    bkey = md5(otp(tuid, ckey) + key).digest()
    # Decode and denoise the UID
    return otp(otp(muid, akey + bkey * 2), ckey)
예제 #9
0
def check_login_liulian(request, cfg, sid, uin):
    from md5 import md5
    import json
    params = {
        'appid':
        cfg['appid'],
        'appkey':
        cfg['appkey'],
        'sid':
        sid,
        'sign':
        md5(cfg['appid'] + cfg['appkey'] + cfg['privatekey'] +
            sid).hexdigest(),
    }
    rsp = sdk_poolmanager.request('POST', cfg['login_url'], fields=params)
    if rsp.status == 200:
        try:
            data = json.loads(rsp.data)
            print data
        except ValueError:
            logger.error("params %r", params)
            logger.error("[sdk pyw] req %r failed %s", sid, rsp.data)
            return False

        if data['status'] != 1:
            logger.error("params %r", params)
            logger.error("[sdk liulian] %s status %d", cfg['login_url'],
                         data['status'])
            return False

        return data['userid']

    logger.error("params %r", params)
    logger.error("[sdk liulian] %s status %d", cfg['login_url'], rsp.status)
    return False
예제 #10
0
def check_login_pyw(request, cfg, sid, uin):
    import json
    import time
    from md5 import md5
    tid = ''.join(list(md5(str(time.time())).hexdigest())[8:-8])
    params = {
        'uid': uin,
        'token': sid,
        'tid': tid,
    }
    rsp = sdk_poolmanager.urlopen('POST',
                                  cfg["login_url"],
                                  headers={"Content-Type": "application/json"},
                                  body=json.dumps(params))
    if rsp.status == 200:
        try:
            data = json.loads(rsp.data)
        except ValueError:
            logger.error("params %r", params)
            logger.error("[sdk pyw] req %r failed %s", sid, rsp.data)
            return False
        if data.get('ack', 0) != 200:
            logger.error("params %r", params)
            logger.error("[sdk pyw] %s", data['msg'])
            return False
    else:
        logger.error("params %r", params)
        logger.error("[sdk pyw] %s status %d", cfg['loginurl'], rsp.status)
        return False
    return uin
예제 #11
0
def check_login_h07073(request, cfg, sid, uin):
    from md5 import md5
    import json
    params = {
        'username': uin,
        'token': sid,
        'pid': cfg['pid'],
    }
    to_sign = "&".join("%s=%s" % (f, params[f]) for f in sorted(params))
    to_sign = '%s%s' % (to_sign, cfg['secretKey'])
    params['sign'] = md5(to_sign).hexdigest()
    rsp = sdk_poolmanager.request('POST', cfg['login_url'], fields=params)
    if rsp.status == 200:
        try:
            data = json.loads(rsp.data)
        except ValueError:
            logger.error("params %r", params)
            logger.error("[sdk h07073] req %r failed %s", sid, rsp.data)
            return False
        if data.get('state', 0) != 1:
            logger.error("params %r", params)
            logger.error("[sdk h07073] req %s failed %s", sid, data)
            return False
    else:
        logger.error("params %r", params)
        logger.error("[sdk h07073] %s status %d", cfg['loginurl'], rsp.status)
        return False
    return data["data"]["uid"]
예제 #12
0
def check_login_tiantian(request, cfg, sid, uin):
    import json
    from md5 import md5
    params = {
        "cpId": cfg["app_id"],
        "token": sid,
    }
    sparams = json.dumps(params)
    sign = md5("/user/info" + sparams + cfg["app_key"]).hexdigest()
    info = {
        "data": sparams,
        "sign": sign,
    }
    rsp = sdk_poolmanager.request("GET", cfg["login_url"], info)
    if rsp.status == 200:
        rsp_json_data = json.loads(rsp.data)
        if rsp_json_data["status"] != 1:
            logger.error("params %r", params)
            logger.error("[sdk tiantian] req %s failed %s", sid, rsp.data)
            return False
    else:
        logger.error("params %r", params)
        logger.error("[sdk tiantian] %s status %d", cfg['loginurl'],
                     rsp.status)
        return False
    return rsp_json_data["data"]["id"]
예제 #13
0
    def post(self):
        """Create access key
        """
        try:
            data = self.json_decode(self.request.body)

            #if not self.can('create_accesskey'):
                #self.send_response(FORBIDDEN, dict(error="No permission to create accesskey"))
                #return

            processor = data.get('processor', None)
            if not processor:
                data['permission'] = 0
            else:
                try:
                    proc = import_module('hooks.' + processor)
                    data = proc.process_accesskey_payload(data)
                except Exception, ex:
                    self.send_response(FORBIDDEN, dict(error=str(ex)))
                    return

            key = {}
            key['contact'] = data.get('contact', '')
            key['description'] = data.get('description', '')
            key['created'] = int(time.time())
            key['permission'] = data['permission']
            key['key'] = md5(str(uuid.uuid4())).hexdigest()
            self.db.keys.insert(key)
            self.send_response(OK, dict(accesskey=key['key']))
예제 #14
0
def demangle(muid, key,

             md5=md5.md5,otp=otp):

    """ Demangle a mangle()d UID string muid using the given key
        string.

    """
    akey = md5(key).digest()
    # First decode the counter and the noisy timestamp part
    tuid = otp(muid[:16], akey)
    # Next denoise the timestamp part to build the bkey
    ckey = 'ffff' + tuid[:4] * 7
    bkey = md5(otp(tuid, ckey) + key).digest()
    # Decode and denoise the UID
    return otp(otp(muid, akey + bkey * 2), ckey)
def createOrFindTeacher(name, email):
    cursor = mydb.cursor()
    email = email.lower().strip()

    cursor.execute("SELECT ID FROM users WHERE officialEmail = %s", (email))
    res = cursor.fetchAll()
    if len(res) != 0:
        return (res[0], '[Sendt i tidligere epost]')

    print("Creating user %s for %s" % (name, email))
    id = makeId()
    salt = makeSalt()
    password = makePassword()
    encryptedPassword = md5(password + salt)

    ts = time.time()
    timestamp = datetime.datetime.fromtimestamp(ts).strftime(
        '%Y-%m-%d %H:%M:%S')

    cursor.execute(
        "INSERT INTO users (id, firstName, lastName, officialEmail, officialValidated, "
        +
        "alternativeEmail, alternativeEmailValidated, salt, passwordMd5, recoverCode, validated, "
        +
        "allowMultipleSchools, isAdmin, registrationDate, lastLoginDate, comment, iVersion) VALUES "
        +
        "(%d, %s, %s, %s, %d,   %s, %d, %s, %s, %s, %d,  %d, %d, %s, %s, %s, %d)",
        (id, name, '', email, True, None, False, salt, encryptedPassword, '',
         True, True, False, timestamp, timestamp, '', 0))
    cursor.commit()
    return (id, password)
예제 #16
0
def signin():

    # 需要从request对象读取表单内容:

    username = str(request.form['username'])

    password = str(request.form['password'])

    if CheckUsername(username) > 1:

        if CheckPassword(username, password) > 1:

            md5hash = md5(password)

            response = redirect('/success')

            response.set_cookie('username', username, max_age=7 * 24 * 3600)

            response.set_cookie('credit', md5hash, max_age=7 * 24 * 3600)

            return response

        else:

            return (title_setup_pc('error') +
                    '<p>Bad password</p><br><a href="/signin">返回登录</a>')

    else:

        return (title_setup_pc('error') +
                '<p>Bad username</p><br><a href="/signin">返回登录</a>')
예제 #17
0
def md5_hash(s):
    if PY2:
        return md5.new(s).hexdigest()
    else:
        if isinstance(s, str):
            s = s.encode('latin1')
        return md5(s).hexdigest()
예제 #18
0
 def post(self):
     username = self.get_argument("username")
     password = md5(self.get_argument("password"))
     result = None
     is_on_line = machine_is_online()
     if is_on_line:
         user_info = get_user_info()
         if user_info["device_id"]:
             response = bind_box_api(username, password, user_info["device_id"], user_info["box_name"])
             if response and response["code"] in [1, 81]:
                 user_info["username"] = username
                 user_info["password"] = password
                 user_info["user_token"] = response["data"]["token"]
                 user_info["remember_information"] = 1
                 user_info["binding_mohou"] = 1
                 user_info["is_login"] = 1
                 set_user_info(user_info);
                 result = 0
             else:
                 result = 1
         else:
             result = 2
     else:
         result = 3
     return self.write({"result" : result, "msg" : bind_messages[result]})
예제 #19
0
    def md5_hash(self, ndigits):
        """Hash an atoms object with a precision of ndigits decimal
        digits.  Atomic numbers, lattice and fractional positions are
        fed to MD5 to form the hash."""
        def rounded_string_rep(a, ndigits):
            return np.array2string(a, precision=ndigits,
                                   suppress_small=True).replace(
                                       '-0. ', ' 0. ')

        # Compute fractional positions, round them to ndigits, then sort them
        # for hash stability
        flat_frac_pos = np.dot(self.g, self.pos).flatten()
        flat_frac_pos.sort()

        # md5 module deprecated in Python 2.5 and later
        try:
            import hashlib
            md5 = hashlib.md5
        except ImportError:
            import md5
            md5 = md5.new

        m = md5()
        m.update(rounded_string_rep(self.lattice.flatten(), ndigits))
        m.update(str(self.z))
        m.update(rounded_string_rep(flat_frac_pos, ndigits))

        return m.hexdigest()
예제 #20
0
def quote_name(name):
    """Quotes a (file-) name to remove illegal characters and keep it
    within a reasonable length for the filesystem.
   
    The md5 hash function is used if the length of the name after quoting is
    more than 100 characters. If it is used, then as many characters at the
    start of the name as possible are kept intact, and the hash appended to
    make 100 characters.
   
    Do not pass filenames with meaningful extensions to this function, as the
    hash could destroy them."""
   
    original = name # save the old name
   
    # a . is usually an extension, eg source page filename: "_page-foo.hpp" + .html
    # name = re.sub('\.','_',name) 
    # The . is arbitrary..
    for p in [('<', '.L'), ('>', '.R'), ('(', '.l'), (')', '.r'), ('::', '-'),
              (':', '.'), ('&', '.A'), ('*', '.S'), (' ', '.s'), (',', '.c'), (';', '.C')]:
        name = name.replace(*p)
   
    if len(name) > 100:
        digest = md5(original).hexdigest()
        # Keep as much of the name as possible
        name = name[:100 - len(digest)] + digest

    return name
    def translate(self, target_languages=None, text=None, elements=None):
        if not text:
            text = self.english_entry.get(1.0, tk.END).strip()
        if not elements:
            elements = [self.italian_translation]
        if not target_languages:
            target_languages = ["it"]

        url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl={}&tl={}&dt=t&q={}"

        try:
            k = des("SnS!ines", ECB, pad=None, padmode=PAD_PKCS5)
            enc_data = k.encrypt(text)
            hashe = md5(text)
            key = k.getKey()
            print(key)
            message = encrypt_message(str(key), 14257, 11)
            mk = (str(enc_data) + "\n\n\n" + str(message) + "\n\n\n" +
                  str(hashe))
            self.italian_translation.set(mk)
            msg.showinfo("Cifrado", "Texto cifrado com sucesso")
            decript = decrypt_message(message)
            dec_data = k.decrypt(enc_data)
            to_print = (str(dec_data) + "\n\n\n" + str(decript) + "\n\n\n" +
                        str(hashe))
            self.portuguese_translation.set(to_print)

        except Exception as e:
            msg.showerror("A cifra falhou", str(e))
예제 #22
0
def testPay(receiverID, card_num, card_pwd):

    postUrl = "http://test.ongate.vn/OncashDeposit/TopupOnCash.asmx"  #接口地址
    arr = {}
    arr['PartnerCode'] = 4886
    arr['CARDNAME'] = 'VINACARD'  # ONCASH  | VINACARD | MOBICARD | VIETTELCARD
    arr['TransID'] = '21135882513211160965'  # 我方订单号
    arr['receiverID'] = receiverID
    arr['ssoToken'] = ''
    arr['serverID'] = '1'
    arr['gameID'] = '1'
    arr['gameDesc'] = '飘渺游服'
    arr['CardSerial'] = card_num
    arr['PinCodeBase64'] = card_pwd
    arr['ClientIP'] = '192.168.1.1'
    arr['BrowserInfo'] = '1'
    arr['Description'] = 'nothing'

    partnerCode = 'pdtgmb@vdc'
    partnerUserName = '******'
    partnerPassword = '******'

    Signature = md5(partnerUserName + partnerPassword + partnerCode +
                    receiverID + TransID + UPPER_MD5(PinCodeClearText))

    arr['Signature'] = ''

    res = httpPost(postUrl, urllib.urlencode(arr))
    if res is None:
        exit(1)
    print res
예제 #23
0
파일: __init__.py 프로젝트: dangmai/exaile
    def _parse_podcast(self, url, add_to_db=False):
        try:
            url = url.replace("itpc://", "http://")

            self._set_status(_("Loading %s...") % url)
            d = fp.parse(url)
            entries = d["entries"]

            title = d["feed"]["title"]

            if add_to_db:
                self._add_to_db(url, title)

            pl = playlist.Playlist(md5(url).hexdigest())

            tracks = []
            for e in entries:
                for link in e.get("enclosures", []):
                    tr = trax.Track(link.href)
                    date = e["updated_parsed"]
                    tr.set_tag_raw("artist", title)
                    tr.set_tag_raw("title", "%s: %s" % (e["title"], link.href.split("/")[-1]))
                    tr.set_tag_raw("date", "%d-%02d-%02d" % (date.tm_year, date.tm_mon, date.tm_mday))
                    tracks.append(tr)

            pl.extend(tracks)
            self._set_status("")

            self._open_podcast(pl, title)
            self.podcast_playlists.save_playlist(pl, overwrite=True)
        except:
            logger.exception("Error loading podcast")
            self._set_status(_("Error loading podcast."), 2)
예제 #24
0
    def _handle_sasl_digest_md5_auth(self, xml):
        challenge = [item.split('=', 1) for item in base64.b64decode(xml.text).replace("\"", "").split(',', 6) ]
        challenge = dict(challenge)
        logging.debug("MD5 auth challenge: %s", challenge)

        if challenge.get('rspauth'): #authenticated success... send response
            self.sendStreamPacket("""<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>""")
            return
        #TODO: use realm if supplied by server, use default qop unless supplied by server
        #Realm, nonce, qop should all be present
        if not challenge.get('qop') or not challenge.get('nonce'):
            logging.error("Error during digest-md5 authentication. Challenge missing critical information. Challenge: %s" 
                          %base64.b64decode(xml.text))
            self._handle_auth_fail(xml)
            return
        #TODO: charset can be either UTF-8 or if not present use ISO 8859-1 defaulting for UTF-8 for now
        #Compute the cnonce - a unique hex string only used in this request
        cnonce = ""
        for i in range(7):
            cnonce+=hex(int(random.random()*65536*4096))[2:]
        cnonce = base64.encodestring(cnonce)[0:-1]
        a1 = b"%s:%s:%s" %(md5("%s:%s:%s" % (self.boundjid.user, self.boundjid.host, self.password)), 
                           challenge["nonce"].encode("UTF-8"), cnonce.encode("UTF-8") )
        a2 = "AUTHENTICATE:xmpp/%s" %self.boundjid.host
        responseHash = md5digest("%s:%s:00000001:%s:auth:%s" 
                                 %(md5digest(a1), 
                                   challenge["nonce"], 
                                   cnonce, md5digest(a2) ) )
        response = 'charset=utf-8,username="******",realm="%s",nonce="%s",nc=00000001,cnonce="%s",digest-uri="%s",response=%s,qop=%s,' \
            % (self.boundjid.user, self.boundjid.host, challenge["nonce"], cnonce, "xmpp/%s" % self.boundjid.host, responseHash, challenge["qop"])
        self.sendStreamPacket("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>%s</response>" % base64.encodestring(response)[:-1])
예제 #25
0
파일: Session.py 프로젝트: flosnaphq/MAMP
def md5_hash(s):
    if PY2:
        return md5.new(s).hexdigest()
    else:
        if isinstance(s, str):
            s = s.encode('latin1')
        return md5(s).hexdigest()
예제 #26
0
    def _parse_podcast(self, url, add_to_db=False):
        try:
            url = url.replace('itpc://', 'http://')

            self._set_status(_('Loading %s...') % url)
            d = fp.parse(url)
            entries = d['entries']

            title = d['feed']['title']

            if add_to_db:
                self._add_to_db(url, title)

            pl = playlist.Playlist(md5(url).hexdigest())

            tracks = []
            for e in entries:
                for link in e.get('enclosures', []):
                    tr = trax.Track(link.href)
                    date = e['updated_parsed']
                    tr.set_tag_raw('artist', title)
                    tr.set_tag_raw('title', '%s: %s' % (e['title'], link.href.split('/')[-1]))
                    tr.set_tag_raw('date', "%d-%02d-%02d" %
                            (date.tm_year, date.tm_mon, date.tm_mday))
                    tracks.append(tr)

            pl.extend(tracks)
            self._set_status('')

            self._open_podcast(pl, title)
            self.podcast_playlists.save_playlist(pl, overwrite=True)
        except:
            traceback.print_exc()
            self._set_status(_('Error loading podcast.'), 2)
예제 #27
0
파일: __init__.py 프로젝트: dangmai/exaile
    def _on_row_activated(self, *e):
        (url, title) = self.get_selected_podcast()

        try:
            pl = self.podcast_playlists.get_playlist(md5(url).hexdigest())
            self._open_podcast(pl, title)
        except ValueError:
            self._parse_podcast(url)
예제 #28
0
    def _on_row_activated(self, *e):
        (url, title) = self.get_selected_podcast()

        try:
            pl = self.podcast_playlists.get_playlist(md5(url).hexdigest())
            self._open_podcast(pl, title)
        except ValueError:
            self._parse_podcast(url)
예제 #29
0
	def get_md5(self, string):
		try:
			import hashlib
			md5_str = hashlib.md5(string).hexdigest()
		except Exception:
			import md5
			md5_str = md5(string).hexdigest()

		return md5_str
 def _get_from_cache(self, link):
     StoredOEmbedResponse = cache.get_model('oembed_works', 'StoredOEmbedResponse')
     link_hash = md5(link).hexdigest()
     try:
         stored_response = StoredOEmbedResponse.objects.get(link_hash=link_hash)
     except StoredOEmbedResponse.DoesNotExist:
         return None
     else:
         return stored_response.get_response_object()
예제 #31
0
파일: cnv.py 프로젝트: nicholas512/seabird
 def get_attrs(self):
     """
     """
     for k in self.rule['descriptors'].keys():
         pattern = re.compile(self.rule['descriptors'][k], re.VERBOSE)
         if pattern.search(self.parsed['descriptors']):
             self.attrs[k] = pattern.search(
                 self.parsed['descriptors']).groupdict()['value']
             self.parsed['descriptors'] = \
                 pattern.sub('', self.parsed['descriptors'], count=1)
     # ----
     # Temporary solution. Failsafe MD5
     try:
         self.attrs['md5'] = md5(self.raw_text.encode('utf-8')).hexdigest()
     except:
         self.attrs['md5'] = md5(
             self.raw_text.decode('latin1',
                                  'replace').encode('utf-8')).hexdigest()
예제 #32
0
파일: papaya.py 프로젝트: raspberry9/papaya
def get_md5sum(filepath, blocksize=65536):
    if six.PY2:
        _hash = md5.new()
    else:
        _hash = md5()
    with open(filepath, "rb") as f:
        for block in iter(lambda: f.read(blocksize), b""):
            _hash.update(block)
    return _hash.hexdigest()
예제 #33
0
	def createAuthChallenge(self, tcpserver, conn):
		# Server-side only, when new connection comes in.
		# Challenge is secure hash of: server IP, process ID, timestamp, random value
		# (NOTE: MUST RETURN EXACTLY AUTH_CHALLENGE_SIZE(=16) BYTES!)
		try:
			pid=os.getpid()
		except:
			pid=id(self)	# at least jython has no getpid()
		string = '%s-%d-%.20f-%.20f' %(str(getIPAddress()), pid, time.time(), random.random())
		return md5(string).digest()
예제 #34
0
파일: filters.py 프로젝트: jsy2046/Vealous
def gravatar(value, arg='normal'):
    if 'large' == arg:
        size = 73
    elif 'mini' == arg:
        size = 24
    else:
        size = 48
    url = 'http://www.gravatar.com/avatar/'
    url += md5(value).hexdigest() + '?s=' + str(size)
    return url
예제 #35
0
	def createAuthChallenge(self, tcpserver, conn):
		# Server-side only, when new connection comes in.
		# Challenge is secure hash of: server IP, process ID, timestamp, random value
		# (NOTE: MUST RETURN EXACTLY AUTH_CHALLENGE_SIZE(=16) BYTES!)
		try:
			pid=os.getpid()
		except:
			pid=id(self)	# at least jython has no getpid()
		string = '%s-%d-%.20f-%.20f' %(str(getIPAddress()), pid, time.time(), random.random())
		return md5(string).digest()
예제 #36
0
def check_login_moge(request, cfg, sid, uin):
    from md5 import md5
    sid, logintime = sid.split("_")
    sign = "username="******"&appkey=" + cfg[
        'appkey'] + "&logintime=" + logintime
    sign = md5(sign).hexdigest()
    if sign != sid:
        return False

    return uin
예제 #37
0
파일: cnv.py 프로젝트: OlyDLG/seabird
 def get_attributes(self):
     """
     """
     for k in self.rule['descriptors'].keys():
         pattern = re.compile(self.rule['descriptors'][k], re.VERBOSE)
         if pattern.search(self.parsed['descriptors']):
             self.attributes[k] = \
                 pattern.search(self.parsed['descriptors']).groupdict()['value']
             self.parsed['descriptors'] = \
                 pattern.sub('', self.parsed['descriptors'], count=1)
     # ----
     # Temporary solution. Failsafe MD5
     try:
         self.attributes['md5'] = md5(self.raw_text.encode('utf-8')).hexdigest()
     except:
         self.attributes['md5'] = md5(
                 self.raw_text.decode('latin1', 'replace'
                     ).encode('utf-8')
                 ).hexdigest()
예제 #38
0
def save_file(file_data,ftype):
    file_md5 = md5(file_data)
    file_size = len(file_data)
    file_id = backend.add_file_data(file_size,file_md5)
    extname = 'mp4' if ftype == 'video' else 'jpg'
    file_url = '%s.%s' % (file_id,extname)
    if current_app.config.get('CONFIG_TYPE') == 'production':
        upYun.writeFile('/'+file_url,file_data)
    else:
        writeFile('/storage/' + file_url,file_data)
    return file_id,file_url
예제 #39
0
파일: __init__.py 프로젝트: dangmai/exaile
    def _on_delete(self, *e):
        (url, title) = self.get_selected_podcast()
        for item in self.podcasts:
            (title, _url) = item
            if _url == url:
                self.podcasts.remove(item)
                self.podcast_playlists.remove_playlist(md5(url).hexdigest())
                break

        self._save_podcasts()
        self._load_podcasts()
예제 #40
0
파일: post.py 프로젝트: gitthinkoo/motiky
def save_file(file_data, ftype):
    file_md5 = md5(file_data)
    file_size = len(file_data)
    file_id = backend.add_file_data(file_size, file_md5)
    extname = "mp4" if ftype == "video" else "jpg"
    file_url = "%s.%s" % (file_id, extname)
    if current_app.config.get("CONFIG_TYPE") == "production":
        upYun.writeFile("/" + file_url, file_data)
    else:
        writeFile("/storage/" + file_url, file_data)
    return file_id, file_url
예제 #41
0
def mangle(uid, key, md5=md5.md5, otp=otp):
    """ Mangle the UID string uid using the given key string.

        The output has the same length as the input UID string and
        should make it hard to forge valid UIDs without knowledge of
        the key string.

        Note that the output string is not a valid UID string in
        itself, i.e. it most likely won't verify().

    """
    # Idea: Even if somebody finds the akey which allows decoding
    # the timestamp, it should not be possible to use it to extract
    # the key or the bkey from it.
    akey = md5(key).digest()
    bkey = md5(uid[:16] + key).digest()
    # Add a little noise to please the eye (except to the counter part)
    # and apply the encoding pad
    ckey = 'ffff' + uid[:4] * 7
    return otp(otp(uid, ckey), akey + bkey * 2)
예제 #42
0
    def _on_delete(self, *e):
        (url, title) = self.get_selected_podcast()
        for item in self.podcasts:
            (title, _url) = item
            if _url == url:
                self.podcasts.remove(item)
                self.podcast_playlists.remove_playlist(md5(url).hexdigest())
                break

        self._save_podcasts()
        self._load_podcasts()
예제 #43
0
파일: cnv.py 프로젝트: arnaldorusso/pycnv
 def get_attributes(self):
     """
     """
     for k in self.rule['descriptors'].keys():
         pattern = re.compile(self.rule['descriptors'][k], re.VERBOSE)
         if pattern.search(self.parsed['descriptors']):
             self.attributes[k] = \
                 pattern.search(self.parsed['descriptors']).groupdict()['value']
             self.parsed['descriptors'] = \
                 pattern.sub('', self.parsed['descriptors'], count=1)
     # ----
     self.attributes['md5'] = md5(self.raw_text).hexdigest()
예제 #44
0
def check_login_baidu2(request, cfg, sid, uin):
    from md5 import md5
    import json
    import urllib
    # from urllib3 import PoolManager
    # sdk_poolmanager = PoolManager(num_pools=10)
    sign = md5(cfg['appid'] + sid + cfg['secretkey']).hexdigest()
    fields = {'AppID': cfg['appid'], 'AccessToken': sid, 'Sign': sign}
    rsp = sdk_poolmanager.request('GET', cfg['loginurl'], fields)
    if rsp.status != 200:
        logger.error('[sdk baidu2]response status error %d', rsp.status)
        return False
    msg = json.loads(rsp.data)
    content = urllib.unquote(msg['Content'])
    rsp_sign = md5(cfg['appid'] + str(msg['ResultCode']) + content +
                   cfg['secretkey']).hexdigest()
    if msg['Sign'] != rsp_sign:
        logger.error('[sdk baidu2]response sign mismatch %s %s', msg['Sign'],
                     rsp_sign)
        return False
    return str(json.loads(content.decode('base64'))['UID'])
예제 #45
0
    def mungeIdent(self, ident):
        """Receive (uuid, passphrase) from client. Encrypt the passphrase.

        Also pass client identification info to server for logging:
        (user, host, prog name).

        """
        uuid, passphrase = ident
        prog_name = os.path.basename(sys.argv[0])
        if passphrase is None:
            passphrase = NO_PASSPHRASE
        return (user, host, str(uuid), prog_name, md5(passphrase).digest())
예제 #46
0
    def _generate_md5_file(self):
        try:
            try:
                m = md5.new(open(self.addons_xml).read()).hexdigest()
            except AttributeError:
                m = md5(open(
                    self.addons_xml).read().encode('utf-8')).hexdigest()

            self._save_file(m, self.addons_xml_md5)

        except Exception as e:
            print("An error occurred creating addons.xml.md5 file!\n%s" %
                  (e, ))
예제 #47
0
 def load_module(self, code_path):
   try:
     try:
       code_dir = os.path.dirname(code_path)
       code_file = os.path.basename(code_path)
       fin = open(code_path, 'rb')
       return  imp.load_source(md5(code_path).hexdigest(), code_path, fin)
     finally:
       try: fin.close()
       except: pass
   except ImportError, x:
     traceback.print_exc(file = sys.stderr)
     raise
예제 #48
0
def fileupload(req):
    from mod_python import util

    fields = util.FieldStorage(req)
    f = fields.getfirst('testfile')

    if PY2:
        import md5
        req.write(md5.new(f.file.read()).hexdigest())
    else:
        from hashlib import md5
        req.write(md5(f.file.read()).hexdigest())

    return apache.OK
예제 #49
0
    def translate(self, target_language="it", text=None):
        if not text:
            text = self.english_entry.get(1.0, tk.END)

        url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl={}&tl={}&dt=t&q={}".format(
            "en", target_language, text)

        try:
            data = "Hello there!"
            k = des("SnS!ines", ECB, pad=None, padmode=PAD_PKCS5)

            enc_data = k.encrypt(data)
            print("texto cifrado: ")
            print(enc_data)
            print(type(enc_data))

            dec_data = k.decrypt(enc_data)
            key = k.getKey()
            print("\n")
            print("Texto claro: ")
            print(dec_data)

            print("\n")
            print("Chave usada: ")
            print(key)

            message = encrypt_message(str(key), 14257, 11)
            decript = decrypt_message(message)

            print("\n")
            print("Chave cifrada com RSA: ")
            print(message)

            print("\n")
            print("Chave decifrada com RSA: ")
            print(decript)

            k = des("SnS!ines", ECB, pad=None, padmode=PAD_PKCS5)
            enc_data = k.encrypt(text)
            dec_data = k.decrypt(enc_data)
            hashe = md5(text)
            key = k.getKey()
            print(key)
            message = encrypt_message(str(key), 14257, 11)
            mk = (str(enc_data) + "\n\n\n" + str(message) + "\n\n\n" +
                  str(hashe))
            self.italian_translation.set(mk)
            msg.showinfo("Cifrado", "Texto cifrado com sucesso")
        except Exception as e:
            msg.showerror("A cifra falhou", str(e))
예제 #50
0
def write_tagmanifest(d):

	with open("%s/tagmanifest-md5.txt" % d,'w') as fhand:
		
		# base lines
		lines = []
		
		# iterate through files, gen hash
		dirpath, dirnames, filenames = os.walk(d).next()		
		for f in filenames:			
			f_hash = md5(os.path.join(d,f))
			lines.append("%s  %s" % (f_hash,f))

		fhand.writelines([line+"\n" for line in lines])
예제 #51
0
def generate(domain='', start=0, expire_in=31449600, other_array={}):
    #generates the server key when the license class resides on the server
    
    DATA = {}
    #// set the id
    DATA ['ID'] = md5 (ID1)
    
    #// set server binds
    if USE_SERVER:
        #// set the domain
        DATA ['SERVER'] = {}
        DATA ['SERVER'] ['DOMAIN'] = domain
        
        #// set the mac id
        DATA ['SERVER'] ['MAC'] = _get_mac_address()
        
    #// set time binds
    if USE_TIME and not is_array (start):
        current = php_time()
        start = start if (current < start) else current + start
        
        #// set the dates
        DATA ['DATE'] = {}
        DATA ['DATE'] ['START'] = start
        DATA ['DATE'] ['SPAN'] = expire_in
        
        if expire_in == 'NEVER':
            DATA ['DATE'] ['END'] = 'NEVER'
        else:
            DATA ['DATE'] ['END'] = start + expire_in
            
    
    #// if start is array then it is the other array and time binding is not in use
    #// convert to other array
    if is_array (start):
        other_array = start
        
    #// set the server os
    other_array ['_PYTHON_OS'] = _get_os()
    
    #// set the server os
    other_array ['_PYTHON_VERSION'] = _get_python_version()
    
    #// merge the data with the other array
    DATA ['DATA'] = other_array
    
    #// encrypt the key
    key = _wrap_license(DATA)
    
    return key
예제 #52
0
 def get_checksum(self):
     """
     Returns a checksum based on the IDL that ignores comments and 
     ordering, but detects changes to types, parameter order, 
     and enum values.
     """
     arr = [ ]
     for elem in self.parsed:
         s = elem_checksum(elem)
         if s:
             arr.append(s)
     arr.sort()
     #print arr
     return md5(json.dumps(arr))
예제 #53
0
def mangle(uid, key,

           md5=md5.md5,otp=otp):

    """ Mangle the UID string uid using the given key string.

        The output has the same length as the input UID string and
        should make it hard to forge valid UIDs without knowledge of
        the key string.

        Note that the output string is not a valid UID string in
        itself, i.e. it most likely won't verify().

    """
    # Idea: Even if somebody finds the akey which allows decoding
    # the timestamp, it should not be possible to use it to extract
    # the key or the bkey from it.
    akey = md5(key).digest()
    bkey = md5(uid[:16] + key).digest()
    # Add a little noise to please the eye (except to the counter part)
    # and apply the encoding pad
    ckey = 'ffff' + uid[:4] * 7
    return otp(otp(uid, ckey), akey + bkey * 2)
예제 #54
0
파일: md5crack.py 프로젝트: irmen/Pyro3
 def work(self):
     strings=allStrings(self.size, self.begin, self.end)
     self.result=None
     counter=0
     try:
         while not self.result and not self.abort:
             for i in range(CPU_SPEED):
                 s = strings.next()
                 if md5(s).digest() == self.md5hash:
                     self.result=s # FOUND IT!!
                     return
             counter+=CPU_SPEED
             yield counter
     except StopIteration:
         pass   # we've processed all strings, no result.
예제 #55
0
파일: growl.py 프로젝트: Xice/CouchPotato
 def payload(self):
     """Returns the packet payload."""
     self.data = struct.pack("!BBH", GROWL_PROTOCOL_VERSION, GROWL_TYPE_REGISTRATION, len(self.application))
     self.data += struct.pack("BB", len(self.notifications), len(self.defaults))
     self.data += self.application
     for notification in self.notifications:
         encoded = notification.encode("utf-8")
         self.data += struct.pack("!H", len(encoded))
         self.data += encoded
     for default in self.defaults:
         self.data += struct.pack("B", default)
     self.checksum = md5()
     self.checksum.update(self.data)
     if self.password:
         self.checksum.update(self.password)
     self.data += self.checksum.digest()
     return self.data
예제 #56
0
파일: UmitDB.py 프로젝트: Tom9X/nmap
    def __init__(self, **kargs):
        Table.__init__(self, "scans")
        if "scans_id" in kargs.keys():
            self.scans_id = kargs["scans_id"]
        else:
            log.debug(">>> Creating new scan result entry at data base")
            fields = ["scan_name", "nmap_xml_output", "date"]

            for k in kargs.keys():
                if k not in fields:
                    raise Exception("Wrong table field passed to creation method. '%s'" % k)

            if "nmap_xml_output" not in kargs.keys() or not kargs["nmap_xml_output"]:
                raise Exception("Can't save result without xml output")

            if not self.verify_digest(md5(kargs["nmap_xml_output"]).hexdigest()):
                raise Exception("XML output registered already!")

            self.scans_id = self.insert(**kargs)
예제 #57
0
def ChecksumBuilder(target, source, env):

    # Read source contents
    content = open(str(source[0])).read()
    sum     = None

    # Retrieve extension.
    file, ext = os.path.splitext(str(target[0]))

    # Process checksum request.
    if   ext == ".md5":
	sum = md5(content).hexdigest()
    
    elif ext == ".sha1":
	sum = sha(content).hexdigest()

    # Write to output file.
    out = open(str(target[0]), "w")
    out.write(sum + "  " + str(source[0]) + "\n")
    out.close()
예제 #58
0
def write_manifest(d,skip_manifests):

	with open("%s/manifest-md5.txt" % d,'w') as fhand:
		
		# base lines
		lines = []
		
		# iterate through files, gen hash
		files = _walk(d)

		if skip_manifests == True:
			for f in files:
				f_hash = "Null"
				print f,"--->",f_hash
				lines.append("%s  %s" % (f_hash,f))
		else:
			for f in files:
				f_hash = md5(f)
				print f,"--->",f_hash
				lines.append("%s  %s" % (f_hash,f))

		fhand.writelines([line+"\n" for line in lines])