Exemplo n.º 1
0
def new_secure_hash(text_type=None):
    """
    Returns either a sha1 hash object (if called with no arguments), or a
    hexdigest of the sha1 hash of the argument `text_type`.
    """
    if text_type:
        return sha1(text_type).hexdigest()
    else:
        return sha1()
Exemplo n.º 2
0
def new_secure_hash(text_type=None):
    """
    Returns either a sha1 hash object (if called with no arguments), or a
    hexdigest of the sha1 hash of the argument `text_type`.
    """
    if text_type:
        return sha1(text_type).hexdigest()
    else:
        return sha1()
Exemplo n.º 3
0
    def getMusicBrainzDiscId(self):
        """
        Calculate the MusicBrainz disc ID.

        @rtype:   str
        @returns: the 28-character base64-encoded disc ID
        """
        if self.mbdiscid:
            self.log('getMusicBrainzDiscId: returning cached %r' %
                     self.mbdiscid)
            return self.mbdiscid
        values = self._getMusicBrainzValues()

        # MusicBrainz disc id does not take into account data tracks
        # P2.3
        try:
            import hashlib
            sha1 = hashlib.sha1
        except ImportError:
            from sha import sha as sha1
        import base64

        sha = sha1()

        # number of first track
        sha.update("%02X" % values[0])

        # number of last track
        sha.update("%02X" % values[1])

        sha.update("%08X" % values[2])

        # offsets of tracks
        for i in range(1, 100):
            try:
                offset = values[2 + i]
            except IndexError:
                #print 'track', i - 1, '0 offset'
                offset = 0
            sha.update("%08X" % offset)

        digest = sha.digest()
        assert len(digest) == 20, \
            "digest should be 20 chars, not %d" % len(digest)

        # The RFC822 spec uses +, /, and = characters, all of which are special
        # HTTP/URL characters. To avoid the problems with dealing with that, I
        # (Rob) used ., _, and -

        # base64 altchars specify replacements for + and /
        result = base64.b64encode(digest, '._')

        # now replace =
        result = "-".join(result.split("="))
        assert len(result) == 28, \
            "Result should be 28 characters, not %d" % len(result)

        self.log('getMusicBrainzDiscId: returning %r' % result)
        self.mbdiscid = result
        return result
Exemplo n.º 4
0
    def do_SSH_dhkex(self, payload):
        e = self.read_SSH_mpint(payload)
        #print(payload.getbuffer())
        #print(self.make_SSH_mpint(e))
        y = secrets.randbits(512)
        f = pow(dh.g, y, dh.p)
        K = pow(e, y, dh.p)
        self.shared_secret = K

        #print("Shared secret: {}".format(hex(K)))

        prehash = self.make_SSH_string(self.client_id_str)
        prehash += self.make_SSH_string(self.ID_STR)
        prehash += self.make_SSH_string(self.client_kexinit)
        prehash += self.make_SSH_string(self.server_kexinit)
        prehash += self.make_SSH_pubkeystr()
        prehash += self.make_SSH_mpint(e)
        prehash += self.make_SSH_mpint(f)
        prehash += self.make_SSH_mpint(K)

        print(prehash)

        H = sha.sha1(prehash)

        #print(H)

        packet = struct.pack("B", self.SSH_MSG_KEXDH_REPLY)
        packet += self.make_SSH_pubkeystr()
        packet += self.make_SSH_mpint(f)
        packet += self.make_SSH_rsasig(H)

        self.write_SSH_packet(packet)
        self.write_SSH_packet(struct.pack("B", self.SSH_MSG_NEWKEYS))
