示例#1
0
def manager():
    decrypt("Hotel.db")
    output = Manager.query.all()
    log.dbSelect(app.config['SQLALCHEMY_DATABASE_URI'],"Manager",Guest.query.count())
    db.session.close()
    encrypt("Hotel.db")
    return render_template('show(man).html',out=output, currentID = currentID)
示例#2
0
文件: aes128.py 项目: alexhutman/AES
def main():
    """
    message = [
        [
            ["3F", "EE", "C0", "E3"], ["93", "29", "87", "A8"],
            ["F7", "78", "65", "87"], ["D4", "AE", "0B", "EF"]
        ]
    ]
    key = [
        ["42", "69", "54", "21"], ["F5", "79", "C9", "FE"],
        ["8D", "65", "52", "41"], ["96", "9F", "75", "05"]
    ]
    """
    choice, message, key = prompt_user()

    # TODO: For decryption (whenever that time comes), bytes.fromhex(message).decode('utf-8') converts back to msg

    print("message: {}".format(message))
    tokenized_msg = tokenize(message, 2)
    print("tokenized message: {}".format(tokenized_msg))
    hexified_msg = hexify(tokenized_msg)
    print("hexified message: {}".format(hexified_msg))
    blockified_msg = blockify_and_matrix_msg(hexified_msg)
    print("blockified message: {}".format(blockified_msg))

    print(key)
    tokenized_key = tokenize(key, 2)
    hexified_key = hexify(tokenized_key)
    blockified_key = blockify_and_matrix_msg(hexified_key)[0]
    print(blockified_key)
    print("-------------------------")

    encrypt.encrypt(blockified_msg, blockified_key)
示例#3
0
def setAppointment(p):
    query = "INSERT INTO appointment VALUES (%s,%s,%s,%s,%s,%s,%s,%s, NULL);"
    cursor = cnx.cursor()
    token = generateAppointmentToken()
    cursor.execute(query, (generateId() ,encrypt(p.firstname), encrypt(p.lastname), encrypt(p.email), encrypt(p.begin_date), encrypt(p.end_date), p.business_id, token))
    cnx.commit()
    return token
示例#4
0
def start():
    while True:
        choise = int(
            input("Enter number: 1 for encode, 2 for decode, 3 for quit\n"))

        if choise == 1:
            # text = str(input("Enter text to encode"))
            text = "Lab 3 seti i telecommunikacii"  #29
            degree = int(
                input("Enter degree of encoding: 1 or 2 or 4 or 8: \n"))
            # text = open('text.txt', 'r')
            start = "start.bmp"
            new = "newImage.bmp"
            encrypt(text, degree, start, new, systemXernya=54, byte=8)

        elif choise == 2:
            degree = int(
                input("Enter degree of decoding: 1 or 2 or 4 or 8: \n"))
            toRead = int(input("How many symbols to read: \n"))
            new = "newImage.bmp"
            decrypt(degree, toRead, new, systemXernya=54, byte=8)

        elif choise == 3:
            break

        else:
            print("Unknown command!")
示例#5
0
def ckcode(e, r):
    c = encrypt(e + r)
    t = encrypt(e) + encode(encrypt(r))
    p = gen(t, c)
    u = encrypt(c)
    y = gen(p + gen(e, t) + u, t)
    return pricd(e, r, y)
示例#6
0
def load_user(id):
    print("FILE DECRYPTED_________________2")
    decrypt("Hotel.db")
    out =  int(id)
    db.session.close()
    encrypt("Hotel.db")
    return out
示例#7
0
def keybld():
    print(
        "\n\n\t -------  K E Y W O R D    P A S S W O R D   B U I L D E R ---- "
    )
    key = raw_input("\n\n Enter the KEYWORD : ")
    size = input(
        "\n\n Enter the No. of additional chars reqd (excluding key)  : ")
    chars = string.ascii_letters + string.digits + '$' + '_' + '%' + '&' + '*'
    loop = 5
    while loop == 5:
        print(chr(27) + "[2J")
        print("\n\n\t ---  A d B   P a s s w o r d   M a n a g e r  --- ")
        pwd = ''.join(random.choice(chars) for i in range(size))
        print("\n - - - - - - - - - - - - - - - - - - - - - - - - - - - ")
        passw = key + pwd
        print("\n\n G e n e r a t e d   P  a s s w o r d :  " + passw)
        print("\n - - - - - - - - - - - - - - - - - - - - - - - - - - - ")
        print("\n\n 1 - Generate new password ")
        print("\n 2 - Save this Password (with Encryption) ")
        print("\n\n\t 0 (or Any other key) - Continue... ")
        c = input("\n\t S e l e c t i o n :  ")
        if c == 1:
            loop = 5
        elif c == 2:
            fname = raw_input("\n\n Enter the Filename : ")
            encrypt(fname, passw)
            loop = 0
        else:
            loop = 0
示例#8
0
文件: aes.py 项目: chrisayoub/AES
def main():
    parser = argparse.ArgumentParser(description='Encrypt or decrypt with AES')
    parser.add_argument('--keysize',
                        help='Either 128 or 256 bits.',
                        required=True)
    parser.add_argument('--keyfile',
                        help='The path of a keyfile that fits the keysize.',
                        required=True)
    parser.add_argument('--inputfile',
                        help='The file to encrypt or decrypt.',
                        required=True)
    parser.add_argument('--outputfile',
                        help='The path for the desired output file.',
                        required=True)
    parser.add_argument('--mode', help='encrypt or decrypt', required=True)

    args = parser.parse_args()
    keysize = int(args.keysize)
    keyfile = args.keyfile
    inputfile = args.inputfile
    outputfile = args.outputfile
    mode = args.mode

    if mode == 'encrypt':
        e.encrypt(keysize, keyfile, inputfile, outputfile)
    elif mode == 'decrypt':
        d.decrypt(keysize, keyfile, inputfile, outputfile)
示例#9
0
def randbld():
    size=8
    chars=string.ascii_letters+string.digits
    loop=1
    while loop==1:
        print(chr(27)+"[2J")
        print("\n\n\t ---  A d B   P a s s w o r d   M a n a g e r  --- ")
        print("\n --  R a n d o m   P a s s    B u i l d e r --")
        print("\n -------------------------------------------------")
        pwd=''.join(random.choice(chars) for i in range(size))
        print("\n\n\t[[[ Generated Password : "******"          ]]]")
        print("\n\n ------------------------------------------------")
        print("\n\t 1 - Generate New Random Password ")
        print("\n\t 2 - Save this password (With Encryption)")
        print("\n\t 3 - copy to clipboard and save (With encryption)")
        print("\n\t\t 0 (or any other) - To Continue... ")
        sel=input("\n\n Enter your Selection : ")
        if sel==1:
            loop=1
        elif sel==2:
            fname=raw_input("\n\n Enter File Name : ")
            encrypt(fname,pwd)
            loop=0
        elif sel==3:
            copyclip(pwd)
            fname=raw_input("\n\n Enter File Name : ")
            encrypt(fname,pwd)
            loop=0
        else:
            loop=0
