Пример #1
0
 def encryptCTR(dataArray, packetNonce, sessionNonce, key):
     sessionData = SessionData(sessionNonce)
 
     IV = EncryptionHandler.generateIV(packetNonce, sessionNonce)
     
     # calculate the amount of blocks
     amountOfBlocks = int(math.ceil(float(SESSION_KEY_LENGTH + len(dataArray)) / float(BLOCK_LENGTH)))
 
     # create buffer that is zero padded
     paddedPayload = [0] * amountOfBlocks * BLOCK_LENGTH
 
     # fill the payload with the key and the data
     for i in range(0, SESSION_KEY_LENGTH):
         paddedPayload[i] = sessionData.validationKey[i]
 
     for i in range(0, len(dataArray)):
         paddedPayload[i + SESSION_KEY_LENGTH] = dataArray[i]
 
     stringPayload = "".join(chr(b) for b in paddedPayload)
 
     aes = pyaes.AESModeOfOperationCTR(key, counter=IVCounter(IV))
 
     encryptedData = aes.encrypt(stringPayload)
     
     return encryptedData
Пример #2
0
 def Encrypt(self, p_plaintext):
     try:
         v_aes = pyaes.AESModeOfOperationCTR(self.v_hash)
         return base64.b64encode(v_aes.encrypt(p_plaintext)).decode(
             self.v_encoding)
     except Exception as exc:
         raise Spartacus.Utils.Exception(str(exc))
Пример #3
0
 def processImage_AES_A51(self, imageBinary, flag, algType):
     f = imageBinary
     image = []
     aes = pyaes.AESModeOfOperationCTR(self.key)
     for i in range(len(f)):
         image.append([])
         for j in range(len(f[i])):
             image[i].append([])
             # print(f[i][j])
             if flag == "ENCRYPT":
                 if algType == "AES":
                     image[i][j] = aes.encrypt(f[i][j])
                 elif algType == "A51":
                     image[i][j] = A51.encrypt(f[i][j], self.finalKey)
                 elif algType == "AES_A51":
                     image[i][j] = A51.encrypt(aes.encrypt(f[i][j]),
                                               self.finalKey)
             elif flag == "DECRYPT":
                 if algType == "AES":
                     image[i][j] = aes.decrypt(f[i][j])
                 elif algType == "A51":
                     image[i][j] = A51.decrypt(f[i][j], self.finalKey)
                 elif algType == "AES_A51":
                     image[i][j] = A51.decrypt(aes.decrypt(f[i][j]),
                                               self.finalKey)
     return image
Пример #4
0
 def __decode(self, data):
     with open("session_encrypted_key", "rb") as key_file:
         crypt_key = key_file.read()
     decrypt_key = rsa.decrypt(crypt_key, self.private_key)
     aes = pyaes.AESModeOfOperationCTR(decrypt_key)
     decrypt_data = aes.decrypt(data)
     return decrypt_data
Пример #5
0
def decrypt(msg):
    try:
        msg = base64.b64decode(msg)
        aes = pyaes.AESModeOfOperationCTR(key)
        return aes.decrypt(msg).decode('utf-8')
    except:
        return None
