def __init__(self, pipe, key, root): rpyc.Service.__init__(self) self.pipe = pipe self.secret = key # secret between the filesystem and this system time.sleep(15) self.base_path = root self.fileid_filename_secret_nonce_length = self.base_path + '/conf/medium.csv' self.filename_admin = self.base_path + '/conf/filess.csv' self.occupied = self.base_path + '/conf/occupied.csv' self.filename_listofusers = self.base_path + '/conf/abcd.csv' self.authenticated = [] self.authenticated_users = {} # users and their passwords self.admin_keys = {} self.nonce = {} self.pipe.send(self.fileid_filename_secret_nonce_length) self.pipe.send(self.filename_admin) self.pipe.send(self.filename_listofusers) self.pipe.send(self.occupied) self.cip = ChaCha20Poly1305(hashlib.sha256(self.secret).digest()) key = RSA.generate(2048) binprivkey = key.exportKey('DER') privk = RSA.importKey(binprivkey) self.privkey = privk a = 1 << 41824 with open(self.occupied, 'w') as f: nonce = self.pipe.recv() self.pipe.send(self.cip.encrypt(nonce), bytearray(nonce)) csvr = csv.writer(f) for i in range(10737): csvr.writerow(['0', a])
def decrypt(privkey, nonce, ciphertext): nonce = top_up_nonce(nonce) pubkey, ciphertext = PublicKey(pubkey=ciphertext[:33], raw=True), ciphertext[33:] shared_key = pubkey.ecdh(privkey.private_key) aead = ChaCha20Poly1305(shared_key, 'python') res = aead.open(nonce, ciphertext, b'') if res is None: raise Exception("Cant decrypt") return res
def encrypt_chacha(infile:str,chacha_key_file:str,outfile:str): key1 = open(chacha_key_file,'rb') key = key1.read(32) nonce = key1.read(12) key1.close() cip = ChaCha20Poly1305(key) head = b'\x45\x6e\x63\x56' enc = cip.encrypt(nonce, read_files(infile)) md5dat = md5(enc) w_files(outfile,head+md5dat+enc)
def modify_encriptor(key, symmetricAlgorithm): """ Returns a new encriptor by using a new key and depending on the symmetric algorithm specified. Fernet and ChaCha20Poly1305 supported. """ if symmetricAlgorithm == "fernet": return Fernet(key.encode("utf-8")) elif symmetricAlgorithm == "chacha": return ChaCha20Poly1305(key.encode("latin-1")) return None
def decrypt_chacha(infile:str,chacha_key_file:str,outfile:str): key1 = open(chacha_key_file,'rb') key = key1.read(32) nonce = key1.read(12) with open(infile,'rb') as fp: head = fp.read(4) md5out = fp.read(16) data = fp.read() if not (head == b'\x45\x6e\x63\x56') or not (md5out == md5(data)): print('Error: File corrupted.') sys.exit(1) cip = ChaCha20Poly1305(key) w_files (outfile,cip.decrypt(nonce, data))
def __init__(self, private_key): """ Create ciphering object which is responsible for all ciphering operation on data. Decrypting data demands generating two nonce's because probability that generated nonce had to late time base and decryption fails therefore provided key was appropriate. :param private_key: security access key """ self.private_key = str(private_key) self.cipher = ChaCha20Poly1305( sha256(private_key.encode("utf-8")).digest()) self.current_nonce = "" self.previous_nonce = "" self.decrypt_data_success = False self.decrypted_data = {} self.input_data_to_encrypt = {}
def getkey(option): nonce_12 = 0 try: key = getpass.getpass("Enter passphrase: ") res = password_check(key) if (option == "-c" and type(res) is tuple): if res[0] is True: print("Password length must be at least 12 characters") if res[1] is True: print("Password must contain at least one digit") if res[2] is True: print("Password must contain at least one uppercase character") if res[3] is True: print("Password must contain at least one lowercase character") if res[4] is True: print("Password must contain at least one symbol/special character") print("Exiting...") exit(0) except KeyboardInterrupt: print("Exiting...") exit(0) if (option == "-c"): try: key2 = getpass.getpass("Check entered passphrase: ") except KeyboardInterrupt: print("\nExiting...\n") exit(0) if (key != key2): print("passphrase does not match!") print("exiting...") exit(0) else: milli = round(time.time() * 1000) msk = randrange(100000000000000000,999999999999999999) print("Creating nonce...") spinner = itertools.cycle(['-', '/', '|', '\\']) for xor, sr in lfsr(milli,msk): sys.stdout.write(next(spinner)) # write the next character sys.stdout.flush() # flush stdout buffer (actual character display) sys.stdout.write('\b') # erase the last written char nonce_12 = hashlib.sha3_256(str(sr).encode()).digest()[:12] key_32 = hashlib.sha256(key.encode()).digest() cipher = ChaCha20Poly1305(key_32) return key_32,nonce_12,cipher
def g_file_access(userid, password, filename): import rpyc c = rpyc.connect('localhost',50001) d1 = pyDH.DiffieHellman key = d1.gen_public_key() with open('.wrapCloud/userid/local/userid','w') as f: userid = f.read() r = c.root.file_access(userid, hashlib.sha256(password).digest(), filename, key) k = r[0] file = r[1] nonce = r[2] try: shared_key = d1.gen_shared_key(k) from chacha20poly1305 import ChaCha20Poly1305 cip = ChaCha20Poly1305(hashlib.sha256(shared_key).digest()) file = cip.decrypt(nonce,file) return file except: return None
def decrypt(d): dev_id = d[0:4] cmd = d[4:6] timetag = d[6:12] nonce = d[12:24] tag = d[24:40] alen = d[40:42] data = d[42:] secret_key = ''.join(map(chr, xrange(0, 16))) * 2 pt = "%016u" % struct.unpack('>I', dev_id)[0] master_key = AES.new(secret_key).encrypt(pt).encode('hex') session_key = str( Poly1305(bytearray(master_key)).create_tag( bytearray(timetag))).encode('hex') cip = ChaCha20Poly1305(bytearray(session_key)) ct = cip.decrypt(bytearray(nonce), bytearray(data + tag), associated_data=bytearray(dev_id)) return str(ct)
def encrypt(pubkey, nonce, plaintext): ''' Encrypt plaintext for some pubkey (owner of corresponding privkey can decrypt). params: pubkey: secp256k1_py PublicKey object nonce: 12 bytes nonce, should not be reused plaintext: bytes object with arbitrary length. Inner logic: 1) generate ephemereal (one time) private_key. 2) generate shared_secret : ecdh of private_key and receiver's pubkey 3) symmetrically encrypt plaintext with shared_secret (encryption with ChaCha20Poly1305) 4) attach ephemereal public_key to ciphertext ''' nonce = top_up_nonce(nonce) ephemeral_privkey = PrivateKey() shared_key = pubkey.ecdh(ephemeral_privkey.private_key) aead = ChaCha20Poly1305(shared_key, 'python') res = aead.seal(nonce, plaintext, b'') res = ephemeral_privkey.pubkey.serialize() + res return res
def __init__(self, root): self.root = root self.value = "parent" key = RSA.generate(2048) binPrivKey = key.exportKey('DER') binPubKey = key.publickey().exportKey('DER') privKeyObj = RSA.importKey(binPrivKey) pubKeyObj = RSA.importKey(binPubKey) try: newpid = os.fork() except: return 'service not started' if newpid == 0: time.sleep(2) os.system("python server.py " + str(root)) else: privilegedProcessPipeEnd, unprivilegedProcessPipeEnd = Pipe() unprivilegedProcess = Process( target=DH(unprivilegedProcessPipeEnd).share_key(root)) unprivilegedProcess.start() d1 = pyDH.DiffieHellman() d1_key = d1.gen_public_key() privilegedProcessPipeEnd.send(d1_key) d2_key = privilegedProcessPipeEnd.recv() shared_key = d1.gen_shared_key(d2_key) self.shared_key = shared_key # GroupService self.privilegedProcessPipeEnd = privilegedProcessPipeEnd self._ = privilegedProcessPipeEnd.recv() self._1 = privilegedProcessPipeEnd.recv() self._2 = privilegedProcessPipeEnd.recv() self._3 = privilegedProcessPipeEnd.recv() self.__ = ChaCha20Poly1305(hashlib.sha256(shared_key).digest()) del d1 del d2_key
def g_file_upload(admin_id, filepath, password,0): import rpyc c = rpyc.connect('localhost', 50001) filename = raw_input('Enter filename:') try: with open('.wrapCloud/userid/local/userid','w') as f: userid = f.read() with open(filepath,'r') as f: file = f.read() except: return 'something wrong with your filepath' try: [nonce, shared_key] = g_file_admin_request(userid,password) except: return 'sorry, request cannot be made!' cip = ChaCha20Poly1305(hashlib.sha256(shared_key).digest()) file = cip.encrypt(nonce,bytearray(file)) try: r = c.root.file_upoad(userid,file,hashlib.sha256(password).digest(),filename, 0) except: pass return r
def encrypt(dev_id, data): secret_key = ''.join(map(chr, xrange(0, 16))) * 2 pt = "%016u" % struct.unpack('>I', dev_id)[0] master_key = AES.new(secret_key).encrypt(pt).encode('hex') timetag = get_timetag() session_key = str( Poly1305(bytearray(master_key)).create_tag( bytearray(timetag))).encode('hex') cip = ChaCha20Poly1305(bytearray(session_key)) nonce = get_randstr(12) ct = cip.encrypt(bytearray(nonce), bytearray(data), associated_data=bytearray(dev_id)) # packet p = '' p += dev_id p += '\xff\xff' p += timetag p += nonce p += str(ct)[-16:] p += struct.pack('>H', len((str(data)))) p += str(ct)[:-16] return p
def on_receive_message_1(client, userdata, msg): """ Handles the registration request coming from a device. Check the algorithms specified by this device and proceed as indicated to negotiate a shared key (HAND-SHAKE). It builds the message 2 to be sent to the device with the ephemeral public key of the platform for the DH or ECDH process. """ global encriptor, shared_key global asymmetricAlgorithm, symmetricAlgorithm # Received message 1 for the registration process auth = msg.get("auth", "") if auth != "": asymmetricAlgorithm = auth.get("asymmetric", "") if asymmetricAlgorithm == "dh": g = auth.get("g", "") p = auth.get("p", "") device_pub_key = auth.get("public_key", "") if g == "" and p == "" and device_pub_key == "": # Cannot be empty. return False # Generate private key and public key for platform # in the registration process pn = dh.DHParameterNumbers(p, g) parameters = pn.parameters(default_backend()) private_key, public_key = utils.dhGenKeys(parameters) # Generate shared key device_pub_key = utils.load_key(device_pub_key) shared_key = utils.dhGenSharedKey(private_key, device_pub_key) # Building message two. answer_registration_request = { "auth": { "public_key": public_key.public_bytes( Encoding.PEM,\ PublicFormat.SubjectPublicKeyInfo ).decode( "utf-8" ) } } elif asymmetricAlgorithm == "ecdh": x = auth.get("x", "") y = auth.get("y", "") if x == "" and y == "": # Cannot be empty. return False private_key, public_key = utils.ecdhGenKeys(utils.curve) device_pub_key = ec.Point(utils.curve, x, y) shared_key = utils.ecdhGenSharedKey(private_key, device_pub_key) # Building message two. answer_registration_request = { "auth": { "x": public_key.x, "y": public_key.y } } if shared_key == "": # Cannot be empty. return False symmetricAlgorithm = auth.get("symmetric", "") if symmetricAlgorithm == "fernet": encriptor = Fernet(base64.urlsafe_b64encode(shared_key)) elif symmetricAlgorithm == "chacha": encriptor = ChaCha20Poly1305(shared_key) message = add_header_message( answer_registration_request, userdata,\ REGISTRATION_TOPIC, 2 ) utils.send(client, None, message) return True return False
from chacha20poly1305 import ChaCha20Poly1305 # See https://pypi.org/project/chacha20poly1305/ key = bytearray([ 0x87, 0x20, 0xe8, 0x62, 0x76, 0x29, 0xc2, 0x85, 0x85, 0x02, 0x30, 0xfe, 0xfa, 0x32, 0x36, 0x57, 0x28, 0x97, 0x32, 0xcb, 0x9f, 0x00, 0xa6, 0x79, 0xd5, 0x20, 0x61, 0x60, 0x45, 0x4d, 0x84, 0xd0 ]) iv = bytearray([0,0,0,0,0,0,0,0,0,0,0,0]) cip = ChaCha20Poly1305(key) ciphertext = cip.encrypt(iv, b'abcd') print(ciphertext) plaintext = cip.decrypt(iv, ciphertext) print(plaintext)
#creates a random nonce from the system nonce = os.urandom(12) #generates both a private and a public key key, pub_key = keys.gen_keypair(curve.P256) #converts that key intro a string and chops it to 32 characters key = str(key) key = key[0:32] #encodes the key encoded = str.encode(key) #uses ChaCha20Poly1305 algorithm on it cip = ChaCha20Poly1305(encoded) #encrypts and saves in cipthertext variable ciphertext = cip.encrypt(nonce, str.encode(text).strip()) def encrypt(): #opens a file and saves the cipthertext f = open('my_file', 'wb') binary_format = bytearray(ciphertext) f.write(binary_format) f.close() print(ciphertext) def decrypt():
def exposed_file_upload(self, admin_id, file, password, filename, update=0, *args): # password for preventing the attacks password = hashlib.sha256(str(password)).digest() if self.authenticated_users[admin_id] != password: return 'wrong password, operation not allowed' fileid = random.SystemRandom().randint(0, pow(32, 7)) cip = ChaCha20Poly1305( hashlib.sha256(self.admin_keys[admin_id]).digest()) n = len(file) / 127 fileid = random.SystemRandom().randint(1, pow(32, 6) - 2) list = [] c = 0 f = open(self.occupied, 'r') nonce = self.pipe.recv() self.pipe.send(self.cip.encrypt(nonce, bytearray(nonce))) r = csv.reader(f, delimiter=",") d = list(r) f.close() while c < n: v = self.privkey.encrypt(long(fileid), 'x')[0] % pow(32, 6) + 1 r = v / 41824 x = v % 41824 if d[r][1] & (1 << x) != 0: list = [] fileid = random.SystemRandom().randint(1, pow(32, 6) - 2) c = 0 continue list.append(v) fileid = v for a in list: row = a / 41824 x = a % 41824 if x == 0: d[row][0] = '1' else: d[row][1] = d[row][1] | (1 << x) for a in range(n): value = list[a] #print 'value is :'+str(value) n = 32 level = 50 path = "" while level > 1: level = int( math.floor(math.log(((n - 1) * (value + 1) + 1), n))) position = (((value - ((pow(n, level) - 1) / (n - 1) - 1)) % n)) # print 'position is :'+str(position) if position == 0: position = n path = str(position) + "/" + path value = int(math.floor((value - 1) / n)) base_path = self.base_path path = base_path + "/" + path #print path+'file' with open(path + "file", "wb") as fil: nonce_ = self.pipe.recv() self.pipe.send(self.cip.encrypt(nonce_, bytearray(nonce_))) try: fil.write(filee[a * 127:a * 127 + 127]) except: return "error" # update the csv files. # update filename_admin try: with open(self.filename_admin, 'w') as f: nonce = self.pipe.recv() self.pipe.send(self.cip.encrypt(nonce, bytearray(nonce))) w = csv.writer(f) w.writerow([filename, hashlib.sha256(admin_id).digest()]) with open(self.filename_listofusers, 'w') as f: nonce = self.pipe.recv() self.pipe.send(self.cip.encrypt(nonce, bytearray(nonce))) w = csv.writer(f) w.writerow([filename, hashlib.sha256(admin_id).digest()]) with open(self.fileid_filename_secret_nonce_length, 'w') as f: nonce = self.pipe.recv() self.pipe.send(self.cip.encrypt(nonce, bytearray(nonce))) w = csv.writer(f) w.writerow([ fileid, filename, self.admin_keys[admin_id], self.nonce[admin_id] ]) with open(self.occupied, 'w') as f: nonce = self.pipe.recv() self.pipe.send(self.cip.encrypt(nonce, bytearray(nonce))) w = csv.writer(f) w.writerows(d) except: with open(self.filename_admin, 'r') as f_r: nonce = self.pipe.recv() self.pipe.send(self.cip.encrypt(nonce, bytearray(nonce))) r = csv.reader(f_r, delimiter=",") d1 = list(r) for row in d1: if row[0] == filename: d1.remove(row) break with open(self.filename_admin, 'w') as f_w: nonce = self.pipe.recv() self.pipe.send(self.cip.encrypt(nonce, bytearray(nonce))) w = csv.writer(f_w) w.writerows(d1) with open(self.filename_listofusers, 'r') as f_r: nonce = self.pipe.recv() self.pipe.send(self.cip.encrypt(nonce, bytearray(nonce))) r = csv.reader(f_r, delimiter=",") d = list(r) for row in d: if row[0] == filename: d.remove(row) break with open(self.filename_listofusers, 'w') as f_w: nonce = self.pipe.recv() self.pipe.send(self.cip.encrypt(nonce, bytearray(nonce))) w = csv.writer(f_w) w.writerows(d) with open(self.fileid_filename_secret_nonce_length, 'r') as f_r: nonce = self.pipe.recv() self.pipe.send(self.cip.encrypt(nonce, bytearray(nonce))) r = csv.reader(f_r, delimiter=",") d = list(r) for row in d: if row[0] == filename: d.remove(row) break with open(self.fileid_filename_secret_nonce_length, 'w') as f_w: nonce = self.pipe.recv() self.pipe.send(self.cip.encrypt(nonce, bytearray(nonce))) w = csv.writer(f_w) w.writerows(d) return 'error' return "okay"
words = argv[1] addr = argv[2] entropy = Mnemonic('english').to_entropy(words) cborEnt = cbor.dumps(bytes(entropy)) seed = blake2b(cborEnt, digest_size=32) cborSeed = cbor.dumps(seed.digest()) for i in range(1, 1000): buf = hmac.new(cborSeed, b'Root Seed Chain %d' % i, sha512).digest() buf_l, buf_r = buf[:32], buf[32:] if sha512(buf_l).digest()[31] & 32 == 0: bip32 = ed25519.SigningKey(buf_l) break xpub = bip32.vk_s + buf_r decodedAddr = b58decode(addr) loadedAddr = cbor.loads(decodedAddr) address = cbor.loads(loadedAddr[0].value) addrAttributes = cbor.loads(address[1][1]) nonce = b'serokellfore' hdpass = PBKDF2(xpub, 'address-hashing', iterations=500, digestmodule=sha512).read(32) cip = ChaCha20Poly1305(hdpass) decryptedAttr = cip.decrypt(nonce, addrAttributes) decryptedAttr = cbor.loads(decryptedAttr) print("Decrypted data:", decryptedAttr)
def connect(server, port, user, password, t): """ Start KMS. It will start the RESTful at port 5000 and start the Key Rotation process. """ global topicsPublishNewKeys global secretRegisteredDevices # Initiate Flask as a new thread. start_flask() # Load the information saved of the registered devices. topicsPublishNewKeys = load_registered_device_topics() secretRegisteredDevices = load_registered_device_secrets() # Connect to MQTT Server. client = mqtt.Client(client_id=KMS_ID) client.username_pw_set(user, password) client.connect(server, port, 60) client.loop_start() while True: # Start key rotation process. Send a new key for each device according to # its symmetric algorithm specified. for device, topic in topicsPublishNewKeys.items(): device_keys = secretRegisteredDevices[device]["secrets"] old_key = device_keys.get("0", "") if old_key != "": # Generates a new key if secretRegisteredDevices[device]["symmetric"] == "fernet": new_key = Fernet.generate_key().decode("utf-8") elif secretRegisteredDevices[device]["symmetric"] == "chacha": new_key = os.urandom(32).decode("latin-1") if new_key != "": # Rotate keys. Discard the oldest key. if device_keys.get("1", "") != "": old_key = device_keys.get("1") secretRegisteredDevices[device]["secrets"][ "0"] = old_key secretRegisteredDevices[device]["secrets"]["1"] = new_key if secretRegisteredDevices[device][ "symmetric"] == "fernet": encriptor = Fernet(old_key.encode()) elif secretRegisteredDevices[device][ "symmetric"] == "chacha": encriptor = ChaCha20Poly1305(old_key.encode("latin-1")) # Send the new generated key to the device secret_message = {"deviceID": device, "key": new_key} message = add_header_message(secret_message, topic) utils.send(client, encriptor, message) else: print( "Device: ", device, " has not a first key. \ Remove it from list and connect it again.") # Save all changes into the `secret.json` file with open(SECRET_FILE, 'w') as file: json.dump(secretRegisteredDevices, file, indent=4) time.sleep(t)
def __init__(self, password): self.aead = None self.password = password if self.password: self.raw_private_key = sha256(self.password.encode("utf-8")) self.aead = ChaCha20Poly1305(self.raw_private_key, 'python')
def decrypt(key, ciphertext): cip = ChaCha20Poly1305(key) return bytes(cip.decrypt(b'\x00' * 12, ciphertext))
def exposed_file_access(self, userid, password, filename, client_key): # check if the user is logged p = hashlib.sha256(password).digest() if self.authenticated_users[admin_id] != password: return 'login_again' # check if the user is allowed to access the files a = False with open(self.filename_listofusers, 'r') as f: nonce = self.pipe.recv() self.pipe.send(self.cip.encrypt(nonce), bytearray(nonce)) r = csv.reader(f, delimiter=",") d = list(r) for ro in d: if ro[0] == filename: for e in ro: if e == userid: a = True if not a: return 'not allowed' with open(self.fileid_filename_secret_nonce_length, 'r') as f: nonce = self.pipe.recv() self.pipe.send(self.cip.encrypt(nonce), bytearray(nonce)) r = list(csv.reader(f, delimiter=",")) for rr in r: if rr[1] == filename: filid = rr[0] secr = rr[2] nonc = rr[3] n = rr[4] l = [] for i in range(n): v = self.privkey.encrypt(long(filid), 'x')[0] % pow(32, 6) + 1 l.append(v) filid = v f = "" cip = ChaCha20Poly1305(hashlib.sha256(secret).digest()) for a in range(n): value = list[a] #print 'value is :'+str(value) n = 32 level = 50 path = "" while level > 1: level = int( math.floor(math.log(((n - 1) * (value + 1) + 1), n))) position = (((value - ((pow(n, level) - 1) / (n - 1) - 1)) % n)) # print 'position is :'+str(position) if position == 0: position = n path = str(position) + "/" + path value = int(math.floor((value - 1) / n)) path = self.base_path + "/" + path #print path+'file' try: with open(path + "file", "rb") as fil: nonce = self.pipe.recv() self.pipe.send(self.cip.encrypt(nonce), bytearray(nonce)) f = f + str(cip.decrypt(nonc, fil.read())) except: return "error" d = pyDH.DiffieHellman() keyy = d.gen_public_key() shared_key = d.gen_shared_key(client_key) cip = ChaCha20Poly1305(hashlib.sha256(shared_key).digest()) nonce = os.urandom(12) return [keyy, cip.encrypt(nonce, bytearray(f)), nonce]
def encrypt(key, plaintext): cip = ChaCha20Poly1305(key) return bytes(cip.encrypt(b'\x00' * 12, plaintext))
import os, re import binascii from chacha20poly1305 import ChaCha20Poly1305 #inkeyx = int(input("[+] Key : ") keyx = binascii.unhexlify( inkeyx ) # 'dd7a5410eef857a4dace7375beb8097aeb2b26d077be6c6084c794b6a5a2ee88' ciphertextx = binascii.unhexlify( '70a66c7a1ebf4b99c963da1d97c96de6c3f70607f30516feaf5a223c5541') noncex = binascii.unhexlify('2f474660dd4a2d8756ca98f6') ### u can use input() if wnt here cip = ChaCha20Poly1305(keyx) ## key ciphertext = ciphertextx ## ciphertext to decrypt nonce = noncex ## nonce plaintext = cip.decrypt(nonce, ciphertext) print("") print(plaintext) print("")