示例#10
0
def room():
    decrypt("Hotel.db")
    output = Room.query.all()
    log.dbSelect(app.config['SQLALCHEMY_DATABASE_URI'],"Room",Room.query.count())
    db.session.close()
    encrypt("Hotel.db")
    return render_template('show(room).html',out=output)
示例#11
0
def main():
    print("\n\n\t Select one of the Following ")
    print("\n\n\t 1 - A c c e s s   P a s s w o r d s ")
    print("\n\t 2 - C r e a t e      R a n d o m      P a s s w o r d ")
    print(
        "\n\t 3 - S a v e   P a s s w o r d (w i t h   E n c r y p t i o n) ")
    print("\n\n\t 9 - A d v a n c e   M o d e ")
    print("\n\n\t\t 0 -  E  X  I  T ")
    sel = input("\n Y o u r    S e l e c t i o n  : ")
    if sel == 1:
        access()
    elif sel == 2:
        randbld()
    elif sel == 3:
        print(chr(27) + "[2J")
        print("\n\n\t ---  A d B   P a s s w o r d   M a n a g e r  --- ")
        pwd = raw_input("\n\n Enter Password :  "******"\n\n Enter the file name : ")
        encrypt(fname, pwd)
    elif sel == 9:
        print(chr(27) + "[2J")
        print(
            "\n\n ------ A d B P a s s M g r      A d v a n c e   M o d e  -----"
        )
        create()
    elif sel == 0:
        print("\n\n Shutting down AdBPassMgr ... ")
        exit()
    else:
        print("\n Invalid Input")
示例#12
0
 def BrowseFile(self):
     global fname
     fname = QFileDialog.getOpenFileName(None, 'Open file', '')[0]
     from encrypt import encrypt
     key = open('crypto.key', 'rb').read()
     encrypt(fname, key)
     Browser.close()
示例#13
0
def ck(e, t, p, u, y, o):
    f = encrypt(e)
    g = encrypt(u + y)
    a = i = encrypt(e) + encode(encrypt(t)) + p
    b = gen_s(i, a)
    v = encrypt(f) + g
    j = gen_s(b + gen_s(e, a) + v, g)
    return prijm(e, t, p, u, y, o, j)
示例#14
0
 def login(self, mobile, password, accountType, userType):
     #传公参
     params = self.scm.public_argument()
     params['mobile'] = encrypt(mobile)
     params['password'] = encrypt(password)
     params['accountType'] = accountType
     params['userType'] = userType
     return self.scm.request_post(params, api.login)
示例#15
0
def updateBusinessOwner(p):
    query = "UPDATE `business_owner` SET `firstname`=%s,`lastname`=%s,`date_of_birth`=%s,`email`=%s,`phone`=%s WHERE id = %s"
    cursor = cnx.cursor()
    cursor.execute(
        query,
        (encrypt(p.firstname), encrypt(p.lastname), encrypt(
            p.date_of_birth), encrypt(p.email), encrypt(p.phone), p.id))
    cnx.commit()
示例#16
0
def op2():
    key = enc.getKey()
    if key == b'':
        print("The key is " + str(enc.createNewKey()))
        enc.encrypt()
        print("Done.")
    else:
        print("Files are already encrypted. Wouldn't want to overdo it :3")
示例#17
0
def setBusinessOwner(p):
    query = "INSERT INTO business_owner (id,firstname,lastname,date_of_birth,email,phone) VALUES (%s,%s,%s,%s,%s,%s);"
    cursor = cnx.cursor()
    id = generateId()
    cursor.execute(
        query, (id, encrypt(p.firstname), encrypt(p.lastname),
                encrypt(p.date_of_birth), encrypt(p.email), encrypt(p.phone)))
    cnx.commit()
    return id
示例#18
0
 def certification(self, acctName, idCode):
     #传公参
     params = self.scm.public_argument()
     result = self.sc.login(cfg.mobile, cfg.password, cfg.accountType,
                            cfg.userType)
     params['token'] = result['data']['token']
     params['acctName'] = encrypt(acctName)
     params['idCode'] = encrypt(idCode)
     return self.scm.request_post(params, api.certification)
示例#19
0
 def Contact_save(self, sessionToken, contacts, mailList):
     #传公参
     params = self.public_argument()
     params['sessionToken'] = sessionToken
     params['contacts'] = encrypt(contacts)
     params['mailList'] = encrypt(mailList)
     #验签
     headers = self.Inspection_sign(params)
     return self.request_post(params, headers, 'data/contact/save.json')
示例#20
0
def main():
    msg = ""
    try:
        client = None
        addr = ""

        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.bind(('', 17389))

        t.start()
        t2.start()

        #print("connecting".upper())
        t.join()
        t2.join()

        if wrong == True:
            return

        if len(sys.argv) == 0:
            #            file_name = input("file name:\n>\t")
            file_name = filedialog.askopenfilename()
            arg = False

            with open(file_name, encoding="utf-8", errors='ignore') as f:
                msg = e.encrypt(longitude, latitude, f.read())

            option = input("(E)ncrypt or (D)ecrypt:\n>\t")

            if option.upper() == 'D':
                file_name = file_name[:file_name.index(
                    '.')] + '_decrypted' + file_name[file_name.index('.'):]

            with open(file_name, 'w') as f:
                f.write(msg)
        else:
            option = input("(E)ncrypt or (D)ecrypt:\n>\t")

            while len(sys.argv) > 0:
                file_name = sys.argv.pop(0)

                with open(file_name, encoding="utf-8", errors='ignore') as f:
                    for line in f:
                        msg += e.encrypt(longitude, latitude, line)

                if option.upper() == 'D':
                    file_name = file_name[:file_name.index(
                        '.')] + '_decrypted' + file_name[file_name.index('.'):]
                with open(file_name, 'w') as f:
                    f.write(msg)
    except Exception as err:
        try:
            os.system("clear")
        except:
            os.system("cls")
        traceback.print_exc()
        print("ERROR\nExiting now")