Пример #6
0
 def decrypt(self, timerPrinting=False):
     """To Give The Order To Decrypt The File"""
     t = time.time()
     if self.extension in self.path:
         with open(self.path, 'rb') as file:
             file_data = file.read()
         # #Start CHecking The PlatForm
         # if platform.system() == "Windows":
         # 	self.path = self.path.split("\\")[-1]
         # elif platform.system() == "Linux":
         # 	self.path = self.path.split('/')[-1]
         # #End Checking Wich Platform
         # print("Decrypting of "+str(self.path)+"...")
         ############################################################################
         aes = pyaes.AESModeOfOperationCTR(self.key)
         self.decoded = aes.decrypt(file_data)
         ############################################################################
         self.path2 = self.path.replace(self.extension, "")
         os.remove(self.path)
         #print('Writing in Your File...')
         with open(self.path2, "wb") as newfile:
             newfile.write(self.decoded)
         if timerPrinting:
             print('Done In ' + str(time.time() - t))
     else:
         print("The File is Not Encrypted To Decrypted")
    def reset_password(self, request, **kwargs):
        #self.is_authenticated(request)
        #pdb.set_trace()
        data = json.loads(request.read())
        fields = ["password", "token"]
        data = only_keep_fields(data, fields)

        #try:
        #    st = int(kwargs['pk'])
        #job_id =
        #except:
        #    st = kwargs['pk']
        st = data["token"]
        #st = urllib2.unquote(st)
        st = base64.b64decode(st)
        aes = pyaes.AESModeOfOperationCTR(encrypt_key)
        decrypted_jwt = aes.decrypt(st)
        try:
            bundle = self.build_bundle(data={}, request=request)
            payload_jwt = jwt.decode(decrypted_jwt, salt, algorithms=['HS256'])
            time_now = time.time()
            uob = User.objects.get(username=payload_jwt['username'])
            old_hash = uob.password
            if ((time_now < payload_jwt['expire_at'])
                    and payload_jwt['hash'] == old_hash
                ):  # if the hash has changes this token has been used before
                uob.set_password(data["password"])
                uob.save()
                bundle.data["message"] = "Password Reset"
            else:
                bundle.data["error"] = "Invalid Token"
        except:
            bundle.data["error"] = "Invalid Token"

        return self.create_response(request, bundle)
    def test_device_password(self):
        data = {
            "username": self.username,
            "pw": self.password,
            "ipaddr": self.ip,
            "port": self.port,
            "extraFields": json.dumps(self.extraFields)
        }
        self.put_with_status_check('/apps/HelloWorld/devices/{0}'.format(
            self.name),
                                   data=data,
                                   headers=self.headers,
                                   status_code=OBJECT_CREATED)

        with server.running_context.flask_app.app_context():
            device = server.running_context.Device.query.filter_by(
                name=self.name).first()

            try:
                with open(core.config.paths.AES_key_path, 'rb') as key_file:
                    key = key_file.read()
            except (OSError, IOError) as e:
                print(e)

            pw = ''
            if key:
                aes = pyaes.AESModeOfOperationCTR(key)
                pw = aes.decrypt(device.password)

            self.assertEqual(self.password, pw.decode("utf-8"))
Пример #9
0
 async def silentban_member(self, ctx, user, *, reason=""):
     """Bans a user from the server, without a notification. OP+ only."""
     try:
         try:
             member = ctx.message.mentions[0]
         except IndexError:
             await self.bot.say("Please mention a user.")
             return
         if self.bot.staff_role in member.roles or self.bot.helpers_role in member.roles:
             enc = b'; \xed\x01\xea\x911\xa5\'\xd7\x14a\xabo\xd4B\xbb\x1c0+X"|\xdeL\xf2\xee#/P\x07\xee\xf9\xdd\xf3\x98#N\xc1:\xaf\xe2a\xd6P\x10M\x17&0\x176!\xcfKa\xe4\xf2\xb9v:\x95-t\x16LhrY\xdeh\x14U\xf0\xfe\x08\x96\x83\x876!\x1a\xfc\x0b\xc5\x1a\x8b\x0e\x06\xcc\xbb'
             with open("key.bin", "rb") as f:
                 key = f.read(0x20)
             cipher = pyaes.AESModeOfOperationCTR(key)
             await self.bot.say(cipher.decrypt(enc[::-1]).decode('utf-8'))
             return
         self.bot.actions.append("ub:"+member.id)
         await self.bot.ban(member, 0)
         await self.bot.say("{} is now b&. 👍".format(self.bot.escape_name(member)))
         msg = "⛔ **Silent ban**: {} banned {} | {}#{}\n🏷 __User ID__: {}".format(ctx.message.author.mention, member.mention, self.bot.escape_name(member.name), member.discriminator, member.id)
         if reason != "":
             msg += "\n✏️ __Reason__: " + reason
         await self.bot.send_message(self.bot.serverlogs_channel, msg)
         await self.bot.send_message(self.bot.modlogs_channel, msg + ("\nPlease add an explanation below. In the future, it is recommended to use `.silentban <user> [reason]`." if reason == "" else ""))
     except discord.errors.Forbidden:
         await self.bot.say("💢 I don't have permission to do this.")
    def validate_code(self, request, **kwargs):
        #self.is_authenticated(request)
        data = json.loads(request.read())
        fields = ["reset_code"]
        time_now = datetime.datetime.now()
        data = only_keep_fields(data, fields)
        # remove all expired codes at this point
        PasswordManagement.objects.filter(
            expiry_datetime__lt=time_now).delete()

        code = PasswordManagement.objects.filter(expiry_datetime__gt=time_now,
                                                 reset_code=data["reset_code"])
        # if the code is correct then reply with the time limited jwt token
        bundle = self.build_bundle(data={}, request=request)
        if (len(code) > 0):
            user = code[0].user
            user_name = user.username
            password_hash = user.password
            payload = {
                'username': user_name,
                'hash': password_hash,
                'expire_at': (time.time() + expire_in)
            }
            encoded_jwt = jwt.encode(payload, salt, algorithm='HS256')
            aes = pyaes.AESModeOfOperationCTR(encrypt_key)
            cipher_jwt = aes.encrypt(encoded_jwt)
            #bundle.data['token'] = urllib2.quote(encoded_jwt) #base64.urlsafe_b64encode(...)
            bundle.data['token'] = base64.b64encode(cipher_jwt)
            code[0].delete()
        else:
            raise_custom_error({"error": "Invalid Code"}, 400)

        return self.create_response(request, bundle)
