【python】 中英文混合块加密算法&&文本文件的块加密

文章目录

一、中英文混合块加密算法

一、安装 numpy 包

方法如下:https://blog.csdn.net/weixin_45759918/article/details/124532318

二、需求

在英文块加密的基础上,完成中英文混合的块加密算法,中文字符从0x4e00开始,矩阵大小为145*145。

分析:这次的密码本需要多种形式组成,所以可以把字符先转为Unicode码的十进制形式再放入不同数组中。
密码本组成 = 中文Unicode字符 + 英文和标点Unicode字符 + 中文标点Unicode字符
145*145 = 20908 + 95 + 22
因为中文的标点符号在Unicode并不连续所以要单独列出来
其他的算法和加密英文没有区别,改改数就行。
注意:输入的字符有时有两个一样的内容(a=[‘人’,’人’]),加密解密时设置跳过相同字符,要不然加密解密都出错。

中文标点符号的列表

chinesePunctuationList = [183, 215, 8212, 8216, 8217, 8220, 8221, 8230, 12289, 12290, 12298, 12302, 12303, 12304,
                              12305, 65281, 65288, 65289, 65292, 65306, 65307, 65311]

可以参考这个图

【python】 中英文混合块加密算法&&文本文件的块加密

三、参考答案

import numpy as np

def makeMatrix():

    englishCharactersList = []

    i = 32
    while (i != 127):
        englishCharactersList.append(i)
        i += 1

    chineseCharactersList = []

    j = 19968
    while (j != 40877):
        chineseCharactersList.append(j)
        j += 1

    chinesePunctuationList = [183, 215, 8212, 8216, 8217, 8220, 8221, 8230, 12289, 12290, 12298, 12302, 12303, 12304,
                              12305, 65281, 65288, 65289, 65292, 65306, 65307, 65311]
    allList = englishCharactersList + chineseCharactersList + chinesePunctuationList

    data = np.random.choice(allList, size=21025, replace=False)

    words = np.full((145, 145), 'k')

    x = 0

    for i in range(145):
        for j in range(145):

            words[i, j] = chr(int(data[x]))
            x += 1
    return words

def segmentationText(text):

    textList = list(text)
    if len(textList) % 2 != 0:
        textList.append(" ")
    data = []
    for index in range(0, len(textList), 2):
        data.append(textList[index:index + 2])
    data = np.array(data)

    return data

def encryption(words, data, text):

    cipher = []
    for i in range(len(data)):
        A = data[i, 0]
        B = data[i, 1]
        Ax, Ay, Bx, By = 0, 0, 0, 0

        if A == B:
            cipher.append(A)
            cipher.append(B)
            continue

        for x in range(145):
            for y in range(145):
                if words[x, y] == A:
                    Ax = int(x)
                    Ay = int(y)
                elif words[x, y] == B:
                    Bx = int(x)
                    By = int(y)

        if Ax == Bx or Ay == By:
            A, B = B, A
        else:
            A = words[Bx, Ay]
            B = words[Ax, By]
        cipher.append(A)
        cipher.append(B)
    cipherStr = "".join(cipher)
    print(f"原文为:{text}")
    print(f"加密后文本为:{cipherStr}")
    return cipher

def decryption(cipher, words, text):

    cipherList = segmentationText(cipher)

    clear = []
    for i in range(len(cipherList)):
        A = cipherList[i, 0]
        B = cipherList[i, 1]
        Ax, Ay, Bx, By = 0, 0, 0, 0

        if A == B:
            clear.append(A)
            clear.append(B)
            continue

        for x in range(145):
            for y in range(145):
                if words[x, y] == A:
                    Ax = int(x)
                    Ay = int(y)
                elif words[x, y] == B:
                    Bx = int(x)
                    By = int(y)

        if Ax == Bx or Ay == By:
            A, B = B, A
        else:
            A = words[Bx, Ay]
            B = words[Ax, By]
        clear.append(A)
        clear.append(B)
    clearStr = "".join(clear)
    print(f"原文为:{text}")
    print(f"解密为:{clearStr}")

text = input("请输入需要加密的字符串:")
words = makeMatrix()
data = segmentationText(text)
print(f"分割后数据为:\n{data}")
cipher = encryption(words, data, text)
decryption(cipher, words, text)

二、文本文件的块加密

一、安装 numpy 包

方法如下:https://blog.csdn.net/weixin_45759918/article/details/124532318

二、需求

增加了从文件中读取到写入文件的问题,并且要将文件名也加密,其实只是入口不一样了,别的没有变化。
在读文件时候注意把\n这个东西去掉,要不然保存出问题