示例#21
0
 def Certification_Update(self, sessionToken, idCardNo, fullname):
     #传公参
     params = self.public_argument()
     params['sessionToken'] = sessionToken
     params['idCardNo'] = encrypt(idCardNo)
     params['fullname'] = encrypt(fullname)
     #验签
     headers = self.Inspection_sign(params)
     return self.request_post(params, headers,
                              'data/certification/update.json')
示例#22
0
def sendCommand():
    message2 = raw_input("Enter command: ")
    if (message2 == "exit"):
        sock.sendall(encrypt.encrypt(message2))
        sock.close()
        quit()

    print("Command received is: " + message2)
    encryptedMessage = encrypt.encrypt(message2)
    print("The encrypted version that will be sent is: " + encryptedMessage)
    sock.sendall(encryptedMessage)
示例#23
0
def op3():
    key = enc.getKey()
    if key == b'':
        print("The key is " + str(enc.createNewKey()))
        enc.encrypt()
    else:
        enc.decrypt()
        print("The key is " + str(enc.createNewKey()))
        enc.encrypt()

    print("Done.")
def new():
    username = request.form['username']
    website = request.form['website']
    length = request.form['length']
    special = request.form['special']
    caps = request.form['caps']
    nums = request.form['nums']

    #print(username, website, length, special, caps, nums)
    encrypt.encrypt(username, website, length, special, caps, nums)
    return send_from_directory('ui', 'passkeep.html')
示例#25
0
def register():
    letterloop = 0
    logdigit = 0
    loglower = 0
    logupper = 0
    logsymbol = 0
    RegisterUser = RegisterUserForm(request.form) #make sure to clear and check fields are ok before inserting into sql database
    with open('./BannedPasswords/banned-passwords-1.txt', 'r') as BannedPassList:
        found = False
        if request.method == 'POST' and RegisterUser.validate():
            for line in BannedPassList:
                if str(RegisterUser.password.data) in line:
                    print("This password is not allowed")
                    return 'This password is not allowed'
            if not found:
                logpass = str(RegisterUser.password.data)
                while letterloop < len(logpass):
                    if logpass[letterloop].isdigit():
                        logdigit += 1
                    elif logpass[letterloop].islower():
                        loglower += 1
                    elif logpass[letterloop].isupper():
                        logupper += 1
                    else:
                        logsymbol += 1
                    letterloop += 1
                if logdigit >= 1 and loglower >= 1 and logupper >= 1 and logsymbol >= 1 and len(logpass) >= 8:
                    logpass = pbkdf2_sha256.hash(logpass)
                    user = Guest(g_name=RegisterUser.name.data, g_email=RegisterUser.email.data, g_password=logpass, g_credit_card=RegisterUser.cc.data, g_phone=RegisterUser.num.data)
                    decrypt("Hotel.db")
                    db.session.add(user)
                    log.dbInsert(app.config['SQLALCHEMY_DATABASE_URI'],"Guest",RegisterUser.email.data, RegisterUser.name.data, str(RegisterUser.cc.data)[-4:0], "1")
                    db.session.commit()
                    log.dbCommit(app.config['SQLALCHEMY_DATABASE_URI'],"Guest","1")
                    try:
                        log.reg_new(RegisterUser.username.data)
                    except Exception:
                        print("Error occurred while logging Registering new guest.")
                    print("Guest successfully registered")
                    session['logged_in'] = 1
                    session['user'] = RegisterUser.name.data
                    login_user(user)
                    db.session.close()
                    encrypt("Hotel.db")
                    try:
                        log.reg_new(RegisterUser.name.data)
                    except Exception:
                        print("Error occurred while logging Registering new user.")
                    return redirect(url_for('index'))
                else:
                    return 'Password must contain at least 1 digit, 1 symbol, 1 uppercase character and 1 lowercase character'

    return render_template('register.html', form=RegisterUser)
示例#26
0
def findUser(uName: str, uDate: str):
    sclCode = searchSchool('인천전자마이스터고등학교')['schulList'][0]['orgCode']
    param = {
        "orgCode": sclCode,
        "name": encrypt.encrypt(uName),
        "birthday": encrypt.encrypt(uDate),
        "stdntPNo": None,
        "loginType": "school"
    }

    user = requests.post(url='https://icehcs.eduro.go.kr/v2/findUser',
                         json=param)
    return user.json()
 def beginEncryption(self, listFilenames, private_key, public_key):
     key = k.Key(private_key, public_key)
     self.changeButtonState(tk.DISABLED)
     self.changeTextBoxState(tk.DISABLED)
     for i in listFilenames:
         self.showBar(i, listFilenames.index(i), len(listFilenames))
         if self.selection_value.get() == 1:
             e.encrypt(i, self.output_entry.get(), key)
         if self.selection_value.get() == 2:
             d.decrypt(i, self.output_entry.get(), key)
     self.progressText.set(self.encrypt_text.get()+"ion finished. ("+str(len(listFilenames))+"/"+str(len(listFilenames))+")")
     self.clearAllText()
     self.changeButtonState(tk.NORMAL)
示例#28
0
def run(usr):
    while (0 == 0):

        web_interface.get_file(usr)
        encrypt.decrypt(["mati2000", "koniec"])
        msg = input()
        encrypt.encrypt(msg, ["mati2000", "koniec"])
        web_interface.upload_file(usr % 1)

        print("would you like to send another file (y/n)")
        response = input()

        if (response == "n"):
            break
示例#29
0
 def Get_code(self, sessionToken,idCardNo,fullname,mobile,bankCardNo,bankName,bankCode,payday):
     #传公参
     params=self.public_argument()
     params['sessionToken']=sessionToken
     params['idCardNo']=encrypt(idCardNo)
     params['fullname']=encrypt(fullname)
     params['mobile']=encrypt(mobile)
     params['bankCardNo']=encrypt(bankCardNo)
     params['bankName']=bankName
     params['bankCode']=bankCode
     params['payday']=payday
     #验签
     headers=self.Inspection_sign(params)
     return self.request_post(params,headers,'data/bank/getCode.json')