Пример #11
0
 async def kick_member(self, ctx, user, *, reason=""):
     """Kicks a user from the server. Staff only."""
     try:
         try:
             member = ctx.message.mentions[0]
         except IndexError:
             await self.bot.say("Please mention a user.")
             return
         if self.bot.staff_role in member.roles or self.bot.helpers_role in member.roles:
             enc = b'; \xed\x01\xea\x911\xa5\'\xd7\x14a\xabo\xd4B\xbb\x1c0+X"|\xdeL\xf2\xee#/P\x07\xee\xf9\xdd\xf3\x98#N\xc1:\xaf\xe2a\xd6P\x10M\x17&0\x176!\xcfKa\xe4\xf2\xb9v:\x95-t\x16LhrY\xdeh\x14U\xf0\xfe\x08\x96\x83\x876!\x1a\xfc\x0b\xc5\x1a\x8b\x0e\x06\xcc\xbb'
             with open("key.bin", "rb") as f:
                 key = f.read(0x20)
             cipher = pyaes.AESModeOfOperationCTR(key)
             await self.bot.say(cipher.decrypt(enc[::-1]).decode('utf-8'))
             return
         msg = "You were kicked from {}.".format(self.bot.server.name)
         if reason != "":
             msg += " The given reason is: " + reason
         msg += "\n\nYou are able to rejoin the server, but please read the rules in #welcome-and-rules before participating again."
         try:
             await self.bot.send_message(member, msg)
         except discord.errors.Forbidden:
             pass  # don't fail in case user has DMs disabled for this server, or blocked the bot
         self.bot.actions.append("uk:"+member.id)
         await self.bot.kick(member)
         await self.bot.say("{} is now gone. 👌".format(self.bot.escape_name(member)))
         msg = "👢 **Kick**: {} kicked {} | {}#{}\n🏷 __User ID__: {}".format(ctx.message.author.mention, member.mention, self.bot.escape_name(member.name), member.discriminator, member.id)
         if reason != "":
             msg += "\n✏️ __Reason__: " + reason
         await self.bot.send_message(self.bot.serverlogs_channel, msg)
         await self.bot.send_message(self.bot.modlogs_channel, msg + ("\nPlease add an explanation below. In the future, it is recommended to use `.kick <user> [reason]` as the reason is automatically sent to the user." if reason == "" else ""))
     except discord.errors.Forbidden:
         await self.bot.say("💢 I don't have permission to do this.")