Exemplo n.º 5
0
    def getMusicBrainzDiscId(self):
        """
        Calculate the MusicBrainz disc ID.

        @rtype:   str
        @returns: the 28-character base64-encoded disc ID
        """
        if self.mbdiscid:
            logger.debug('getMusicBrainzDiscId: returning cached %r'
                         % self.mbdiscid)
            return self.mbdiscid
        values = self._getMusicBrainzValues()

        # MusicBrainz disc id does not take into account data tracks
        # P2.3
        try:
            import hashlib
            sha1 = hashlib.sha1
        except ImportError:
            from sha import sha as sha1
        import base64

        sha = sha1()

        # number of first track
        sha.update("%02X" % values[0])

        # number of last track
        sha.update("%02X" % values[1])

        sha.update("%08X" % values[2])

        # offsets of tracks
        for i in range(1, 100):
            try:
                offset = values[2 + i]
            except IndexError:
                #print 'track', i - 1, '0 offset'
                offset = 0
            sha.update("%08X" % offset)

        digest = sha.digest()
        assert len(digest) == 20, \
            "digest should be 20 chars, not %d" % len(digest)

        # The RFC822 spec uses +, /, and = characters, all of which are special
        # HTTP/URL characters. To avoid the problems with dealing with that, I
        # (Rob) used ., _, and -

        # base64 altchars specify replacements for + and /
        result = base64.b64encode(digest, '._')

        # now replace =
        result = "-".join(result.split("="))
        assert len(result) == 28, \
            "Result should be 28 characters, not %d" % len(result)

        logger.debug('getMusicBrainzDiscId: returning %r' % result)
        self.mbdiscid = result
        return result
Exemplo n.º 6
0
def TraktCall(method, api, username=None, password=None, data={}):
    """
    A generic method for communicating with trakt. Uses the method and data provided along
    with the auth info to send the command.

    method: The URL to use at trakt, relative, no leading slash.
    api: The API string to provide to trakt
    username: The username to use when logging in
    password: The unencrypted password to use when logging in

    Returns: A boolean representing success
    """

    #logger.log("trakt: Call method " + method, logger.DEBUG)

    # if the API isn't given then it failed
    if not api:
        return None

    # replace the API string with what we found
    method = method.replace("%API%", api)

    # make the full url
    url = 'https://api.trakt.tv/' + method

    # take the URL params and make a json object out of them
    encoded_data = json.JSONEncoder().encode(data)

    request = Request(url, encoded_data)

    # if the username isn't given then it failed
    if username and password:
        pwdsha1 = sha1(password).hexdigest()
        base64string = base64.encodestring(
            '%s:%s' % (username, pwdsha1)).replace('\n', '')
        request.add_header("Accept", "*/*")
        request.add_header("User-Agent", "CPython/2.7.5 Unknown/Unknown")
        request.add_header("Authorization", "Basic %s" % base64string)

    # request the URL from trakt and parse the result as json
    try:
        #logger.log("trakt: Calling method http://api.trakt.tv/" + method + ", with data" + encoded_data, logger.DEBUG)
        stream = urlopen(request).read()

        # check if results are valid
        if stream == '[]':
            resp = 'NULL'
        else:
            resp = json.JSONDecoder().decode(stream)

        if ("error" in resp):
            raise Exception(resp["error"])

    except (IOError):
        #logger.log("trakt: Failed calling method", logger.ERROR)
        return None

    #logger.log("trakt: Failed calling method", logger.ERROR)
    return resp
Exemplo n.º 7
0
def TraktCall(method, api, username=None, password=None, data={}):
    """
    A generic method for communicating with trakt. Uses the method and data provided along
    with the auth info to send the command.

    method: The URL to use at trakt, relative, no leading slash.
    api: The API string to provide to trakt
    username: The username to use when logging in
    password: The unencrypted password to use when logging in

    Returns: A boolean representing success
    """
    # logger.log("trakt: Call method " + method, logger.DEBUG)

    # if the API isn't given then it failed
    if not api:
        return None

    # replace the API string with what we found
    method = method.replace("%API%", api)

    # make the full url
    url = "https://api.trakt.tv/" + method

    # take the URL params and make a json object out of them
    encoded_data = json.JSONEncoder().encode(data)

    request = Request(url, encoded_data)

    # if the username isn't given then it failed
    if username and password:
        pwdsha1 = sha1(password).hexdigest()
        base64string = base64.encodestring("%s:%s" % (username, pwdsha1)).replace("\n", "")
        request.add_header("Accept", "*/*")
        request.add_header("User-Agent", "CPython/2.7.5 Unknown/Unknown")
        request.add_header("Authorization", "Basic %s" % base64string)

    # request the URL from trakt and parse the result as json
    try:
        # logger.log("trakt: Calling method http://api.trakt.tv/" + method + ", with data" + encoded_data, logger.DEBUG)
        stream = urlopen(request).read()

        # check if results are valid
        if stream == "[]":
            resp = "NULL"
        else:
            resp = json.JSONDecoder().decode(stream)

        if "error" in resp:
            raise Exception(resp["error"])

    except (IOError):
        # logger.log("trakt: Failed calling method", logger.ERROR)
        return None

    # logger.log("trakt: Failed calling method", logger.ERROR)
    return resp