示例#30
0
def difbld():
    alf = string.ascii_letters
    dig = string.digits
    spl = '$' + '_' + '%' + '&' + '*'
    nc = input("\n Number of Alphabets  : ")
    ns = input("\n Number of Special Ch : ")
    nd = input("\n Number of Digits     : ")
    print("\n\n Select the format ")
    print("\n 1 > alphabets - special_characters - digits ")
    print("\n 2 > alphabets -      digits        - special characters ")
    print("\n 3 > special c -     alphabets      - digits ")
    print("\n 4 > special c -      digits        - alphabets ")
    print("\n 5 > digits    - special characters - alphabets ")
    print("\n 6 > digits    -     alphabets      - special characters ")
    com = input("\n\n\t S E L E C T I O N : ")
    loop = 3
    while loop == 3:
        fal = ''.join(random.choice(alf) for i in range(nc))
        fdg = ''.join(random.choice(dig) for i in range(nd))
        fsp = ''.join(random.choice(spl) for i in range(ns))
        if com == 1:
            pwd = fal + fsp + fdg
        elif com == 2:
            pwd = fal + fdg + fsp
        elif com == 3:
            pwd = fsp + fal + fdg
        elif com == 4:
            pwd = fsp + fdg + fal
        elif com == 5:
            pwd = fdg + fsp + fal
        elif com == 6:
            pwd = fdg + fal + fsp
        else:
            print("\n\n Invalid Selection")
        print(chr(27) + "[2J")
        print("\n\n\t ---  A d B   P a s s w o r d   M a n a g e r  --- ")
        print("\n - - - - - - - - - - - - - - - - - - - - - - - - - - ")
        print("\n\n G e n e r a t e d     P a s s w o r d   : " + pwd)
        print("\n - - - - - - - - - - - - - - - - - - - - - - - - - - ")
        print("\n\n 1 - Generate New Password ")
        print("\n 2 - Save this Password (with Encryption ) ")
        print("\n\t 0 (or any other key) - Continue... ")
        sel = input("\n S E L E C T I O N : ")
        if sel == 1:
            loop = 3
        elif sel == 2:
            fname = raw_input("\n\n Enter File Name : ")
            encrypt(fname, pwd)
        else:
            loop = 0
示例#31
0
    def encrypt(self, plainTextFile):
        if len(self.key) != 0:
            rsaEncrypt(self.key);
            return encrypt(self.key, plainTextFile);

        else:
            return
示例#32
0
 def test_point_encryption(self):
     
     m = ec.point(1,2,priv.A, priv.B, priv.prime)
     cipher = encrypt.encrypt(m, priv.base_point, priv.pub_raised_point)
     m2 = decrypt.decrypt(cipher, priv.exponent)
     
     self.assertEqual(m, m2)
示例#33
0
    def btnOKClicked(self, event):

        if isinstance(self.project, conman.conman.ConMan):
            self.project.name = self.generalPanel.txtname.GetValue()
            self.project.description = self.generalPanel.txtdescription.GetValue()
            self.project.keywords = self.generalPanel.txtkeywords.GetValue()
            self.parent.pub.pubid = self.searchPanel.txtpubid.GetValue()

        elif isinstance(self.project, ims.contentpackage.ContentPackage):
            lang = appdata.projectLanguage
            self.project.metadata.lom.general.title[lang] = self.generalPanel.txtname.GetValue()
            self.project.metadata.lom.general.description[lang] = self.generalPanel.txtdescription.GetValue()
            self.project.metadata.lom.general.keyword[lang] = self.generalPanel.txtkeywords.GetValue()

        settings.ProjectSettings["FTPHost"] = self.ftpPanel.txtFTPSite.GetValue()
        settings.ProjectSettings["FTPDirectory"] = self.ftpPanel.txtDirectory.GetValue()
        settings.ProjectSettings["FTPUser"] = self.ftpPanel.txtUsername.GetValue()
        settings.ProjectSettings["FTPPassword"] = encrypt.encrypt(self.ftpPanel.txtPassword.GetValue())

        if self.ftpPanel.chkPassiveFTP.GetValue() == True:
            settings.ProjectSettings["FTPPassive"] = "Yes"
        else:
            settings.ProjectSettings["FTPPassive"] = "No"

        if self.ftpPanel.chkUploadOnSave.GetValue() == True:
            settings.ProjectSettings["UploadOnSave"] = "Yes"
        else:
            settings.ProjectSettings["UploadOnSave"] = "No"

        settings.ProjectSettings["CDSaveDir"] = self.publishPanel.txtCDDir.GetValue()
        settings.ProjectSettings["WebSaveDir"] = self.publishPanel.txtWebDir.GetValue()

        self.parent.isDirty = True
        self.EndModal(wx.ID_OK)
示例#34
0
def encryption(plain, key):
    inp = to_hex(pad(plain))
    key = to_hex(pad(key))[0]

    ct = []
    for block in inp:
        ct.append(encrypt(block, key))
    return ct
示例#35
0
def encrypt_data(user_password, salt, data):
    """
    Encrypt the data and store it in form of [IV,TAG,CIPHER].
    """
    key = pyscrypt.hash(password = user_password.encode(encoding='UTF-8'), salt = salt.encode(encoding='UTF-8'), N = 1024, r = 1, p = 1, dkLen = 32)
    iv = os.urandom(12)
    ret = encrypt.encrypt(key, iv, data)
    return b''.join([iv, ret["tag"], ret["cipher"]])
示例#36
0
def login(steamid, login_key):
    steamid = SteamID(steamid)
    session_key, crypted_key, _ = encrypt.make_session_key()
    ticket = encrypt.encrypt(login_key, session_key)
    key = call('ISteamUserAuth', 'AuthenticateUser', data={
        'steamid': steamid.id,
        'sessionkey': crypted_key,
        'encrypted_loginkey': ticket,
    })
    return key.json().get('authenticateuser', {}).get('token')
示例#37
0
 def __init__(self):
     config = ConfigParser.SafeConfigParser()
     config.read(os.path.normpath(sys.argv[3]))
     self.source = os.path.normpath(sys.argv[1])
     self.remote = os.path.normpath(sys.argv[2])
     self.oauth_folder = os.path.normpath(config.get('folder','oauth',1))
     #self.log_file = open(str(os.path.join(os.path.normpath(config.get('folder','log',1)),'EncryptedUploader.log')),'w')
     self._create_drive()
     self.mapping = dict()#names of directories to parent folder id
     self.encrypter = encrypt()
示例#38
0
def getObjectProperties(obj, projections):
	ret = {}
	if not projections:
		projections = obj._properties.keys()
	for p in projections:
		prop = str(getattr(obj, p[:-1] if p.endswith('~') else p, 'null'))
		if p.endswith('~'):
			p = p[:-1]
			prop = encrypt.encrypt(prop, SAGPASS)
		ret[p] = prop
	return ret
 def createUserGuest(self):
     if filter(lambda x: int(x[2])>=self.minSysId, self.dataUsers):
         return True
     else:
         # add user guest
         pwd = "guest"
         encryptObj = encrypt()
         pwdHash = encryptObj.getHashPasswd(pwd, "shadow_ssha256")
         if pwdHash is False:
             return False
         if not self.addUser("guest", pwdHash):
             return False
         return True