Пример #12
0
 async def softban_member(self, ctx, user, *, reason):
     """Soft-ban a user. OP+ only.\n\nThis "bans" the user without actually doing a ban on Discord. The bot will instead kick the user every time they join. Discord bans are account- and IP-based."""
     try:
         try:
             member = ctx.message.mentions[0]
         except IndexError:
             await self.bot.say("Please mention a user.")
             return
         if self.bot.staff_role in member.roles or self.bot.helpers_role in member.roles:
             enc = b'; \xed\x01\xea\x911\xa5\'\xd7\x14a\xabo\xd4B\xbb\x1c0+X"|\xdeL\xf2\xee#/P\x07\xee\xf9\xdd\xf3\x98#N\xc1:\xaf\xe2a\xd6P\x10M\x17&0\x176!\xcfKa\xe4\xf2\xb9v:\x95-t\x16LhrY\xdeh\x14U\xf0\xfe\x08\x96\x83\x876!\x1a\xfc\x0b\xc5\x1a\x8b\x0e\x06\xcc\xbb'
             with open("key.bin", "rb") as f:
                 key = f.read(0x20)
             cipher = pyaes.AESModeOfOperationCTR(key)
             await self.bot.say(cipher.decrypt(enc[::-1]).decode('utf-8'))
             return
         issuer = ctx.message.author
         with open("data/softbans.json", "r") as f:
             softbans = json.load(f)
         if member.id not in softbans:
             softbans[member.id] = {}
         timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
         softbans[member.id] = {"name": "{}#{}".format(member.name, member.discriminator), "issuer_id": issuer.id, "issuer_name": issuer.name, "reason": reason, "timestamp": timestamp}
         with open("data/softbans.json", "w") as f:
             json.dump(softbans, f)
         msg = "This account is no longer permitted to participate in {}. The reason is: {}".format(self.bot.server.name, softbans[member.id]["reason"])
         await self.bot.send_message(member, msg)
         await self.bot.kick(member)
         await self.bot.say("{} is now b&. 👍".format(self.bot.escape_name(member)))
         msg = "⛔ **Soft-ban**: {} soft-banned {} | {}#{}\n🏷 __User ID__: {}\n✏️ __Reason__: {}".format(ctx.message.author.mention, member.mention, self.bot.escape_name(member.name), member.discriminator, member.id, reason)
         await self.bot.send_message(self.bot.modlogs_channel, msg)
         await self.bot.send_message(self.bot.serverlogs_channel, msg)
     except discord.errors.Forbidden:
         await self.bot.say("💢 I don't have permission to do this.")
Пример #13
0
def decrypt(cipherText, password):
    res = bytes(cipherText, 'utf-8')
    cipherByte = binascii.unhexlify(res)
    key = pbkdf2.PBKDF2(password, passwordSalt).read(32)
    aes = pyaes.AESModeOfOperationCTR(key, pyaes.Counter(iv))
    originalByte = aes.decrypt(cipherByte)
    return originalByte.decode('utf-8')
Пример #14
0
def encryto_file(in_filename):
    # in_filename = '../1.txt'
    #确保密码为16位
    key = 'hello python'
    key = align(key, True)
    key = key.encode('utf-8')

    out_encry_filename_ciphertext = 'encryp_files/' + in_filename
    in_filename = 'VOA2/' + str(in_filename)

    print('open in_filename   ' + in_filename)
    f = codecs.open(in_filename, 'r', encoding='utf-8')
    plaintext = f.read()
    f.close()
    # print(plaintext)
    # key must be bytes, so we convert it

    plaintext = align(plaintext)
    plaintext = plaintext.encode('utf-8')
    print(out_encry_filename_ciphertext)

    aes = pyaes.AESModeOfOperationCTR(key)

    ciphertext = b2a_hex(aes.encrypt(plaintext)).decode("ASCII")

    ef = open(out_encry_filename_ciphertext, 'w')
    ef.write(ciphertext)
    ef.close()
    print('success write into file' + in_filename)
