Problems when encrypting text with matrices

Asked

Viewed 123 times

0

Here comes the code:

import numpy as np

def invert(matrix):
    try:
        new = list(np.linalg.inv(matrix))
    except np.linalg.LinAlgError:
        return "Matrix not inversible!"

    for i in range(len(new)):
        new[i] = list(new[i])
    return new

def mxmult(x, y):
    ls=[]
    for i in range(len(x)): #generate null matrix
        ls.append([])
        for j in range(len(y[0])):
            ls[i].append(0)

    for i in range(len(x)):
        for j in range(len(y[0])):
            for k in range(len(y)):
                ls[i][j] += x[i][k] * y[k][j]
    return ls

def encrypt(text, matrix):
    text_matrix = [[ord(letter) for letter in text][i:i+len(matrix[0])] for i in range(0, len(text), len(matrix))] #error?
    print(text_matrix)
    return mxmult(matrix, text_matrix)

def decrypt(text_matrix, inverse_matrix):
    decoded = mxmult(inverse_matrix, text_matrix)
    print(decoded)
    original_text = []
    for row in decoded:
        for column in row:
            print(column)
            original_text.append(chr(int(column)))
    return ''.join(original_text)

When I run the following tests

print(invert([[2, 3], [4, 5]]))
print(invert([[2, 3], [4, 6]]))
print(invert([[1,2,3], [4,5,6], [7,8,9]]))

print(mxmult([[1,2,3], [4,5,6]], [[7,8,9], [10,11,12]]))
print(mxmult([[7,8,9], [10,11,12]], [[1,2,3], [4,5,6]]))
x = encrypt('ola como ', [[1,2,3], [4,5,6], [7,8,9]])
print(x)
print(decrypt(x, invert([[1,2,3], [4,5,6], [7,8,9]])))

get that:

[[-2.5, 1.5], [2.0, -1.0]]
Matrix not inversible!
[[-4503599627370498.0, 9007199254740992.0, -4503599627370494.5], [9007199254740996.0, -1.8014398509481984e+16, 9007199254740990.0], [-4503599627370498.0, 9007199254740992.0, -4503599627370495.5]]
[[27, 30, 33], [78, 87, 96]]
[[39, 54, 69], [54, 75, 96]]
[[111, 108, 97], [32, 99, 111], [109, 111, 32]]
[[502, 639, 415], [1258, 1593, 1135], [2014, 2547, 1855]]
[[2048.0, 4096.0, 2048.0], [-2048.0, -4096.0, -2048.0], [0.0, 2048.0, 0.0]]
2048.0
4096.0
2048.0
-2048.0
Traceback (most recent call last):
  File "C:\...", line 54, in <module>
    print(decrypt(x, invert([[1,2,3], [4,5,6], [7,8,9]])))
  File "C:\...", line 42, in decrypt
    original_text.append(chr(int(column)))
ValueError: chr() arg not in range(0x110000)

Because when I invert a 2x2 matrix it works, but a 3x3 generates absurd results?

Because when I decrypt it generates strange numbers (negative, repeated)?

How do I make when executing Encrypt() the number of rows of text_matrix is equal to the number of columns of the parameter Matrix and so I can multiply them?

1 answer

0

import numpy

print('inversao de matrizes')
print(numpy.linalg.inv([[2,3], [4,5]]))
print(numpy.linalg.inv([[1,2,-3], [4,5,6], [7,0,9]]))
print(numpy.linalg.inv([[1,2,3],[4,5,6],[7,8,9]])) # Este caso da ruim
                                                   # por coincidencia.

print('---')
print('multiplicacao')
print(numpy.matmul(
    [[1,2,-3], [4,5,6]],
    [[1,0], [0,1], [1, -1]]))
print(numpy.matmul(
    [[1, 2], [3,4]],
    [[1, 0], [-1, 1]]))

def pegachave(senha, ordem):
    altura = ordem
    largura = ordem
    chave = numpy.zeros((altura,largura))
    for i in range(0, altura):
        for j in range(0, largura):
            if j < i:
                chave[i][j] = (-1) ** (i+j) # alterna o sinal na linha i,
                                            # coluna j
            else:
                chave[i][j] = ord(senha[j % len(senha)]) # pega o codigo
                                                         # ASCII
                                                         # da senha
                                                         # na posicao j;
                # Se o comprimento da senha for menor do que a largura da
                # matriz, volta para o inicio da senha e recomeca.
    return chave

def criptografa(senha, matriz):
    altura, largura = numpy.shape(numpy.matrix(matriz))
    if altura == largura:
        ordem = altura # ou largura
        chave = pegachave(senha, ordem)

        # multiplica a matriz pela chave
        return numpy.matmul(
            numpy.array(matriz),
            chave)
    else:
        raise ValueError

def descriptografa(senha, matriz):
    altura, largura = numpy.shape(numpy.matrix(matriz))
    if altura == largura:
        ordem = altura # ou largura
        chave = pegachave(senha, ordem)

        # multiplica a matriz pelo inverso da chave
        return numpy.matmul(
            numpy.array(matriz),
            numpy.linalg.inv(numpy.array(chave)))
    else:
        raise ValueError

print('---')
print('criptografia')
original = numpy.matrix([[1,2,3],[4,5,6],[7,8,9]])
print(original)
criptografado = criptografa('ola como ', original)
print(criptografado)
print(descriptografa('ola como ', criptografado))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.