示例#40
0
 def OnClose(self, event):
     if not self.mythread == None and self.mythread.isAlive():
         self.ftpService.stop()
         self.stopupload = True
         self.closewindow = True
         self.txtTotalProgress.SetValue(_("Shutting down FTP connection, please wait."))
         while self.mythread.isAlive():
             pass
             
         settings.ProjectSettings["FTPHost"] = self.txtFTPSite.GetValue()
         settings.ProjectSettings["FTPUser"] = self.txtUsername.GetValue()
         settings.ProjectSettings["FTPPassword"] = encrypt.encrypt(self.txtPassword.GetValue())
         settings.ProjectSettings["FTPDirectory"] = self.txtDirectory.GetValue()
         settings.ProjectSettings["FTPPassive"] = int(self.chkPassive.GetValue())
         #self.parent.pub.settings.SaveAsXML()
     self.EndModal(wx.ID_OK)
示例#41
0
	def tx_packet(self,data):
		bytes=data.data
		if data.zip==True:
			bytes = zlib.compress(bytes)

		tx_size=len(bytes)
		if tx_size!=0:
			expand=((int(tx_size)/int(512))+1)*512-tx_size
			bytes+= "\0" * expand


		header=data.id+"\n"

		if data.file_name!="":
			header=header+"#file_name\n"+data.file_name+"\n"

		header=header+"#size\n"+str(tx_size)+"\n"

		if data.target!="":
			header=header+"#target\n"+data.target+"\n"

		header=header+"#stat\n"+str(data.stat)+"\n"

		if data.dir_name!="":
			header=header+"#dir_name\n"+data.dir_name+"\n"

		if data.exe_name!="":
			header=header+"#exe_name\n"+data.exe_name+"\n"

		if data.command!="":
			header=header+"#command\n"+data.command+"\n"

		if data.zip==True:
			header=header+"#zip\n"+"1"+"\n#uzipsize\n"+str(data.uzipsize)+"\n"

		header=header+"#end"

		buf=bytearray(512)

		for i in range(0,len(header)):
			buf[i]=ord(header[i])
		buf.extend(map(ord, bytes))
		#buf=buf+bytes
		print("I am sending",len(buf),data.id)
		buf=encrypt(buf)
		print("I am sending",len(buf),data.id)
		self.socket.sendall(buf)
示例#42
0
文件: local.py 项目: uees/lightsocks
 def handle_tcp(self, remote):
     sock = self.request
     sock_list = [sock, remote]
     try:
         while (1):
             read_list, _, _ = select(sock_list, [], [])
             if remote in read_list:
                 data = remote.recv(8192)
                 if (sock.send(decrypt(data)) <= 0):
                     break
             if sock in read_list:
                 data = sock.recv(8192)
                 if (remote.send(encrypt(data)) <= 0):
                     break
     finally:
         remote.close()
         sock.close()
示例#43
0
	def sync_dir(self,path,target):
		count=0
		banned=[]
		sums=""

		files=self.gen_dir_list(path)
		for fname in files:
			f = open(fname, 'rb')   
			bytes = f.read()
			size=len(bytes)
			f.close()

			m = hashlib.md5()
			m.update(bytes)
			bin=m.digest()
			key_hash=""
			for i in range(0,m.digest_size):
				key_hash=key_hash+format(ord(bin[i]), '02x')
			sums=sums+fname+"\n"+key_hash+"\n"


		sums=sums[0:len(sums)-1]
		#print("sending",sums0
		size=len(sums)

		tx_size=((int(size)/int(512))+1)*512


		data=bytearray(tx_size)
		for i in range(0,size):
			data[i]=sums[i]

		
		head="gpvdm_sync_packet_one\n#size\n"+str(size)+"\n#target\n"+target+"\n#src\n"+path+"\n#end"

		start_len=len(head)

		head_buf=bytearray(512)
		for i in range(0,len(head)):
			head_buf[i]=head[i]

		buf=head_buf+data

		buf=encrypt(buf)
		self.socket.sendall(buf)
 def addUsers(self,*users_passwd):
     """Added users and groups to current system"""
     if not self.checkPermFiles():
         return False
     getDataInFile = _shareData().getDataInFile
     self.dataUsers = getDataInFile(fileName=migrateUsers.filePasswd,
                                    lenData=7)
     self.dataGroups = getDataInFile(fileName=migrateGroups.fileGroups,
                                     lenData=4)
     self.dataShadow = getDataInFile(fileName=migrateShadow.fileShadow,
                                     lenData=9)
     getHash = encrypt().getHashPasswd
     for userName, pwd in zip(users_passwd[0::2],
                              users_passwd[1::2]):
         pwdHash = getHash(pwd,"shadow_ssha256")
         if not self.addUser(userName, pwdHash):
             return False
     self.saveNewFiles()
     return True
示例#45
0
    def send_block(self, client, block_type, name, number, content):
        """
        Send block to the logic thread.

        Args:
            client (str): The client ip address.
            block_type (str): The type of the block.
            name (str): The name of the file
            number (int): The number of the block.
            content (str): The content of the block.
        """
        log_params = (block_type, number, client)
        self.logger.debug('%s block number %s sent to %s' % log_params)

        encrypted = encrypt.encrypt(self.key, content)

        net_message = protocol.server.send_block(
            block_type=block_type,
            name=os.path.basename(self.file_path),
            number=number,
            content=encrypted
        )
        message = protocol.thread.send(message=net_message, client=client)
        self.logic_queue.put(message)
示例#46
0
文件: local.py 项目: uees/lightsocks
    def handle(self):
        try:
            logging.info("Connection from {}".format(self.client_address[0]))
            # Here we do not need to recv exact bytes,
            # since we do not require clients to use any auth method
            data = self.request.recv(256)
            if not data or ord(data[0]) != 5:
                raise socket.error("Not socks5")
            # Send initial SOCKS5 response
            self.request.sendall('\x05\x00')
            data = self.request.recv(4)
            ver, cmd, rsv, atyp = [ord(x) for x in data]
            if cmd != 1:
                raise socket.error("Bad cmd value: %d" % cmd)
            if atyp != 3:
                raise socket.error("Bad atyp value: %d" % atyp)
            addr_len = ord(self.request.recv(1))
            addr = self.request.recv(addr_len)
            addr_port = self.request.recv(2)

            # Reply to client to estanblish the socks v5 connection
            reply = "\x05\x00\x00\x01"
            reply += socket.inet_aton('0.0.0.0')
            reply += struct.pack("!H", 0)
            self.request.sendall(reply)

            remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            remote.connect((SERVER_IP, SERVER_PORT))
            logging.info("Connect to %s" % addr)
            # encrypt address before sending it
            addr = encrypt(addr)
            dest_address = "%s%s%s" % (chr(len(addr)), addr, addr_port)
            remote.sendall(dest_address)
            self.handle_tcp(remote)
        except socket.error, e:
            logging.warn(e)
