当前位置: 首页>>代码示例>>Python>>正文


Python XOR.new方法代码示例

本文整理汇总了Python中Crypto.Cipher.XOR.new方法的典型用法代码示例。如果您正苦于以下问题:Python XOR.new方法的具体用法?Python XOR.new怎么用?Python XOR.new使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Crypto.Cipher.XOR的用法示例。


在下文中一共展示了XOR.new方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: encrypt_url

# 需要导入模块: from Crypto.Cipher import XOR [as 别名]
# 或者: from Crypto.Cipher.XOR import new [as 别名]
def encrypt_url(path, dl_filename=None):
    """
    Call this within your client app to generate a URL to query the
    Cryptostream WSGI app server with.
    
    path: (str) The URL path to the internal-flagged location
        on the Nginx server that the files will be served from via
        X-Accel-Redirect.
    dl_filename: (str/None) If specified, the file that the user downloads will
        be named according to the value, instead of from the name on 
        the filesystem.
    """
    # Encrypt the path and the timestamp.
    path = XOR.new(KEY).encrypt(path)
    ts = XOR.new(KEY).encrypt(time.time().__str__())
    # Encode path/ts to base 64.
    path = base64.b64encode(path)
    ts = base64.b64encode(ts)

    # This dict will get urlencoded as GET keywords.
    value_dict = {"path": path, "ts": ts}

    # Check for download filename override.
    if dl_filename:
        value_dict["dl_filename"] = dl_filename

    return urllib.urlencode(value_dict)
开发者ID:duointeractive,项目名称:cryptostream,代码行数:29,代码来源:main.py

示例2: initvars

# 需要导入模块: from Crypto.Cipher import XOR [as 别名]
# 或者: from Crypto.Cipher.XOR import new [as 别名]
def initvars():
	global Logueado
	Logueado = False
	config = ConfigParser()
	config.read("conf/config.ini")
	tipo = config.get('CUENTA', 'Tipo')
	ps = b64decode('MjAxMDE3MzMtOTYwOTkyNg==')
	xorps = XOR.new(str(ps))
	global Tipo
	Tipo = xorps.decrypt(b64decode(str(tipo)))
	webserver = config.get('WEB', 'srv')
	ps = b64decode('MjAxMDE3MzMtOTYwOTkyNg==')
	xorps = XOR.new(str(ps))
	global WEBServer
	WEBServer = xorps.decrypt(b64decode(str(webserver)))
	print WEBServer
	global DatosUsuario
	DatosUsuario = {}
	global DictSenales
	DictSenales = {}
	global BD
	BD = BasedeDatos()
	BD.Conectar()
	global DictColaResultados
	DictColaResultados = {}
	t = threading.Thread(target=GetIps)
	t.start()
开发者ID:smsalarmas,项目名称:SMSAlarmasDesktop,代码行数:29,代码来源:globalvars.py

示例3: xor_encode_dict

# 需要导入模块: from Crypto.Cipher import XOR [as 别名]
# 或者: from Crypto.Cipher.XOR import new [as 别名]
def xor_encode_dict(dictionary):
    """ Кодирует словарь алгоритмом XOR """
    result = {}
    for key, val in dictionary.iteritems():
        key = base64.encodestring(XOR.new(settings.XOR_KEY).encrypt(key))
        val = base64.encodestring(XOR.new(settings.XOR_KEY).encrypt(val))
        result[key] = val

    return result
开发者ID:wis-auralov,项目名称:statistic-analyzer,代码行数:11,代码来源:helpers.py

示例4: _getMAC

# 需要导入模块: from Crypto.Cipher import XOR [as 别名]
# 或者: from Crypto.Cipher.XOR import new [as 别名]
 def _getMAC(self, mac, key):
     modName = self.macMap[mac]
     if not modName:
         return None
     mod = __import__(modName, {}, {}, '')
     if not hasattr(mod, 'digest_size'):
         ds = len(mod.new().digest())
     else:
         ds = mod.digest_size
     key = key[: ds]+'\x00'*(64-ds)
     i = XOR.new('\x36').encrypt(key)
     o = XOR.new('\x5c').encrypt(key)
     return mod, i,o, ds
