示例#1
0
def CEupload(file_name):
    # Upload a file with convergent encryption (using the file's hash as its key).
    remote_file_name = base64.urlsafe_b64encode(enc.siv_encrypt(pbkey1, pbkey2, file_name, ""))
    content_file_name = remote_file_name + '.contents'
    key_file_name = remote_file_name + '.key'
    s = open(file_name, 'rb').read()
    key = hashlib.sha256(s).digest()[0:16]
    # print "key: " + key
    c1 = enc.encrypt(key, s)
    temp_contents = open("./tempc", "wb")
    temp_contents.write(c1)
    temp_contents.close()
    temp_contents = open("./tempc", "rb")
    hash_r = hmac.new(pbkey3, c1+remote_file_name+key, hashlib.sha256).digest()
    c2 = enc.encrypt(pbkey4, key + hash_r)
    temp_key = open("./tempk", "wb")
    temp_key.write(c2)
    temp_key.close()
    temp_key = open("./tempk", "rb")
    up_thread = Thread(
        target=dpbx_client.put_file, args=(content_file_name, temp_contents, True) )
    up_thread.start()
    dpbx_client.put_file(key_file_name, temp_key, True)
    up_thread.join()
    print file_name + " has been uploaded with convergent encryption."
    def encryptvote(self):
        """
        the data of the vote (in the votedata list) will be first hashed by SHA-256
        and then, the data will be converted into bytes and signed by voter's private key
        and that hashed signature will be appended with votedata itself
        """
        self.votedata.append(
            enc.sign(
                voterkeys['sk'],
                bytes(
                    sha256(
                        str('---'.join(str(x) for x in self.votedata)).encode(
                            'utf-8')).hexdigest(), 'utf-8')))
        """
        now that whole data (the new votedata list) will be encrypted by AES encryption
        and the shared key of AES will be encrypted with admin's public key
        this data will be broadcasted and saved into the unconfirmed votepool and will be added in the block
        """
        voterpk = self.get_voter_pk()

        #--byte value of voter public key pickle object is converted to string
        #--then added to list
        return [
            str(voterpk)[2:-1],
            aes.encrypt('***'.join(str(i) for i in self.votedata),
                        voterkeys['aeskey']),
            enc.encrypt(Blockchain.adminpub, voterkeys['aeskey'])
        ]
示例#3
0
 def enc_payload_str(self, payload: str) -> dict:
     '''
     payload是字符串,返回payload:{'_': 'base64-str'}
     '''
     c = self.get_cipher()
     bs = encrypt(c, payload)
     return {'_': b2a_base64_trimed(bs)}
示例#4
0
def p2pupload(file_name, info):
    # Upload a file.
    remote_file_name = base64.urlsafe_b64encode(enc.siv_encrypt(pbkey1, pbkey2, file_name, ""))
    content_file_name = remote_file_name + '.contents'
    key_file_name = remote_file_name + '.key'
    file_plaintext = open(file_name, 'rb').read()
    key = enc.get_convergent_key(file_plaintext, info)
    c1 = enc.encrypt(key, file_plaintext)
    temp_contents = open("./tempc", "wb")
    temp_contents.write(c1)
    temp_contents.close()
    temp_contents = open("./tempc", "rb")
    hash_r = hmac.new(pbkey3, c1+remote_file_name+key, hashlib.sha256).digest()
    c2 = enc.encrypt(pbkey4, key + hash_r)
    temp_key = open("./tempk", "wb")
    temp_key.write(c2)
    temp_key.close()
    temp_key = open("./tempk", "rb")
    up_thread = Thread(
        target=dpbx_client.put_file, args=(content_file_name, temp_contents, True) )
    up_thread.start()
    dpbx_client.put_file(key_file_name, temp_key, True)
    up_thread.join()
    print file_name + " has been uploaded with p2p encryption."
示例#5
0
def main():
    keysize = 32

    p, q, e, d, N = key_generate.generateKeys(keysize)
    msg = "%s" % (sys.argv[1])
    en = enc.encrypt(e, N, msg)
    de = dec.decrypt(d, N, en)

    print(f"p: {p}")
    print(f"q: {q}")
    print(f"Message: {msg}")
    print(f"e: {e}")
    print(f"d: {d}")
    print(f"N: {N}")
    print(f"enc: {en}")
    print(f"dec: {de}")
示例#6
0
def encryption(request):
    inp1 = request.POST.get('param1')
    en = enc.encrypt(e, N, inp1)
    return render(request, 'home.html', {'enc': en})
示例#7
0
        del dialog
        
        if not loginData:
            sys.exit()
        
        if not scraper.doLogin(loginData['email'], loginData['password']):
            xbmcgui.Dialog().ok('LOGIN', 'Email-ul sau parola sunt incorecte.')
            sys.exit()
        
        _email = loginData['email']
        _password = loginData['password']
        
        q = 'Sunteti de acord ca datele de logare sa fie salvate pe dispozitiv?'
        qd = xbmcgui.Dialog().yesno('LOGIN', q, '', '', 'NU', 'DA')
        if qd:
            common.setSetting('email', enc.encrypt(loginData['email']))
            common.setSetting('password', enc.encrypt(loginData['password']))