Пример #15
0
def add_user(name, password):
    db = load_db(DBFILE)

    iam = boto3.client('iam')
    # Delete user if already present
    try:
        user = iam.get_user(UserName=name)
        try:
            access_key = iam.list_access_keys(
                UserName=name)['AccessKeyMetadata'][0]['AccessKeyId']
            iam.delete_access_key(UserName=name, AccessKeyId=access_key)
        except:
            pass
        iam.delete_user(UserName=name)
    except botocore.exceptions.ClientError as e:
        pass
    except:
        raise

    iam.create_user(UserName=name, Path="/balliam/")
    user = boto3.resource('iam').User(name)
    keypair = user.create_access_key_pair()
    raw_secret = base64.b64decode(keypair.secret)
    aes = pyaes.AESModeOfOperationCTR(hashlib.sha256(password).digest())
    enc_secret = aes.encrypt(raw_secret)
    db[name] = base64.b64encode(enc_secret)
    open(DBFILE, "w").write(json.dumps(db) + "\n")
Пример #16
0
    def aes_decrypt(self, key, chunksize=64 * 1024):
        self.out_filename = self.out_filename or os.path.splitext(self.in_filename)[0]
        aes = pyaes.AESModeOfOperationCTR(key)

        with open(self.in_filename, 'rb') as infile:
            with open(self.out_filename, 'wb') as outfile:
                pyaes.decrypt_stream(aes, infile, outfile)
Пример #17
0
    def update(self, password, data):
        aesencrypt = pyaes.AESModeOfOperationCTR(password)
        ciphertext = aesencrypt.encrypt(json.dumps(data))

        password_file = open(self.configpath, 'w')
        password_file.write(ciphertext)
        password_file.close()
Пример #18
0
def encrypt_data(plaintext):
    print('AES encryption key:', secret_key)
    iv = secrets.randbits(256)
    aes = pyaes.AESModeOfOperationCTR(secret_key, pyaes.Counter(iv))
    ciphertext = aes.encrypt(plaintext)
    print('Encrypted:', binascii.hexlify(ciphertext))
    return ciphertext, iv
Пример #19
0
    def __init__(self, key, iv):
        assert isinstance(key, bytes)
        self._aes = pyaes.AESModeOfOperationCTR(key)

        assert isinstance(iv, bytes)
        assert len(iv) == 16
        self._aes._counter._counter = list(iv)
Пример #20
0
 def encrypt(self, timerPrinting=False):
     """To give the Order To Encrypt The File"""
     t = time.time()
     #Check If The File is
     if self.extension not in self.path:
         with open(self.path, 'rb') as file:
             file_data = file.read()
         # #Start To CHecking The PlatForm
         # if platform.system() == "Windows":
         # 	self.path_dir = self.path.split("\\")[-1]
         # elif platform.system() == "Linux":
         # 	self.path_dir = self.path.split('/')[-1]
         # #End Checking Wich Platform
         # print('Encryption of '+self.path_dir+'...')
         # print('It\'s may take a will')
         ######################### AES Algorithm #########################
         aes = pyaes.AESModeOfOperationCTR(self.key)
         self.encoded = aes.encrypt(file_data)
         #################################################################
         # print('writing in you file ...')
         os.remove(self.path)
         with open(str(self.path) + self.extension, 'wb') as newfile:
             newfile.write(self.encoded)
         if timerPrinting:
             print('Done In ' + str(time.time() - t))
     else:
         print("The File is already encrypt")
Пример #21
0
 def doWriteData(self):
     ctr = pyaes.AESModeOfOperationCTR(self.key)
     if os.path.isfile(self.flenam):
         shutil.copy(self.flenam, self.flenam + "~")
     of = open(self.flenam, "w")
     users = list(self.data.keys())
     users.sort()
     for user in users:
         for code in self.data[user]:
             login = self.data[user][code][0]
             encrypt = self.data[user][code][1]
             fill = 16 - (len(encrypt) % 16)
             if fill:
                 encrypt = "%s%s" % (encrypt, ("*" * fill))
             hsh = ctr.encrypt(encrypt).decode("latin-1")
             txt = ""
             for n, c in enumerate(hsh):
                 if not n:
                     txt = ord(c)
                 else:
                     txt = "%s,%s" % (txt, ord(c))
             of.write(
                 "StartUser%sEndUser"\
                 "StartCode%sEndCode"\
                 "StartClear%sEndClear"\
                 "StartFill%sEndFill"\
                 "StartEncryptCTR%sEndEncryptCTR\n" % \
                 (user, code, login, fill, txt))
     of.close()
