Я изобрел метод шифрования данных. Я буду знать, если это безопасно - PullRequest
0 голосов
/ 27 марта 2020

Я не уверен на 100%, если это лучшее место, чтобы спросить это. Если да, не могли бы вы предложить мне лучший сайт.

Я написал программу на python 3 для шифрования данных. Но он использует совершенно новый метод шифрования данных, который я сделал. И я sh хочу знать, считает ли кто-либо из вас, что это достаточно безопасно для любого практического использования. или , если вы видите в нем fl aws.

Основа c Суть программы такова:

Программа преобразует каждый символ данных в их номера ASCII. Затем, чтобы зашифровать его, он «случайным образом» добавляет большое число к исходному номеру ASCII каждого символа.

Но это не случайно, потому что начальное число было установлено с помощью функции random.seed(). И начальное значение, которое устанавливает программа, определяется ключом.

И затем он перетасовывает каждый ди git.

Из-за отсутствия лучшего названия я назвал этот метод SABONK. Это ничего не значит.


import random


def ASCII(x): #converts string to ASCII and returns as a list.
    return [ord(c) for c in x]

def ASCII_char(x): #turns a list of ASCII numbers back into text and in a string
    try:
        result = ""
        for i in x:
            result = result + chr(i)
        return result
    except:
        return None

def modifier(key): #returns the "modifier" value used for encryption
    return len(key)*sum(key)

def pad(n, x): #adds 0 to front of number so the length is as required.

    if len(str(x)) >= n: return x
    return ("0"*(n-len(str(x))))+str(x)

class SABONK:
    def __init__(self, key, max=856076, min=100, length=7):
        self.keyString = key
        self.key = ASCII(key)
        self.m = modifier(self.key)

        self.length = 7
        self.maxLength = max
        self.minLength = min

    def setKey(self, newKey):
        pass

    def Encrypt(self, data, password=None): #the main encrypt function
        if data == "": return ""
        #setting up variables needed.
        key = password
        if password == None: key = self.key #If password is None, use the password saved in the class.

        return self.shuffle(self.combine(self.basicEncrypt(data, key)))

    def Decrypt(self, data, password=None, toText=True): #the main encrypt function
        if data == "": return ""
        #setting up variables needed.
        key = password
        if password == None: key = self.key #If password is None, use the password saved in the class.

        if toText: return ASCII_char(self.basicDecrypt(self.disjoin(self.unshuffle(data)), key)) #if toText is True, the function wil return decrypted text and translate it back to characters.
        return self.basicDecrypt(self.disjoin(self.unshuffle(data)), key)#If not, will return list of ASCII numbers


    def basicEncrypt(self, data, password=None): #does the 1/3 part of the encryption process.
        #setting up variables needed.
        key = password
        if password == None: key = self.key #If password is None, use the password saved in the class.

        m = self.m
        if password != self.key: m = modifier(key)
        current = 0 #current refers to the current item in the key list being applied to the encryption process.
        result = []
        data = ASCII(data)

        for x in data:
            random.seed(key[current]*m)#setting the seed
            result.append(pad(self.length, random.randint(self.minLength, self.maxLength)+x))#encrypted character to result

            if current >= (len(key)-1): current = 0 #changing the current item in the key list being applied to the encryption process.
            else: current +=1

            m += x*random.randint(0, 100000) #chaning the modifier

        return result


    def basicDecrypt(self, data, password=None): #does the 1/3 part of the decryption process.
        #setting up variables needed.
        key = password
        if password == None: key = self.key#If password is None, use the password saved in the class.

        m = self.m
        if password != self.key: m = modifier(key)
        current = 0 #current refers to the current item in the key list being applied to the encryption process.
        result = []

        for x in data:
            random.seed(key[current]*m)#setting the seed
            d = x-random.randint(self.minLength, self.maxLength)
            result.append(d)#encrypted character to result

            if current >= (len(key)-1): current = 0 #changing the current item in the key list being applied to the encryption process.
            else: current +=1

            m += d*random.randint(0, 100000) #chaning the modifier

        return result

    def combine(self, data):#combine the numbers from the encrypted data
        result = ""
        for x in data: #going through data list, converting it into string and joining it into single string to retrun
            result = result + str(x)
        return result

    def disjoin(self, data):#disjoin the list of data that was combined by the "combine" function
        l = self.length
        result = []

        while len(data) != 0: #going thorugh the data, converting it into intager and putting it in result list
            result.append(int(data[:l]))
            data = data[l:]
        return result

    def shuffle(self, data, password=None): #data should be a string
        #setting up variables needed.
        key = password
        if password == None: key = self.key#If password is None, use the password saved in the class.

        m = self.m
        if password != self.key: m = modifier(key)
        current = 0 #current refers to the current item in the key list being applied to the random.seed.
        result = []

        l = (len(data) - 1)

        #firist we split the data string into a list, so that every elemnt in the list is a single number
        for x in data:
            result.append(x)


        #And now we shuffle the list
        for x in range(6*len(data)):
            random.seed(key[current]*m)#setting the seed

            i1 = random.randint(0, l) #choosing the two indexes of the data list to swap
            i2 = i1
            while i2 == i1: i2 = random.randint(0, l) #this makes sure i2 is different from i1
            result[i1], result[i2] = result[i2], result[i1]

            current +=1
            if current >= (len(key)-1): current = 0 #changing the current item in the key list being applied to the encryption process.
            m += 1

        return "".join(result)

    def unshuffle(self, data, password=None): #data should be a string
        #setting up variables needed.
        key = password
        if password == None: key = self.key#If password is None, use the password saved in the class.
        m = self.m
        if password != self.key: m = modifier(key)
        current = 0 #current refers to the current item in the key list being applied to the random.seed.
        result = []
        actionsList = []
        l = (len(data) - 1)

        #firist we split the data string into a list, so that every elemnt in the list is a single number
        for x in data:
            result.append(x)

        #figure out list of swaps the shuffle dunctionn would have taken.
        for x in range(6*len(str(data))): 
            random.seed(key[current]*m)#setting the seed

            i1 = random.randint(0, l) #choosing the two indexes of the data list to swap
            i2 = i1
            while i2 == i1: i2 = random.randint(0, l) #this makes sure i2 is different from i1

            actionsList.append([i1,i2])
            current +=1
            if current >= (len(key)-1): current = 0 #changing the current item in the key list being applied to the encryption process.
            m += 1

        actionsList = list(reversed(actionsList))#Then reverse the list, so the swaps can be undone.


        #And now we unshuffle the list
        for x in range(6*len(str(data))):
            result[actionsList[x][0]], result[actionsList[x][1]] = result[actionsList[x][1]], result[actionsList[x][0]]

        return "".join(result)