getUserCredentials()
scraper.setUserCredentials(_email, _password)


def main():
    addDir('Canale TV', '', 1, os.path.join(common.addon_path, 'resources', 'media', 'tvicon.png'))
    addDir('Stare Cont', '', 98, os.path.join(common.addon_path, 'resources', 'media', 'accountinfoicon.png'))
    addDir('Logout', '', 99, os.path.join(common.addon_path, 'resources', 'media', 'logouticon.png'))
    
    xbmcplugin.endOfDirectory(int(sys.argv[1]))    
    xbmc.executebuiltin('Container.SetViewMode(500)')

示例#8
0
    voterpriv, voterpub = enc.rsakeys()
    adminpriv, adminpub = enc.rsakeys()

    l = ['eee9ca050b625c9a8206beb29e5687d915f70aaa061993d9ea5bdf2041c66a26', 1, time.time()]
    #--all 3 elements of votedata appended together as a string and hashed
    #--hash converted to bytes
    #--then signed by voter's private key
    #--then appended back to the list
    l.append(enc.sign(voterpriv,bytes(sha256(str('---'.join(str(x) for x in l)).encode('utf-8')).hexdigest(),'utf-8')))
    #--now the list elements are again appended together as string and encrypted
    #--using the shared key
    #--this encrypted data is to be added to vote pool and sent to other as well.
    #--and the key must be encrypted by RSA algotithm using the public key of admin(reciever)

    vote = {'data': encrypt('***'.join(str(i) for i in l),get_private_key(pw)), 'key': enc.encrypt(adminpub,get_private_key(pw))}
    print(vote)
    #--decrypt key
    deckey = enc.decrypt(adminpriv,vote['key'])

    decrypted = decrypt(vote['data'],get_private_key(pw)).decode('utf-8')
    print(decrypted)
    ourdata = decrypted.split('***')
    ourdata[1] = int(ourdata[1])
    ourdata[2] = float(ourdata[2])
    ourdata[3] = bytes(((ourdata[3].replace('b\'','')).replace('\'','')),'utf-8')

    # First let us encrypt secret message
    # encrypted = encrypt("This is a secret message", pw)
    # print(encrypted)
    #
示例#9
0
    charge = dataList[2]
except IOError as e:
    print(e)
    lon = 56
    lat = 95
    charge = 100
    pass
while True:
    if float(charge) > 30:
        x = 0.97
    else:
        x = 1.03
    lon = float(lon) + (random.random() - 0.5) / 100
    lat = float(lat) + (random.random() - 0.5) / 100
    charge = float(charge) * x
    fakegps = '{"data":"' + str("{:.4f}".format(lon)) + ',' + str(
        "{:.4f}".format(lat)) + ',' + str(
            "{:.2f}".format(charge)) + '","ttl":60,"published_at":"' + str(
                timestamp) + '","coreid":"999999999999999999999999"}'
    data = json.loads(fakegps)
    gpsdata = data['data']
    dataList = gpsdata.split(',')
    gps_aes = enc.encrypt(str(data), str(pword))
    result = oraclesio.write2oracle(CHAIN, ORCLID, bytes.decode(gps_aes))
    while result == 'error':
        time.sleep(30)
        result = oraclesio.write2oracle(CHAIN, ORCLID, bytes.decode(gps_aes))
        print(result)
    gps_dec = enc.decrypt(gps_aes, pword)
    time.sleep(300)
    sg = np.dot(keys.SK, g) % keys.q
    div = np.rint((msg / sg).astype(np.float)).astype(np.int64)
    modes = np.unique(div, return_counts=True)
    modes = sorted(zip(modes[0], modes[1]), key=lambda t: -t[1])
    best_num = 0
    best_dist = float('inf')
    for mu, count in modes:
        dist = (msg - mu * sg) % keys.q
        dist = np.minimum(dist, keys.q - dist)
        #dist = np.linalg.norm(dist)
        dist = np.dot(dist, dist)
        if dist < best_dist:
            best_num = mu
            best_dist = dist
    return best_num


if __name__ == '__main__':
    from keygen import keygen
    from enc import encrypt
    keys = keygen(28)
    for idx in [34, 117, 62]:
        c = encrypt(keys, idx)
        m = decrypt(keys, c)
        print(" " * 12 + "Expected %d" % idx)
        print(" " * 12 + "Received %d" % m)
        if idx == m:
            print(" " * 12 + "\x1B[32;1mPassed\x1B[0m")
        else:
            print(" " * 12 + "\x1B[31;1mFailed\x1B[0m")
示例#11
0
import enc

