Example #1
0
def test():
    p1 = 790383132652258876190399065097
    q1 = 662503581792812531719955475509
    p2 = 656917682542437675078478868539
    q2 = 1263581691331332127259083713503
    n1 = p1 * q1
    n2 = p2 * q2
    ciphertext1 = Encrypt("attack", n1, 2)
    ciphertext2 = Encrypt("attack", n2, 2)
    message = DecipherHastad(ciphertext1, n1, ciphertext2, n2)
    print(message)
Example #2
0
def test():
    # Example usage with common prime p and different second primes q1 and q2
    p = 101
    q1 = 1829897073254110
    q2 = 1000000007
    first_modulo = p * q1
    second_modulo = p * q2
    first_exponent = 239
    second_exponent = 17
    first_ciphertext = Encrypt("attack", first_modulo, first_exponent)
    second_ciphertext = Encrypt("wait", second_modulo, second_exponent)
    print(
        DecipherCommonDivisor(first_ciphertext, first_modulo, first_exponent,
                              second_ciphertext, second_modulo,
                              second_exponent))
Example #3
0
 def searchbyName(self, name):
     encrypt = Encrypt()
     text_dir = {
         "hlpretag": "<span class=\"s-fc7\">",
         "hlposttag": "</span>",
         "s": name,
         "type": "1",
         "offset": "0",
         "total": "true",
         "limit": "30",
         "csrf_token": ""
     }
     text = str(text_dir)
     data = encrypt.getParamsAndSecKey(text)
     searchUrl = 'https://music.163.com/weapi/cloudsearch/get/web?csrf_token='
     try:
         response = requests.post(url=searchUrl,
                                  data=data,
                                  headers=self.headers)
         response.raise_for_status()
         response.encoding = 'utf-8'
         return response.json()
     except Exception as err:
         print(err)
         return '请求异常'
def test_encryption():
    # Define intputs to check
    mobile = "+447740193397"
    password_input = "456"
    password_encrypted = "LfrpS0GQHWrK7Bf3hymo2lY53xZVcIxthjTG92E5s97DpBgwIq0le5CkwxS5gy/r"

    verification_id_input = "5240822173794304"
    verification_id_encrypted = "5RCQVvDLFeIkbOKUkXq4xUfLOUJbF5piAtoLRtvFKhUbtJvvO7wV9cQXhtsQj5jq"

    # Create test object
    encrypt = Encrypt()

    # Test
    print('Test that a key has been loaded')
    assert len(encrypt.key) > 10

    # Test
    print('test encryption without a salt')
    e = encrypt.encryptString(verification_id_input)
    assert verification_id_encrypted == e

    # Test
    print('test encryption with a salt')
    e = encrypt.encryptString(password_input, mobile)
    assert password_encrypted == e

    print("Success")
    def get(self):
        if isDev(self.request.host):
            logging.info("creating test password records")
            for i in xrange(1, 11):
                created = datetime.now() - timedelta(days=i)

                mobileNumber = "+" + str(447700000000 + i)
                clue = "clue" + str(i)
                password = "******" + str(i)
                encrypt = Encrypt()
                e = encrypt.encryptString(password, mobileNumber)

                passwordStorerecord = PasswordStore()
                passwordStorerecord.clue = clue
                passwordStorerecord.mobileNumber = mobileNumber
                passwordStorerecord.encryptedPassword = e
                passwordStorerecord.confirmed = random.choice([0, 1])
                passwordStorerecord.created = created
                passwordStorerecord.put()

            logging.info("creating test verification records")
            for i in xrange(1, 11):
                created = datetime.now() - timedelta(days=i)
                verificationRecord = Verification()

                verificationRecord.action = random.choice(['delete', 'add'])
                verificationRecord.confirmed = random.choice([0, 1])
                verificationRecord.passwordStoreId = 1000 + i * 17
                verificationRecord.created = created
                verificationRecord.put()

            self.response.write("done")

        logging.warning("Tried to activate CleanUpTest not in dev")