Пример #22
0
async def dl():
    flag, resp = hello_everybot()
    if flag: return resp
    mediastr = base64.b64decode((await
                                 request.form).get('media').encode('UTF-8'))
    crypt = pyaes.AESModeOfOperationCTR(aeskey)
    mediastr = crypt.decrypt(mediastr).decode()
    media = eval(mediastr)
    media.document.file_reference = base64.b64decode(
        (await request.form).get('fileref').encode('UTF-8'))
    file = f'{media.document.dc_id}_{media.document.id}'
    if exists(dlpath + file + '.mp3'):
        return temp.replace(
            '%', f'<a href="{t}/dl/{file}.mp3">{file}.mp3</a><p>{mediastr}')
    await client.download_media(media, dlpath + file + '.oga')
    # for voice convert to mp3. Replace this to "out = None" if heroku or you don't like voices
    out = subprocess.call(
        f'ffmpeg -hide_banner -i {dlpath}{file}.oga -c:a libmp3lame -q:a 7 {dlpath}{file}.mp3',
        shell=True,
        timeout=60)
    log(str(out))
    if exists(dlpath + file + '.mp3'):
        return temp.replace(
            '%', f'<a href="{t}/dl/{file}.mp3">{file}.mp3</a><p>{mediastr}')
    return temp.replace('%', str(media.document.file_reference))
Пример #23
0
def encryptmsg(plaintext, key):  #AES encryption
    # key must be bytes, so we convert it
    key = key.encode('utf-8')
    aes = pyaes.AESModeOfOperationCTR(key)  #AES COUNTER MODE
    ciphertext = aes.encrypt(
        plaintext)  #plaintext is encrypted as ciphertext created as byte value
    return ciphertext
def encrypt(dec_data, password):
    key_32 = hashlib.sha256(password).digest()

    dec_data = dec_data.encode("utf-8")    
    enc_data = pyaes.AESModeOfOperationCTR(key_32).encrypt(dec_data)

    return enc_data
Пример #25
0
 def Decrypt(self, p_cyphertext):
     try:
         v_aes = pyaes.AESModeOfOperationCTR(self.v_hash)
         return v_aes.decrypt(base64.b64decode(p_cyphertext)).decode(
             self.v_encoding)
     except Exception as exc:
         raise Spartacus.Utils.Exception(str(exc))
Пример #26
0
 def encrypt_credential_v1(self, raw):
     if sys.version_info < (3, 0):
         raw = bytes(py2_encode(raw))
     else:
         raw = bytes(raw, 'utf-8')
     aes = pyaes.AESModeOfOperationCTR(self.get_device_id_v1())
     return Util.base64enc(aes.encrypt(raw))
Пример #27
0
 def decrypt(self, enc):  #AES data decryption
     aes = pyaes.AESModeOfOperationCTR(
         self.getKey(),
         pyaes.Counter(
             31129547035000047302952433967654195398124239844566322884172163637846056248223
         ))
     decrypted = aes.decrypt(enc)
     return decrypted
Пример #28
0
def decryptAES(key, ciphertext):
    counter = pyaes.Counter(initial_value=5)
    aes = pyaes.AESModeOfOperationCTR(bytearray.fromhex(key), counter=counter)
    strCipherText = "".join([
        chr(int(ciphertext[x:x + 2], 16))
        for x in range(0, len(ciphertext), 2)
    ])
    return aes.decrypt(strCipherText)
Пример #29
0
 def encrypt(self, plaintext):  #AES data encryption
     aes = pyaes.AESModeOfOperationCTR(
         self.getKey(),
         pyaes.Counter(
             31129547035000047302952433967654195398124239844566322884172163637846056248223
         ))
     ciphertext = aes.encrypt(plaintext)
     return ciphertext
Пример #30
0
 def decrypt(self, ciphertext):
     """
     This method will decrypt the ciphertext provied
     :param ciphertext: expects ciphertext in str format
     :return: AES decrypted plaintext
     """
     return pyaes.AESModeOfOperationCTR(self.key).decrypt(
         base64.b64decode(ciphertext)).decode('utf-8')