key = "1234567890123456"
e = enc.cipher(key)
d = enc.cipher(key)
plain = "asfadsfasljasldkasdlfkasdkfnlkjfasjlkdsf"
data = enc.encrypt(e, plain)
plain2 = enc.decrypt(d, data)
print(plain2)
示例#12
0
homomorphic encryption scheme. GSW transforms a plaintext bit into a
ciphertext matrix and relies on the Decisional Learning With Errors
assumption for computational security.

Authors: Nolan Hedglin, Kade Phillips, Andrew Reilley '''

import numpy as np
from util import *
from keygen import keygen
from enc import encrypt, buildGadget
from dec import decrypt

keys = keygen(24)

for a, b in [(1, 1), (17, 19), (34, 62)]:
    ca = encrypt(keys, a)
    cb = encrypt(keys, b)
    a_b = a + b
    ca_cb = (ca + cb) % keys.q
    d_ca_cb = decrypt(keys, ca_cb)

    print(" " * 12 + "Expected %d" % a_b)
    print(" " * 12 + "Received %d" % d_ca_cb)
    if a_b == d_ca_cb:
        print(" " * 12 + "\x1B[32;1mPassed\x1B[0m")
    else:
        print(" " * 12 + "\x1B[31;1mFailed\x1B[0m")

ca = encrypt(keys, a)
cb = encrypt(keys, b)
a_b = a + a + a + b + b + b
示例#13
0
 def enc(self, data: str) -> bytes:
     c = self.get_cipher()
     return encrypt(c, data)
示例#14
0
def enc():
	enc = encrypt('plaintextasdfasdfsdffasdfg7gtfyrfytgugytvysafdsdfadsf', 'key1111111111111')

	return enc
示例#15
0
    del dialog

    if not loginData:
        sys.exit()

    if not scraper.doLogin(loginData['email'], loginData['password']):
        xbmcgui.Dialog().ok('LOGIN', 'Email-ul sau parola sunt incorecte.')
        sys.exit()

    _email = loginData['email']
    _password = loginData['password']

    q = 'Sunteti de acord ca datele de logare sa fie salvate pe dispozitiv?'
    qd = xbmcgui.Dialog().yesno('LOGIN', q, '', '', 'NU', 'DA')
    if qd:
        common.setSetting('email', enc.encrypt(loginData['email']))
        common.setSetting('password', enc.encrypt(loginData['password']))

getUserCredentials()
scraper.setUserCredentials(_email, _password)


def main():
    addDir('Canale TV', '', 1,
           os.path.join(common.addon_path, 'resources', 'media', 'tvicon.png'))
    addDir(
        'Stare Cont', '', 98,
        os.path.join(common.addon_path, 'resources', 'media',
                     'accountinfoicon.png'))
    addDir(
        'Logout', '', 99,
示例#16
0

@app.route('/fileupload', methods=['POST'])
def file_upload():
    file = request.files['file']
    pw = request.form['pw']
    passward = enc.getKey(pw)
    filename = secure_filename(file.filename)
    try:
        os.makedirs('./upload/file')
    except OSError, e:
        if e.errno != errno.EEXIST:
            raise
        pass
    file.save(os.path.join('./upload/file', filename))
    enc.encrypt(passward, './upload/file/' + file.filename)
    return render_template('down.html')


@app.route('/downfile', methods=['POST'])
def downfile():
    filename = request.form['filename']
    os.remove('./upload/file/' + filename)
    return send_file('./upload/file/' + filename + '.enc',
                     mimetype='text/txt',
                     as_attachment=True)


@app.route('/decryptfile', methods=['POST'])
def decrypt_file():
    pw = request.form['pw']
示例#17
0
			print('data: '+str(data))
			gpsdata = data['data']
			print('gpsdata: '+str(gpsdata))
			dataList = gpsdata.split(',')
			print('dataList length: '+str(len(dataList)))
			try :
				if len(dataList) == 3:
					lon = str(dataList[0])
					lat = str(dataList[1])
					charge = str(dataList[2])
					timestamp = int(time.time())
					#print('time: '+str(time))
					#print('lon: '+lon)
					#print('lat: '+lat)
					#print('c: '+charge)
					#print('---------------')
					gps = '{"data":"'+lon+','+lat+','+charge+'","published_at":"'+str(timestamp)+'"}'
					print(gps)
					gps_aes = enc.encrypt(gps,str(pword))
					print("aes: "+str(gps_aes))
					result = oraclesio.write2oracle(CHAIN, ORCLID, bytes.decode(gps_aes))
					while result == 'error':
						time.sleep(30)
						result = oraclesio.write2oracle(CHAIN, ORCLID, bytes.decode(gps_aes))
						print(result)	
					print('bytes.decode(aes): '+bytes.decode(gps_aes))
					gps_dec = enc.decrypt(gps_aes,pword)
					print('dec: '+bytes.decode(gps_dec))
			except Exception as e:
				print(e)
				pass
def gen_keyfile(in_file,password):
  with open("ckeys", 'wb') as keyfile:
    keys = enc.encrypt(in_file,keyfile,password)
  keyfile.close()