Example #6
0
 def __init__(self, builtinDataDir, serverCfg, encryptCfg, crawlerCfg):
     self.encryptTool = Encrypt(encryptCfg)
     self.dao = DAO(serverCfg.get('database'))
     self.db = CrawlerDB(self.dao, builtinDataDir)
     self.crawlerQueryBuilder = self.__initialize_crawler__(
         builtinDataDir, crawlerCfg)
     self.worker = BlockingScheduler()
    def post(self):
        clue = self.request.get('clue')
        mobileNumber = "+44" + self.request.get('mobilenumber')

        query = PasswordStore.query(
            ndb.AND(
                PasswordStore.clue == clue,
                PasswordStore.mobileNumber == mobileNumber,
                PasswordStore.confirmed == 1)).order(-PasswordStore.created)
        result = query.fetch(1)

        if result:
            encrypt = Encrypt()

            #logging.info('found: ' + clue + " - " + mobileNumber)
            sms = SendSMS()
            sms.sendPassword(
                mobileNumber,
                encrypt.decryptString(result[0].encryptedPassword,
                                      mobileNumber))
        #else:
        #logging.info('not found: ' + clue + " - " + mobileNumber)

        template_values = {'nav': 'retrieve'}

        template = JINJA_ENVIRONMENT.get_template('templates/success.html')
        self.response.write(template.render(template_values))
Example #8
0
def secCmp(answer):
    """Compare security question answer against database answer."""

    if Encrypt().secQCmp(answer):
        return True
    else:
        return False
Example #9
0
 def loadMethod(self):
     if os.path.exists("./code.txt"):
         f = open('./code.txt', 'r')
         code = f.readline()
         self.e = Encrypt()
         self.e.setCode(code)
         self.displayText["text"] = "code: " + self.e.getCode()
     else:
         self.displayText["text"] = "Load denied!!"
Example #10
0
def editEntry(ow, ou, op, nw, nu, np):
    """Update database with new data for specific entry."""

    encryptObj = Encrypt()
    nw = encryptObj.encrypt(nw)
    nu = encryptObj.encrypt(nu)
    np = encryptObj.encrypt(np)

    dbq.updateEntry(ow, ou, op, nw, nu, np)
Example #11
0
def test():
    p = 1000000007
    q = 1000000009
    n = p * q
    e = 239
    ciphertext = Encrypt("attack", n, e)
    message = DecipherSmallDiff(ciphertext, n, e)
    print(ciphertext)
    print(message)