示例#47
0
import utils
import encrypt
import decrypt

words = utils.word_set
letters = utils.letter_set

on_loop = 0

print "Welcome to the Navajo Code Talkers Encryption / Decryption tool."

while on_loop == 0:
        print "Enter 1 to Encrypt a message"
        print "Enter 2 to Decrypt a message"
        print "Enter 3 to Quit"
        while True:
                try:
                        choice = int(raw_input("Your choice:  "))
                        break
                except ValueError:
                        print "That's not a valid choice. Please try again."
        if choice == 1:
                print "Time to encrypt"
                encrypt.encrypt(words,letters)
        elif choice == 2:
                print "Time to decrypt"
                decrypt.decrypt(words,letters)
        elif choice == 3:
                print "Thank you, have a nice day."
                sys.exit()
示例#48
0
文件: driver.py 项目: seanbrecke/RSA
#imports functions
import encrypt
import key_generation

#This script asks the user for known information, and uses it to (generate a new modulus and/or then) encrypt entered text
user_encryption_key = "None"
user_encryption_input = str(raw_input("What is the text? \n")).lower()
print("\n To generate a new modulus, leave blank.")
generated_modulus = (raw_input("\n What is the Modulus? \n"))
if generated_modulus == "" or generated_modulus == " ":
  upperlimit = int(raw_input("\n Upper Limit for Modulus, Must be above 70,000 \n"))
  new_key = key_generation.new_mod(upperlimit)
  generated_modulus = new_key[0]
  print("\n [Modulus, Encryption Key, Decryption Key]  \n")
  print(new_key)
else:
  user_encryption_key = int(raw_input("\n What is the encryption key? \n"))
  
print("\n Encrypted Message \n")
print(encrypt.encrypt(user_encryption_input, int(generated_modulus), user_encryption_key))
示例#49
0
文件: run.py 项目: alyakhtar/Crypteda
from decrypt import rmpad, to_str, decrypt

plain = input("Enter Plain Text: ")
key = input("Enter Key: ")

# print("Plain Text: ", plain)
# print("Key: ", key)

print("\n-------------------- Encryption ----------------------\n")

inp = to_hex(pad(plain))
key = to_hex(pad(key))[0]

ct = []
for block in inp:
    ct.append(encrypt(block, key))

encrypted_text = ""
for block in ct:
    encrypted_text += to_str(block)

print("\n")
print("Encrypted Text: ", encrypted_text)
print("\n")

print("\n-------------------- Decryption ----------------------\n")

dt = []
for block in ct:
    dt.append(decrypt(block, key))
    print()
示例#50
0
文件: crypter.py 项目: iFDVCS/spy-cy
def run_encrypt():
    form = EncryptionForm(request.form)
    if request.method == 'POST' and form.validate():
        message_input = form.message.data
        key_input = form.key
        level_input = form.level
        DNA_sequence_input = form.DNA_sequence.data
        DNA_sequence_input = DNA_sequence_input.strip()
        return render_template('encrypt_result.html', title="Encrypt", form=form, result = en.encrypt(message_input, key_input, level_input, DNA_sequence_input))  
    else:
        return render_template('encrypt.html', title="Encrypt", form=form)
示例#51
0
    return the_page;

web =  GetWeb('http://check.ptlogin2.qq.com/check?uin=1213247447&appid=1003903&r=0.6331230279734363','')
print web
state = re.compile("'(.*?)'").findall(web)[0]
# print cj
password = '******'
uin = '1213247447'
verifycode = re.compile("'(.*?)'").findall(web)[1]
if state == '1':
    gif = GetWeb('http://captcha.qq.com/getimage?aid=1003903&r=0.45623475915069394&uin=' + uin, '')
    file = open(os.getcwd()+'\qqcode.bmp','w+b')
    file.write(gif)
    file.close()
    verifycode = raw_input("输入验证码呗:")
p = encrypt.encrypt(password, uin, verifycode)


loginURL = 'https://ssl.ptlogin2.qq.com/login?u='+uin+'&p='+p+'&verifycode='+verifycode+'&webqq_type=10&remember_uin=1&login2qq=1&aid=1003903&u1=http%3A%2F%2Fweb.qq.com%2Floginproxy.html%3Flogin2qq%3D1%26webqq_type%3D10&h=1&ptredirect=0&ptlang=2052&from_ui=1&pttype=1&dumy=&fp=loginerroralert&action=2-22-19371&mibao_css=m_webqq&t=1&g=1&js_type=0&js_ver=10017&login_sig=H1HNZ8CjZK5qNcZM1KOzjaHK6jFt5ZLoF*snOAhi9zi2k-NDzZt21r8vgsTwXVrg'

# print loginURL

login = GetWeb(loginURL,'')
print login
# print cj
for cookie in cj:
    print(cookie.name, cookie.value)
    if cookie.name == 'ptwebqq':
        ptwebqq = cookie.value

# print ptwebqq
示例#52
0
文件: main.py 项目: htadg/Encryptor
import encrypt
import decrypt
import datetime
import msvcrt

while True:
    encrypted = encrypt.encrypt(raw_input("\n\n\nEnter message to encrypt -- "))
    print "\nEncrypted Message -- \n"
    print encrypted
    print "\nDecrypted Message -- \n"
    msg = decrypt.decrypt(encrypted, str(datetime.datetime.now()))
    print msg
    print "\n\n\nPress Enter to try once again or any other key to quit......"
    if ord(msvcrt.getch()) != 13:
        exit(0)