注意!注意!注意!

需要加密的文件放在与py文件同一个文件夹下,这样可以直接写文件名,保存也会默认保存在这里。否则请使用绝对路径。

三、参考答案

import numpy as np
import os

def makeMatrix():

    englishCharactersList = []

    i = 32
    while (i != 127):
        englishCharactersList.append(i)
        i += 1

    chineseCharactersList = []

    j = 19968
    while (j != 40877):
        chineseCharactersList.append(j)
        j += 1

    chinesePunctuationList = [183, 215, 8212, 8216, 8217, 8220, 8221, 8230, 12289, 12290, 12298, 12302, 12303, 12304,
                              12305, 65281, 65288, 65289, 65292, 65306, 65307, 65311]
    allList = englishCharactersList + chineseCharactersList + chinesePunctuationList

    data = np.random.choice(allList, size=21025, replace=False)

    words = np.full((145, 145), 'k')

    x = 0

    for i in range(145):
        for j in range(145):

            words[i, j] = chr(int(data[x]))
            x += 1
    return words

def segmentationText(text):

    textList = list(text)
    if '\n' in textList:
        x = 0
        for i in range(len(textList)):
            if i == "\n":
                textList[x] == " "
            x += 1

    if len(textList) % 2 != 0:
        textList.append(" ")
    data = []
    for index in range(0, len(textList), 2):
        data.append(textList[index:index + 2])
    data = np.array(data)

    return data

def encryption(words, data, text):

    cipher = []
    for i in range(len(data)):
        A = data[i, 0]
        B = data[i, 1]
        Ax, Ay, Bx, By = 0, 0, 0, 0

        if A == B:
            cipher.append(A)
            cipher.append(B)
            continue

        for x in range(145):
            for y in range(145):
                if words[x, y] == A:
                    Ax = int(x)
                    Ay = int(y)
                elif words[x, y] == B:
                    Bx = int(x)
                    By = int(y)

        if Ax == Bx or Ay == By:
            A, B = B, A
        else:
            A = words[Bx, Ay]
            B = words[Ax, By]
        cipher.append(A)
        cipher.append(B)
    cipherStr = "".join(cipher)
    print(f"原文为:{text}")
    print(f"加密后文本为:{cipherStr}")
    return cipher

def decryption(cipher, words, text):

    cipherList = segmentationText(cipher)

    clear = []
    for i in range(len(cipherList)):
        A = cipherList[i, 0]
        B = cipherList[i, 1]
        Ax, Ay, Bx, By = 0, 0, 0, 0

        if A == B:
            clear.append(A)
            clear.append(B)
            continue

        for x in range(145):
            for y in range(145):
                if words[x, y] == A:
                    Ax = int(x)
                    Ay = int(y)
                elif words[x, y] == B:
                    Bx = int(x)
                    By = int(y)

        if Ax == Bx or Ay == By:
            A, B = B, A
        else:
            A = words[Bx, Ay]
            B = words[Ax, By]

        clear.append(A)
        clear.append(B)
    clearStr = "".join(clear)
    print(f"原文为:{text}")
    print(f"解密为:{clearStr}")

def readFile(fileName):
    strs = ""

    with open(fileName, 'r', encoding="UTF-8", newline=None) as file:
        strs = file.read().splitlines()
        st = "".join(strs)
        return st

def writeFile(cipher, fileName, words):

    encryptionFileName = str(fileName.split(".")[0])

    fileNameData = segmentationText(encryptionFileName)

    fileNamecipher = encryption(words, fileNameData, encryptionFileName)

    st = "".join(fileNamecipher) + "." + fileName.split(".")[-1]

    with open(st, "w", encoding="UTF-8") as op:
        op.write("加密后文本为:" + "".join(cipher))
        op.close()

    os.system("notepad "+fileName+" && "+"notepad "+st)

fileName = input("请输入需要加密的文件名:")

text = readFile(fileName)

words = makeMatrix()

data = segmentationText(text)
print(f"分割后数据为:\n{data}")

cipher = encryption(words, data, text)

decryption(cipher, words, text)

writeFile(cipher, fileName, words)

四、例子

加密前:

【python】 中英文混合块加密算法&&文本文件的块加密
加密后:
【python】 中英文混合块加密算法&&文本文件的块加密

Original: https://blog.csdn.net/weixin_45759918/article/details/124575212
Author: 刘泳谦
Title: 【python】 中英文混合块加密算法&&文本文件的块加密

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/761854/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球