开发者ID:galaxysd,项目名称:BitTorrent,代码行数:15,代码来源:transport.py

示例5: app

# 需要导入模块: from Crypto.Cipher import XOR [as 别名]
# 或者: from Crypto.Cipher.XOR import new [as 别名]
def app(environ, start_response):
    """
    WSGI app method. You'll want to point your WSGI server at this method.
    """
    data = environ["PATH_INFO"]
    # GET querystring.
    qs = urlparse.parse_qs(environ["QUERY_STRING"])

    # Decode from base64.
    try:
        path = base64.b64decode(qs["path"][0])
        ts = base64.b64decode(qs["ts"][0])
    except:
        return render_error_page(environ, start_response)

    # Decrypt using XOR.
    try:
        path = XOR.new(KEY).decrypt(path)
        ts = datetime.datetime.fromtimestamp(float(XOR.new(KEY).decrypt(ts)))
    except:
        return render_error_page(environ, start_response)

    # Determine what the file will be named for the user's browser.
    if qs.has_key("dl_filename"):
        # Filename was passed as a GET keyword.
        dl_filename = qs["dl_filename"][0]
    else:
        # No filename specified, use the name on the filesystem.
        dl_filename = os.path.basename(path)

    dbg = path
    now = datetime.datetime.now()
    if (now - ts) > LINK_EXPIRE_TDELTA:
        # Expired, show vague error page.
        return render_error_page(environ, start_response)
    else:
        # Everything is good, serve the file through X-Accel-Redirect.
        status = "200 OK"

        response_headers = [
            ("X-Accel-Redirect", path),
            ("Content-Disposition", "attachment; filename=%s" % dl_filename),
        ]

        start_response(status, response_headers)
        # This needs to be an empty string or we'll get premature socket
        # closing errors. The body is ignored by Nginx, and the connection is
        # closed before this returned value can be read, causing the error.
        return ""
开发者ID:duointeractive,项目名称:cryptostream,代码行数:51,代码来源:main.py

示例6: token_json

# 需要导入模块: from Crypto.Cipher import XOR [as 别名]
# 或者: from Crypto.Cipher.XOR import new [as 别名]
 def token_json(self, uuid):
     crypt = XOR.new(self.password)
     str = "%s\n%s " % ( int(time.mktime(datetime.now().timetuple())), uuid)
     # I hate obfuscation.  Its all I've got
     token = crypt.encrypt(str)
     return dict(token=urllib.quote(token),
                 prefered_protocol=self.smolt_protocol)
开发者ID:MythTV,项目名称:smolt,代码行数:9,代码来源:token.py

示例7: get_key

# 需要导入模块: from Crypto.Cipher import XOR [as 别名]
# 或者: from Crypto.Cipher.XOR import new [as 别名]
def get_key(request):
	if (request.method != 'POST'):
		return err_GE002()
	form = GetKeyForm(request.POST)
	if (not form.is_valid()):
		return err_GE031(form)
	
	#dbkey = get_user_key(request, ss=form.cleaned_data['secret'])
	db_secret = request.device_assn.db_secret
	xor = XOR.new(base64.b64decode(form.cleaned_data['secret']))
	db_key = xor.encrypt(base64.b64decode(db_secret))
	
	if (not request.device_assn.verify_db_key(db_key)):
		return err_GE022()
	
	# Okay, we need to test the validity of this key before we return it.
	# Otherwise, we could return an invalid key.

	response = {
			'data': {
					'key':base64.b64encode(db_key),
#					'gcm_project_id': settings.GCM_PROJECT_ID
				},
			'warnings':{}
		}
	return HttpResponse(content=json.dumps(response), mimetype='application/json')