示例#53
0
文件: PyQQ.py 项目: anchowee/PyQQ
    def login(self, qqnum, pwd):
        if type(qqnum) == type(0):
            qqnum = str(qqnum)
            
        web = self.GetWeb('http://check.ptlogin2.qq.com/check?uin=' + qqnum +'&appid=1003903&r=0.6331230279734363')
        #print web
        state = re.compile("'(.*?)'").findall(web)[0]
        # print cj
        self.uin = qqnum
        self.pwd = pwd
        self.verifycode = re.compile("'(.*?)'").findall(web)[1]
        if state == '1':
            gif = self.GetWeb('http://captcha.qq.com/getimage?aid=1003903&r=0.45623475915069394&uin=' + self.uin)
            file = open(os.getcwd()+'\qq' + qqnum +'code.bmp','w+b')
            file.write(gif)
            file.close()
            self.verifycode = raw_input('[' + qqnum + "] 输入验证码呗:")
        p = encrypt.encrypt(self.pwd, self.uin, self.verifycode)
        loginURL = 'https://ssl.ptlogin2.qq.com/login?u=' + self.uin + \
                    '&p=' + p + \
                    '&verifycode=' + self.verifycode + \
                    '&webqq_type=10&remember_uin=1&login2qq=1&aid=1003903&u1=http%3A%2F%2Fweb.qq.com%2Floginproxy.html%3F' + \
                    'login2qq%3D1%26webqq_type%3D10&h=1&ptredirect=0&ptlang=2052&from_ui=1&pttype=1&dumy=&fp=loginerroralert&action=2-22-19371&'+ \
                    'mibao_css=m_webqq&t=1&g=1&js_type=0&js_ver=10017&login_sig=H1HNZ8CjZK5qNcZM1KOzjaHK6jFt5ZLoF*snOAhi9zi2k-NDzZt21r8vgsTwXVrg'
        # print loginURL
        login = self.GetWeb(loginURL)        
        info = re.compile("'(.*?)'").findall(login)
#        print info
        print '用户:[' + info[5] + '(' + self.uin + ')]' + info[4]
        #成功是返回0
        if info[0] != '0':
            print random.choice(['不识字啊喂!','重新来过吧', '弱爆了,这也能看错?'])
            self.login(qqnum, pwd)
        # print cj
        for cookie in self.cj:
            if cookie.name == 'ptwebqq':
                self.ptwebqq = cookie.value
                break 
    
        # print ptwebqq
        self.clientid = '51167527'
        data = 'r=%7B%22status%22%3A%22online%22%2C%22ptwebqq%22%3A%22' + self.ptwebqq + \
               '%22%2C%22passwd_sig%22%3A%22%22%2C%22clientid%22%3A%2251167527%22%2C%22'\
               'psessionid%22%3Anull%7D&clientid=51167527&psessionid=null'
        
        #{"retcode":103,"errmsg":""} {"retcode":121,"t":"0"} {"retcode":100006,"errmsg":""}
        # 返回103、121,代表连接不成功,需要重新登录;
        # 返回102,代表连接正常,此时服务器暂无信息;
        # 返回0,代表服务器有信息传递过来:包括群信、群成员给你的发信,QQ好友给你的发信。
        login2 = self.GetWeb('http://d.web2.qq.com/channel/login2', 'post', data)
        # print login2
        dic = eval(login2)
        # print dic
        
        self.vfwebqq = dic['result']['vfwebqq']
        self.psessionid = dic['result']['psessionid']
        
        getUserFriend = 'http://s.web2.qq.com/api/get_user_friends2'
        hash = encrypt.get_hash(self.uin, self.ptwebqq)
        data = 'r=%7B%22h%22%3A%22hello%22%2C%22hash%22%3A%22' + hash + '%22%2C%22vfwebqq%22%3A%22'\
               + self.vfwebqq + '%22%7D'
        userfriend = self.GetWeb(getUserFriend,'post', data)
        # print userfriend
        
        #fri = json.loads(userfriend.decode(sys.stdin.encoding).encode('utf8'))
        #fri = json.loads(userfriend)
        self.friend = json.loads(userfriend)['result']['info']
        
        # 这个能得到真正的QQ号
        getUserFriend = 'http://web2-b.qq.com/api/get_user_friends'
        data = 'r=%7B%22h%22%3A%22hello%22%2C%22vfwebqq%22%3A%22'\
               + self.vfwebqq + '%22%7D'
        userfriend = self.GetWeb(getUserFriend,'post', data)
        # print userfriend
        qqfriend = json.loads(userfriend)['result']['info']
        
        for user in self.friend:
            for qquser in qqfriend:
                if user['flag'] == qquser['flag']:
                    user['qq'] = qquser['uin']
                    continue
        
        getGroup = 'http://s.web2.qq.com/api/get_group_name_list_mask2'
        data = 'r=%7B%22vfwebqq%22%3A%22' + self.vfwebqq + '%22%7D'
        usergroup = self.GetWeb(getGroup,'post', data)
#        print usergroup
        self.group = json.loads(usergroup)['result']['gnamelist']
#        print self.group
        
        getGroup = 'http://s.web2.qq.com/api/get_friend_uin2?' + \
                   'tuin=%d&verifysession=&type=4&code=&vfwebqq=' + self.vfwebqq + '&t=1375202994632'
        for gp in self.group:
            item = self.GetWeb(getGroup%gp['code'])
            gp[u'gpid'] = int(json.loads(item)['result']['account'])
示例#54
0
 def send(self, data):
     if self.key:
         data = encrypt(data, self.key)
     length = struct.pack('<I', len(data))
     self.socket.send(length + self.MAGIC + data)
示例#55
0
increment = 250

moves = []
for i in range(10000):
    moves.append(move.Movement(increment, increment))

iterations = range(0, 1000, increment)

encrypted_image = numpy.array([x[:] for x in [[0] * 1000] * 1000])
decrypted_image = numpy.array([x[:] for x in [[0] * 1000] * 1000])

for X in iterations:
    for Y in iterations:
        cube = rubiks.Cube(list(img[X:X + increment, Y:Y + increment]))
        encrypt.encrypt(cube, moves)
        encrypted_image[X:X + increment, Y:Y + increment] = cube.matrix
        encrypt.decrypt(cube, moves)
        decrypted_image[X:X + increment, Y:Y + increment] = cube.matrix

img = img.astype(numpy.uint16)
encrypted_image = encrypted_image.astype(numpy.uint16)
decrypted_image = decrypted_image.astype(numpy.uint16)

# Assert that the dimensions of original and decrypted are equal
assert img.__len__() == decrypted_image.__len__()
assert img.__len__() == decrypted_image[0].__len__()

# Assert that each pixel in original and decrypted are the same
dimensions = [img.__len__(), img[0].__len__()]
for i in range(dimensions[0]):
示例#56
0
 def test(self):
     self.assertEqual(encrypt("hi","abc"), 'haib')
示例#57
0
import encrypt
#import cProfile, pstats
import decrypt3
import sys

ciphertext = encrypt.encrypt(sys.argv[1])

#cProfile.run('wordlist = decrypt3.read_words()', 'rundata')
wordlist = decrypt3.read_words()
result = decrypt3.decrypt3(ciphertext,wordlist)

## check results
#if sys.argv[1] not in result:
	#print("BAD"*100)