if __name__ == "__main__":
    key = input("Please type out key: ")
    s = SABONK(key)
    text = input("Please type out text to encrypt: ")
    print("You have typed: " + text)
    e = s.Encrypt(text)
    print("Text Encrypted: "+ e)
    print("Text Decrypted: "+ str(s.Decrypt(e)))

1 Ответ

4 голосов
/ 27 марта 2020

Я sh, чтобы узнать, считает ли кто-либо из вас, что он достаточно безопасен для практического использования.

Одним словом, нет. Требуется много лет изучения математики и криптографии, чтобы дистанционно понять, как создаются современные шифры, и невероятно тонкие факты, которые математики обнаружили за годы исследований.

Стэнфордский онлайн Криптография I курс является хорошим введением в некоторые концепции, но вам понадобятся, по крайней мере, математические навыки университетского уровня. Cryptopals Crypto Challenges также может научить вас кое-чему о современной криптографии, но будьте осторожны, эти задачи становятся невероятно трудными.

Хотя создавать шифры для развлечения может быть весело, пожалуйста, не используйте свои шифры для защиты чего-либо, что действительно чувствительно, и не вводите в заблуждение безопасность вашего шифра другим.

Такие сайты, как r / codes , - это места, где вы можете размещать подобные "хобби-шифры". И книга «Кодовая книга» Саймона Сингха - это хорошее прочтение о различных исторических шифрах и о том, как они были взломаны.


Рассматривали ли вы такие вещи, как:

  • basicEncrypt генерирует числа длиной не более 6 цифр, а затем дополняет их до 7 цифр. Это может вызвать такие проблемы, как усиление смещения вашего алгоритма тасования в сторону перетасовки цифр заполнения.

  • Длина data влияет на вероятность того, что данный di git будет заменен или нет .

  • Если вы дважды используете один и тот же ключ для данных одинакового размера, он сгенерирует одну и ту же комбинацию тасования.

  • Вы сильно полагаетесь на random.seed(), вы знаете, что он на самом деле делает под капотом? Безопасно ли использовать в безопасных целях?

...