Example #12
0
 def __init__(self, IP, port):
     self.__IP = IP
     self.__port = port
     self.__add = (self.__IP, self.__port)
     self.__sock = None
     self.__isBusy = False
     self.__encryption = Encrypt()
     self.lock = threading.Lock()
     self.image = None
     self.text = None
    def updateFile(self, filepath, contents, organisation, password):
        # self function can be used when the user chooses to save their work
        # get the key for the provided organisation
        key = self.getOrganisationKey(organisation, password)
        enc = Encrypt(key)

        encrypted_file = open(filepath, 'wb')
        encrypted_contents = enc.encrypt_string(contents)
        encrypted_file.write(encrypted_contents)
        encrypted_file.close()
    def readFile(self, filepath, organisation, password):
        # get the key for the provided organisation
        key = self.getOrganisationKey(organisation, password)
        enc = Encrypt(key)

        encrypted_file = open(filepath, 'rb')
        encrypted_contents = encrypted_file.read()
        encrypted_file.close()

        decrypted_contents = enc.decrypt_string(encrypted_contents)
        return decrypted_contents
    def post(self):
        # Step 1 - retrieve and verify user input
        clue = self.request.get('clue').strip()
        mobileNumber = "+44" + self.request.get('mobilenumber').strip()

        # Step 2 - get the password record

        query = PasswordStore.query(
            ndb.AND(PasswordStore.clue == clue, PasswordStore.mobileNumber ==
                    mobileNumber)).order(-PasswordStore.created)
        passwordStorerecord = query.fetch(1)

        if passwordStorerecord:
            #logging.info('found: ' + clue + " - " + mobileNumber)

            passwordStorerecord = passwordStorerecord[0]
            passwordStoreId = passwordStorerecord.key.id(
            )  # the id of the record just created

            # Step 3 - store verification record
            verificationRecord = Verification()
            verificationRecord.action = 'delete'
            verificationRecord.confirmed = 0
            verificationRecord.passwordStoreId = passwordStoreId
            verificationRecord.put()

            verificationRecordId = verificationRecord.key.id(
            )  # the id of the record just created
            logging.info('storing verification id: ' +
                         str(verificationRecordId))

            # Step 4 - send SMS with encrypted verification

            encrypt = Encrypt()

            i = str(verificationRecordId)
            e = encrypt.encryptString(i)
            d = encrypt.decryptString(e)

            sms = SendSMS()
            sms.verifyDelete(mobileNumber, e)

            logging.info('sending delete verification: ' + " - " + i + " - " +
                         e + " - " + d)
        #else:
        #logging.info('not found: ' + clue + " - " + mobileNumber)

        # Step 5 - render reply
        template_values = {'nav': 'delete', 'id': e}

        template = JINJA_ENVIRONMENT.get_template(
            'templates/check_phone_success.html')
        self.response.write(template.render(template_values))
Example #16
0
    def __init__(self, IP, port, retryTimes=3, timeout=10):
        self.__IP = IP
        self.__port = port
        self.__add = (self.__IP, self.__port)
        self.__sock = None
        self.__isBusy = False
        self.__errLimit = retryTimes
        self.__timeout = timeout
        self.__encryption = Encrypt()

        self.image = None
        self.text = None
 def createOrganisation(self, organisation, password):
     keyPath = self.local_keys_path + '/' + organisation + '.key'
     enc = Encrypt()
     password = bytes(password, encoding='utf-8')
     # enc.privateKey needs to be saved
     pem = enc.privateKey.private_bytes(
         encoding=serialization.Encoding.PEM,
         format=serialization.PrivateFormat.PKCS8,
         encryption_algorithm=serialization.BestAvailableEncryption(
             password))
     with open(keyPath, 'wb') as f:
         f.write(pem)
Example #18
0
 def __init__(self):
     super(Window, self).__init__()
     self.layout = QBoxLayout(QBoxLayout.TopToBottom)
     self.setLayout(self.layout)
     self.setWindowTitle("GUI")
     self.setFixedSize(500, 500)
     Encrypt(self)
     Add(self)
     Delete(self)
     self.Dcheck.toggle()
     self.Acheck.toggle()
     self.Echeck.toggle()