#p = pstats.Stats('rundata')
#p.sort_stats('cumulative').print_stats(10)


#cProfile.run('decrypt3.decrypt3(a,wordlist)', 'rundata')
#p = pstats.Stats('rundata')
#p.sort_stats('cumulative').print_stats(10)
def load_db():
    global db
    print "Loading DB..."
    t1 = time.clock()
    itemdb = assets.get_file('db\\itemdb.xml')
    itemdb = StringIO(itemdb)
    entry = {'name': "", 'fname': "", 't1': "", 't2': "", 't3': ""}
    #sex = {'male': list(), 'female': list()}
    #item = {'human': deepcopy(sex), 'giant': deepcopy(sex), 'elf': deepcopy(sex)}
    item = {FRM_HUMAN_F: list(), FRM_HUMAN_M: list(), FRM_GIANT_F: list(), FRM_GIANT_M: list()}
    db['body'] = deepcopy(item)
    db['hand'] = deepcopy(item)
    db['foot'] = deepcopy(item)
    db['head'] = deepcopy(item)
    db['robe'] = deepcopy(item)
    body = '/equip/armor/'
    hand = '/equip/hand/'
    foot = '/equip/foot/'
    head = '/equip/head/'
    robe = '/equip/robe/'
    items = iterparse(itemdb)
    for i in items:
        if 'Category' in i[1].attrib:
            if i[1].attrib['Category'][:len(body)] == body: equip = 'body'
            elif i[1].attrib['Category'][:len(hand)] == hand: equip = 'hand'
            elif i[1].attrib['Category'][:len(foot)] == foot: equip = 'foot'
            elif i[1].attrib['Category'][:len(head)] == head: equip = 'head'
            elif i[1].attrib['Category'][:len(robe)] == robe: equip = 'robe'
            else: continue
            name = get_local_name(i[1].attrib['Text_Name1'])
            if name is None: name = i[1].attrib['Text_Name0']
            t = i[1].attrib['App_WearType']
            e = entry.copy()
            e['name'] = name.strip('@')
            if equip == 'body':
                if len(t) > 2: e['t3'] = encrypt(t[2])
                if len(t) > 1: e['t2'] = encrypt(t[1])
                if len(t) > 0: e['t1'] = encrypt(t[0])
            else:
                try:
                    e['t1'] = int(t)-1
                except ValueError:
                    e['t1'] = t[0]
            if 'File_FemaleMesh' in i[1].attrib:
                e['fname'] = encrypt(i[1].attrib['File_FemaleMesh'] + '.pmg')
                db[equip][FRM_HUMAN_F] += [e]
            if 'File_MaleMesh' in i[1].attrib:
                e['fname'] = encrypt(i[1].attrib['File_MaleMesh'] + '.pmg')
                db[equip][FRM_HUMAN_M] += [e]
            if 'File_FemaleGiantMesh' in i[1].attrib:
                e['fname'] = encrypt(i[1].attrib['File_FemaleGiantMesh'] + '.pmg')
                db[equip][FRM_GIANT_F] += [e]
            if 'File_GiantMesh' in i[1].attrib:
                e['fname'] = encrypt(i[1].attrib['File_GiantMesh'] + '.pmg')
                db[equip][FRM_GIANT_M] += [e]
    for frm in range(4):
        db['body'][frm] = sorted(db['body'][frm], key=lambda e: e['name'])
        db['hand'][frm] = sorted(db['hand'][frm], key=lambda e: e['name'])
        db['foot'][frm] = sorted(db['foot'][frm], key=lambda e: e['name'])
        db['head'][frm] = sorted(db['head'][frm], key=lambda e: e['name'])
        db['robe'][frm] = sorted(db['robe'][frm], key=lambda e: e['name'])
    t2 = time.clock()
    print "Loaded DB in", t2 - t1, "sec"
示例#59
0
print("\nWallet Private Key WIF %s" % wallet.get_private_key_wif())
str = wallet.get_bitcoin_address()
print("\nWallet Address %s" % wallet.get_bitcoin_address())

pubkeyhex = wallet.get_public_key_hex()
pubkey = wallet.get_public_key()

addrfrom = P2PKHBitcoinAddress.from_pubkey(pubkey)
addrfromhex = P2PKHBitcoinAddress.from_pubkey(pubkeyhex.decode("hex"))
print("\nAddress From %s" % addrfrom)
print("\nAddress From Hex %s" % addrfromhex)

message = "bitid://localhost:5000/callback?x=30f56bc022dde976&u=1"

print("\nClear: %s" % message)
encrypted = encrypt.encrypt(wallet.get_public_key(), message)
print("\nEncrypted: %s" % encrypted)

decrypted = encrypt.decrypt(wallet.get_private_key_wif(), encrypted)
print("\nDecrypted: %s" % decrypted)

signature = wallet.sign(message)

print("\nSignature: %s" % signature)
print("\nVerified: %s" % wallet.verify(message, signature))

test1_raw_hex = '3e52050b58e1765ca9abfce576aa0efc27eaa4dd11a4051affabd050e6b92324'
test1_private_key_wif = privateKeyToWif(test1_raw_hex)
test1_key = CBitcoinSecret(test1_private_key_wif)
test1_pub = test1_key.pub
示例#60
0
文件: bot.py 项目: PSJoshi/botnet-lab
    parseText = recvText.split(" ")

    try:
        if parseText[1] == "PRIVMSG":
            # Handle PRIVMSGs here
            privmsgText = recvText.split(" ", 3)
            messageSender = privmsgText[0].lstrip(":").split("!")[0]
            messageChannel = privmsgText[2]
            messageSent = privmsgText[3].lstrip(":")
            # print "messageSender:", messageSender, "messageChannel:", messageChannel, "messageSent:", messageSent
            if not messageSender.startswith( 'bot' ):
                if messageSent[0] == settings_commandprefix:
                    ircSession.ParseUserCommands(ircSession, messageSender, messageChannel, messageSent)
                else:
                    output = router.distribute(messageSent)
                    # encrypt output
                    try:
                        output = encrypt.encrypt(output)
                        output = unicode(output, "utf-8")
                        ircSession.send('PRIVMSG ' + messageChannel + ' :' + str(output) + '\r\n')
                    except:
                        ircSession.send('PRIVMSG ' + messageChannel + ' :' + "Failed to encrypt." + '\r\n')
        if parseText[0] == "PING":
            # Respond to PINGs
            pingSender = parseText[1].split(":")[1]
            ircSession.send("PONG :" + pingSender + "\r\n")
        # print "--> PONG :" + pingSender

    except IndexError:
        continue