开发者ID:DongHuaLu,项目名称:mdcom,代码行数:28,代码来源:views_account.py

示例8: encrypt

# 需要导入模块: from Crypto.Cipher import XOR [as 别名]
# 或者: from Crypto.Cipher.XOR import new [as 别名]
    def encrypt(self, key, plaintext):
        (input_whitening_key, output_whitening_key) = self.build_whitening_keys(key)

        input_whitener = XOR.new(str(input_whitening_key)).encrypt
        output_whitener = XOR.new(str(output_whitening_key)).encrypt
        ciphertext = bytearray(len(plaintext))

        if (len(plaintext) % 8):
            raise Exception("plaintext length must be a multiple of 8")

        des = DES.new(str(key[0:8]), DES.MODE_CBC, str(bytearray(8))).encrypt
        for i in range(len(plaintext)/8):
            ciphertext[i*8:i*8+8] = bytearray(output_whitener(des(input_whitener(str(plaintext[i*8:i*8+8])))))
            des = DES.new(str(key[0:8]), DES.MODE_CBC, str(bytearray(8))).encrypt

        return ciphertext
开发者ID:woutervddn,项目名称:stratasys,代码行数:18,代码来源:crypto.py

示例9: xor_decrypt

# 需要导入模块: from Crypto.Cipher import XOR [as 别名]
# 或者: from Crypto.Cipher.XOR import new [as 别名]
 def xor_decrypt(raw):
     if cipher[0] is None:
         if len(raw) < AES.block_size:
             return None, 0
         cipher[0] = XOR.new(raw[: AES.block_size])
         return None, AES.block_size
     return cipher[0].decrypt(raw), len(raw)
开发者ID:binasc,项目名称:utils,代码行数:9,代码来源:obscure.py

示例10: decrypt_chunk

# 需要导入模块: from Crypto.Cipher import XOR [as 别名]
# 或者: from Crypto.Cipher.XOR import new [as 别名]
def decrypt_chunk(secret, fpath, queue):
    """
    @type secret: str
    @type fpath: str
    @type queue: multiprocessing.Queue
    """
    chunk_file = open(fpath.strip())
    chunk_pos_len = int(chunk_file.readline())
    chunk_pos = int(chunk_file.read(chunk_pos_len))
    initialization_vector_len = int(chunk_file.readline())
    initialization_vector = chunk_file.read(initialization_vector_len)
    data_hash_len = int(chunk_file.readline())
    data_hash = chunk_file.read(data_hash_len)
    enc_data_len = int(chunk_file.readline())
    enc_data = chunk_file.read(enc_data_len)
    if 16 != len(initialization_vector):
        raise Exception("initialization_vector len is not 16")

    #cipher = AES.new(secret, AES.MODE_CFB, IV=initialization_vector)
    cipher = XOR.new(secret)
    dec_data = cipher.decrypt(enc_data)
    calculated_hash = make_checksum(dec_data)
    if data_hash != calculated_hash:
        raise EncryptionHashMismatch("decrypt_file -> the decryption went wrong, hash didn't match")

    if queue.qsize() > 20:
        time.sleep(0.5)
    queue.put((chunk_pos, dec_data))
    return True
开发者ID:Active8-BV,项目名称:cryptobox_app,代码行数:31,代码来源:cba_crypto.py

示例11: encrypt_chunk

# 需要导入模块: from Crypto.Cipher import XOR [as 别名]
# 或者: from Crypto.Cipher.XOR import new [as 别名]
def encrypt_chunk(secret, fpath, chunksize, initialization_vector):
    """
    @param secret: pkdf2 secre
    @type secret: str
    @type fpath: str
    @type chunksize: tuple
    """
    try:
        f = open(fpath)
        f.seek(chunksize[0])
        chunk = f.read(chunksize[1])

        #cipher = AES.new(secret, AES.MODE_CFB, IV=initialization_vector)
        cipher = XOR.new(secret)
        data_hash = make_checksum(chunk)
        enc_data = cipher.encrypt(chunk)
        ntf = get_named_temporary_file(auto_delete=False)
        chunk_seek = str(chunksize[0])
        ntf.write(str(len(chunk_seek)) + "\n")
        ntf.write(chunk_seek)
        ntf.write(str(len(initialization_vector)) + "\n")
        ntf.write(initialization_vector)
        ntf.write(str(len(data_hash)) + "\n")
        ntf.write(data_hash)
        ntf.write(str(len(enc_data)) + "\n")
        ntf.write(enc_data)
        return ntf.name
    except Exception, e:
        raise e