Example #19
0
def test():
    a = 3
    b = 7
    c = InvertModulo(a, b)
    print(c)

    p = 1000000007
    q = 1000000009
    exponent = 23917
    modulo = p * q
    ciphertext = Encrypt("attack", modulo, exponent)
    message = Decrypt(ciphertext, p, q, exponent)
    print(message)
 def lm(self):
     # 先測試檔案是否存在
     if os.path.exists("./code.txt"):
         # 檔案存在就進行載入工作
         f = open('./code.txt', 'r')
         code = f.readline()
         self.e = Encrypt(code)
         s = str("".join(self.e.code))
         m = "密碼表: " + s
         self.app.dt["text"] = m
     else:
         m = "無法載入!"
         self.app.dt["text"] = m
    def post(self):
        # Step 1 - retrieve and verify user input
        clue = self.request.get('clue').strip()
        mobileNumber = "+44" + self.request.get('mobilenumber').strip()
        password = self.request.get('pass').strip()

        # Step 2 - store the password
        encrypt = Encrypt()
        e = encrypt.encryptString(password, mobileNumber)

        passwordStorerecord = PasswordStore()
        passwordStorerecord.clue = clue
        passwordStorerecord.mobileNumber = mobileNumber
        passwordStorerecord.encryptedPassword = e
        passwordStorerecord.confirmed = 0
        passwordStorerecord.put()

        passwordStoreId = passwordStorerecord.key.id(
        )  # the id of the record just created
        logging.info('storing password id: ' + str(passwordStoreId))

        # Step 3 - store verification record
        verificationRecord = Verification()
        verificationRecord.action = 'add'
        verificationRecord.confirmed = 0
        verificationRecord.passwordStoreId = passwordStoreId
        verificationRecord.put()

        verificationRecordId = verificationRecord.key.id(
        )  # the id of the record just created
        logging.info('storing verification id: ' + str(verificationRecordId))

        # Step 4 - send SMS with encrypted verification
        i = str(verificationRecordId)
        e = encrypt.encryptString(i)
        d = encrypt.decryptString(e)

        sms = SendSMS()
        sms.verifyPasswordAdd(mobileNumber, e)

        logging.info('sending verification: ' + " - " + i + " - " + e + " - " +
                     d)

        # Step 5 - render reply

        template_values = {'nav': 'store', 'id': e}

        template = JINJA_ENVIRONMENT.get_template(
            'templates/check_phone_success.html')
        self.response.write(template.render(template_values))
Example #22
0
def encrypt():
    form = EncryptForm(request.form)
    if request.method == "POST" and form.validate():
        text = form.text.data
        file_name = str(random.random())[2:]
        Encrypt(
            text,
            "static/encrypted/" + file_name,
            "png"
        )
        session['filename'] = file_name
        return render_template("encrypt.html", form=form)
    session['filename'] = ''
    return render_template("encrypt.html", form=form)
Example #23
0
    def __init__(self, IP, port):
        self.__IP = IP
        self.__port = port
        self.__add = (self.__IP, self.__port)
        self.__encryption = Encrypt()

        self.image = None
        self.text = None

        self.__s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.__s.bind((self.__IP, self.__port))
        self.__s.listen(2)
        self.__cli = None
        self.lock = threading.Lock()
Example #24
0
def pushEntry(web, user, passwd):
    """Encrypt data and send to database."""

    encryptObj = Encrypt()
    if web != '':
        web = encryptObj.encrypt(web)
        user = encryptObj.encrypt(user)
        passwd = encryptObj.encrypt(passwd)

        dbq.addEntry(web, user, passwd)

        return True
    else:
        return False
Example #25
0
def pushSignup(password, question, answer):
    """Hash and encrypt all data and send to database."""

    encryptObj = Encrypt()
    if passwordRules(password) and answer != '':
        password = hashIt(password)
        question = encryptObj.encrypt(question)
        answer = encryptObj.encrypt(answer)
        key = dbq.selectKey()[0]

        dbq.updateMasterInfo(password[0], password[1], question, answer)

        return True
    else:
        return False
    def get(self):

        template = 'error.html'
        template_values = {'nav': 'none'}

        if (self.request.get('id')):
            encrypt = Encrypt()
            verificationId = int(encrypt.decryptString(self.request.get('id')))

            verificationRecord = Verification.get_by_id(verificationId)
            logging.info(verificationRecord)

            if verificationRecord:
                passwordStorerecord = PasswordStore.get_by_id(
                    verificationRecord.passwordStoreId)

                if passwordStorerecord:
                    # Handle the add verification step
                    if verificationRecord.action == 'add':
                        passwordStorerecord.confirmed = 1
                        passwordStorerecord.put()
                        verificationRecord.key.delete()
                        logging.info(
                            'Updated records - verification (deleted) and passwordStore (updated)'
                        )
                        template = 'success.html'

                    # Handle the delete verification step
                    if verificationRecord.action == 'delete':
                        passwordStorerecord.key.delete()
                        verificationRecord.key.delete()
                        logging.info(
                            'Updated records - verification (deleted) and passwordStore (deleted)'
                        )
                        template = 'success.html'
                    else:
                        logging.info(
                            'Failed to retrieve Verification record id: ' +
                            str(verificationId))
                else:
                    logging.info(
                        'Failed to retrieve PasswordStore record id: ' +
                        str(verificationRecord.passwordStoreId))
            else:
                template = 'error.html'

        template = JINJA_ENVIRONMENT.get_template('templates/' + template)
        self.response.write(template.render(template_values))
