本文整理汇总了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)
示例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()
示例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
示例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
示例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 ""
示例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)
示例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')
示例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
示例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)
示例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
示例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
示例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
示例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)))
示例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)
示例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