开发者ID:Active8-BV,项目名称:cryptobox_app,代码行数:31,代码来源:cba_crypto.py

示例12: createciphermsgs_xor

# 需要导入模块: from Crypto.Cipher import XOR [as 别名]
# 或者: from Crypto.Cipher.XOR import new [as 别名]
def createciphermsgs_xor(jt65msgcount, stegmsg, key, verbose=False):
# Performs the actual XOR cipher

    ciphermsgs = []

    # Can we fit your hidden message?
    if jt65msgcount * 8 < len(stegmsg):
        print(
            "Length of hidden message exceeds capacity of number of valid JT65 messages provided")
        sys.exit(0)

    originallength = len(stegmsg)
    while len(stegmsg) % 8:
        stegmsg += chr(random.randint(0, 255))

    cryptobj = XOR.new(key)
    cipherdata = cryptobj.encrypt(stegmsg)
    cipherlist = list(bytearray(cipherdata))

    # Is the total length too big to fit into our max number of packets?
    if len(cipherlist) > MAX_MULTI_PACKET_STEG_BYTES_XOR:
        print("Length of hidden message exceeds capacity of multi-packet steg")
        sys.exit(0)
    totalpackets = len(cipherlist) / 8

    if verbose:
        print "Cipher list: " + str(cipherlist)

    createciphermsgs_packer_xor(
        totalpackets, originallength, ciphermsgs, cipherlist, verbose)

    return ciphermsgs
开发者ID:pdogg,项目名称:jt65stego,代码行数:34,代码来源:jt65stego.py

示例13: __init__

# 需要导入模块: from Crypto.Cipher import XOR [as 别名]
# 或者: from Crypto.Cipher.XOR import new [as 别名]
	def __init__(self):
		self.resultado = None
		#Buscando el archivo INI para saber el String de Conexion
		config = ConfigParser()
		config.read("conf/config.ini")
		self.conexioncifrada = config.get('BASE DE DATOS', 'conexion')
		PASSWORD = XOR.new(base64.b64decode('MjAxMDE3MzMtOTYwOTkyNg=='))
		self.conexion = PASSWORD.decrypt(base64.b64decode(str(self.conexioncifrada)))
开发者ID:smsalarmas,项目名称:GETA-8.1,代码行数:10,代码来源:bd.py

示例14: _xor

# 需要导入模块: from Crypto.Cipher import XOR [as 别名]
# 或者: from Crypto.Cipher.XOR import new [as 别名]
    def _xor(self, a, b):
        """Performs XOR on two strings a and b"""

        if len(a) != len(b):
            raise "ERROR: Strings are of different size! %s %s" % (len(a), len(b))

	xor = XOR.new(a)
	return xor.encrypt(b)
开发者ID:FooBarWidget,项目名称:revelation,代码行数:10,代码来源:PBKDFv2.py

示例15: fixkey

# 需要导入模块: from Crypto.Cipher import XOR [as 别名]
# 或者: from Crypto.Cipher.XOR import new [as 别名]
def fixkey(key):
	
	half1= key[:16]
	half2= key[16:]
	
	encryptor = XOR.new(half2)
	
	newkey= encryptor.encrypt(half1)
	return newkey
开发者ID:robins35,项目名称:Asguard,代码行数:11,代码来源:CAST_filecrypt.py


注:本文中的Crypto.Cipher.XOR.new方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。