def create_handshake(handshake):
    handshakelines = handshake.split("\r\n")
    matching = [s for s in handshakelines if "Sec-WebSocket-Key: " in s]

    returning_handshake = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "

    if(len(matching) > 0):
        returning_handshake+=base64.b64encode(sha.sha1((matching[0][19:]+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode(), False)).decode()
        returning_handshake+="\r\n\r\n"
    return returning_handshake
Exemplo n.º 9
0
	def _session_id():
		id_str = "%f%s%f%s" % (
			time.time(),
			id({}),
			random.random(),
			getpid()
		)
		# NB: nothing against second parameter to b64encode, but it seems
		#     to be slower than simple chained replacement
		raw_id = b64encode(sha1(id_str).digest())
		return raw_id.replace('+', '-').replace('/', '_').rstrip('=')
Exemplo n.º 10
0
def create_handshake(handshake):
    handshakelines = handshake.split("\r\n")
    matching = [s for s in handshakelines if "Sec-WebSocket-Key: " in s]

    returning_handshake = "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "

    if (len(matching) > 0):
        returning_handshake += base64.b64encode(
            sha.sha1((matching[0][19:] +
                      "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode(),
                     False)).decode()
        returning_handshake += "\r\n\r\n"
    return returning_handshake
Exemplo n.º 11
0
def sign(m, d, n):
    OIDSTR = b"\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14"
    h = sha.sha1(m)
    padded = b"\x00\x01" + b"\xFF" * (256 - 23 -
                                      len(OIDSTR)) + b"\x00" + OIDSTR + h
    c = 0
    for x in padded:
        c <<= 8
        c |= x
    sig = pow(c, d, n)
    output = b""
    for _ in range(2048 // 8):
        output = struct.pack("B", sig & 0xFF) + output
        sig >>= 8
    return output
Exemplo n.º 12
0
def make_hash_authorization_signature(method, url, date_string, company_id,
                                      user_id, nonce, api_key):
    s = ("%(method)s %(path)s\r\n"
         "Date: %(date_string)s\r\n"
         "X-SuT-CID: %(company_id)s\r\n"
         "X-SuT-UID: %(user_id)s\r\n"
         "X-SuT-Nonce: %(nonce)s\r\n"
         "%(api_key)s" % dict(method=method,
                              path=urllib_parse.urlparse(url).path.rstrip('/'),
                              date_string=date_string,
                              company_id=company_id,
                              user_id=user_id,
                              nonce=nonce,
                              api_key=api_key))
    return sha1(s.encode('utf-8')).hexdigest()
Exemplo n.º 13
0
def secret_to_key(secret, s2k_specifier):
    """Used to generate a hashed password string. DOCDOC."""
    c = ord(s2k_specifier[8])
    EXPBIAS = 6
    count = (16 + (c & 15)) << ((c >> 4) + EXPBIAS)

    d = sha1()
    tmp = s2k_specifier[:8] + secret
    slen = len(tmp)
    while count:
        if count > slen:
            d.update(tmp)
            count -= slen
        else:
            d.update(tmp[:count])
            count = 0
    return d.digest()
Exemplo n.º 14
0
def secret_to_key(secret, s2k_specifier):
  """Used to generate a hashed password string. DOCDOC."""
  c = ord(s2k_specifier[8])
  EXPBIAS = 6
  count = (16+(c&15)) << ((c>>4) + EXPBIAS)

  d = sha1()
  tmp = s2k_specifier[:8]+secret
  slen = len(tmp)
  while count:
    if count > slen:
      d.update(tmp)
      count -= slen
    else:
      d.update(tmp[:count])
      count = 0
  return d.digest()
Exemplo n.º 15
0
def hashAndBase64(s):
    return stringToBase64(sha1(s).digest())
Exemplo n.º 16
0
 def hashFunction(self, number):
     """ Fonction de hashage d'un entier, renvoie un autre entier issue du hashage"""
     
     hexe = number.to_bytes(self.bit_size//8, sys.byteorder)
     #return int.from_bytes(Hasher().digest(hexe), sys.byteorder)
     return int.from_bytes(str.encode(sha.sha1(str(hexe))), sys.byteorder)
Exemplo n.º 17
0
import socket  # Import socket module
import sha

s = socket.socket()  # Create a socket object
host = socket.gethostname()  # Get local machine name
port = 12345  # Reserve a port for your service.
s.bind((host, port))  # Bind to the port

s.listen(1)  # Now wait for client connection.
while True:
    c, addr = s.accept()  # Establish connection with client.
    print 'Got connection from ', addr
    data = raw_input("enter the data to be sent ")
    c.send(data)
    sh = sha.sha1(data)
    sh.process_data()
    msgD = sh.sha_1()
    print msgD
    c.send(msgD)
    data = ""
    c.close()  # Close the connection
Exemplo n.º 18
0
    def __decorate(func):

        rkey = sha1(str(time())).hexdigest()[:7]
        rkw = 'kw_%s' % rkey

        code = func.func_code
        varnames = list(code.co_varnames)
        defaults = func.func_defaults or ()
        func_name = func.func_name

        varargs = varkwargs = None

        if code.co_flags & CO_VARKEYWORDS:
            varkwargs = varnames.pop(-1)

        if code.co_flags & CO_VARARGS:
            varargs = varnames.pop(-1)

        params = [varnames.pop(0)]; add = params.append
        params2 = params[:]; add2 = params2.append
        default_pointer = len(varnames) - len(defaults)

        for idx, varname in enumerate(varnames):
            if idx < default_pointer:
                add(varname)
                add2("%s[%r]" % (rkw, varname))
            else:
                add("%s=defaults_%s[%s]" % (varname, rkey, idx-default_pointer))
                add2("%s=%s.get(%r, defaults_%s[%s])" % (varname, rkw, varname, rkey, idx-default_pointer))

        if varargs:
            add("*%s" % varargs)
            add2("*%s[%r]" % (rkw, varargs))
        if varkwargs:
            add("**%s" % varkwargs)
            add2("**%s[%r]" % (rkw, varkwargs))
            
        params = ", ".join(params)
        params2 = ", ".join(params2)

        source = """
def %(func_name)s(%(params)s):
    kws_%(r)s = locals()
    kw_%(r)s = {}
    for key_%(r)s in kws_%(r)s:
        if key_%(r)s in spec_%(r)s: 
            try:
                kw_%(r)s[key_%(r)s] = spec_%(r)s[key_%(r)s](kws_%(r)s[key_%(r)s])
            except Exception:
                raise ValueError(
                    "Could not validate input argument '%%s=%%s'" %% (key_%(r)s, kws_%(r)s[key_%(r)s])
                    )
        else:
            kw_%(r)s[key_%(r)s] = kws_%(r)s[key_%(r)s]
    return func_%(r)s(%(params2)s)
""" % dict(params=params, params2=params2, r=rkey, func_name=func_name)

        env = {
            'func_%s' % rkey: func,
            'spec_%s' % rkey: spec,
            'defaults_%s' % rkey: defaults,
            'ValueError': ValueError
            }
        exec source in env

        return env[func_name]
Exemplo n.º 19
0
import socket  # Import socket module
import sha

s = socket.socket()  # Create a socket object
host = socket.gethostname()  # Get local machine name
port = 12345  # Reserve a port for your service.

s.connect((host, port))
message = s.recv(1024)
print str(message)
msgD = s.recv(1024)
print str(msgD)
sh = sha.sha1(message)
sh.process_data()
msgD1 = sh.sha_1()
print msgD1
if msgD == msgD1:
    print "message is integrate."
elif msgD != msgD1:
    print "message not integrate"
s.close
Exemplo n.º 20
0
def sha_calculator(string):
    """Function to calculate sha1sum"""
    ans1 = sha1(string)
    return (ans1)
Exemplo n.º 21
0
 def __init__(self):
     self.MAGIC = sha1('[TL]').digest()
     self.KEY = sha1('TL-Cookies').digest()
Exemplo n.º 22
0
def hashAndBase64(s):
    return stringToBase64(sha1(s).digest())
Exemplo n.º 23
0
 def __init__(self):
     self.MAGIC = sha1('[TL]').digest()
     self.KEY   = sha1('TL-Cookies').digest()