Example #27
0
def getEntries():
    """Get rows of encrypted data and decrypted data for gui. The encrypted
    data is used in other functions for the gui buttons."""

    encryptObj = Encrypt()
    rows = dbq.selectEntries()

    decryptedRows = [[] for i in range(len(rows))]
    i = 0
    for row in rows:
        web = encryptObj.decrypt(row[0])
        user = encryptObj.decrypt(row[1])
        passwd = encryptObj.decrypt(row[2])
        decryptedRows[i].extend((web, user, passwd))
        i += 1

    return (decryptedRows, rows)
    def importFile(self, filepath, organisation, password, savepath=None):
        # first check if the organisation is is a new one
        if self.isNewOrganisation(organisation):
            self.createOrganisation(organisation, password)

        # read the file they provided, encrypt the contents and save it
        original_file = open(filepath, 'r')
        original_contents = original_file.read()
        original_file.close()

        # load the key for the organisation
        key = self.getOrganisationKey(organisation, password)
        enc = Encrypt(key)
        encrypted_contents = enc.encrypt_string(original_contents)
        savepath = savepath + '.enc' if savepath == None else savepath
        encrypted_file = open(savepath, 'wb')
        encrypted_file.write(encrypted_contents)
        encrypted_file.close()
Example #29
0
 def download_search(self, id):
     encrypt = Encrypt()
     text_dir = {
         "ids": "[" + id + "]",
         "level": "standard",
         "encodeType": "aac",
         "csrf_token": ""
     }
     id_url = 'https://music.163.com/weapi/song/enhance/player/url/v1?csrf_token='
     text = str(text_dir)
     data = encrypt.getParamsAndSecKey(text)
     try:
         response = requests.post(url=id_url,
                                  data=data,
                                  headers=self.headers)
         response.raise_for_status()
         response.encoding = 'utf-8'
         return response.json()
     except Exception as err:
         print(err)
         return '请求异常'
Example #30
0
    def run(self):
        global enc
        key = self.key_exchange()
        enc = Encrypt(key)
        self.client_socket.send(
            enc.encrypt(('Welcome to the Interview Portal')))
        time.sleep(0.1)
        _LOGIN_STATUS = self.validate()
        if _LOGIN_STATUS == True:
            print('User', self._USER_NAME, 'has a log in status of',
                  str(_LOGIN_STATUS))
            logger.info('User {} has a login status of {}'.format(
                self._USER_NAME, str(_LOGIN_STATUS)))
        else:
            logger.warning('Invalid login attempt with username {}'.format(
                self._USER_NAME))
            CredentialsException()
            self.terminate_session()
            return
        ##This assumes that the user is trying to take an interview. Additional##
        ##user options could be added easily by making the giveInterview call  ##
        ##conditional
        user_role = self.currentuser.getPer()
        self.client_socket.send(
            enc.encrypt(str('{}'.format(
                db_interaction.getUserRole(user_role)))))

        if (user_role == 4):
            self.giveInterview()
        elif (user_role == 1):
            self.adminMenu()
        elif (user_role == 2):
            self.adminMenu()
        elif (user_role == 3):
            self.reviewInterview()

        self.terminate_session()