python 異或加密 (加密重要信息)

python 異或加密

說明:

- 通過密碼對文件進行異或加密並存儲加密文件
- 首次使用需要對創建account.txt 並設置密碼
- rsa 未使用、但可以用
# -*- coding: utf-8 -*-
# [email protected]
# Derek
# 12/16/2018

"""
這是一個對文本進行加密的程序
"""

import os
import time
import rsa
import hashlib


class RSA(object):
    """rsa 加密 解密操作"""
    def __init__(self):
        self.public_key_file_name = 'public.pem'
        self.private_key_file_name = 'private.pem'

        self.is_empty_create_key()

    def is_empty_create_key(self):
        """沒有時:創建私鑰公鑰"""
        for file in [self.public_key_file_name, self.private_key_file_name]:
            if not self.judge_file_exists(file):
                public_key, private_key = self.create_new_key()
                self.operation_file(self.public_key_file_name, 'w', public_key)
                self.operation_file(self.private_key_file_name, 'w', private_key)

    @staticmethod
    def judge_file_exists(file_name):
        """判斷文件是否存在"""
        return os.path.exists(file_name)

    @staticmethod
    def rsa_write_file(file_name, inner=None):
        """對文件進行讀操作"""
        with open(file_name, 'w')as f:
            f.write(inner.save_pkcs1().decode())

    def read_rsa_public(self):
        with open(self.public_key_file_name, 'r') as f:
            return rsa.PublicKey.load_pkcs1(f.read().encode())

    def read_rsa_private(self):
        with open(self.private_key_file_name, 'r') as f:
            return rsa.PrivateKey.load_pkcs1(f.read().encode())

    @staticmethod
    def create_new_key(number=1024):
        """創建私鑰公鑰"""
        return rsa.newkeys(number)

    def rsa_encrypt(self, message):
        """rsa 加密"""
        return rsa.encrypt(message.encode(), self.read_rsa_public())

    def rsa_decrypt(self, crypto):
        """rsa 解密"""
        return rsa.decrypt(crypto, self.read_rsa_private()).decode()


class StrNumber(object):
    """異或加密"""
    def __init__(self, text=None, password=None):
        self.text = text
        self.password = self.get_md5(password)

    @staticmethod
    def get_md5(md5str):
        """對字符 md5"""
        # 生成一個md5對象
        m1 = hashlib.md5()

        # 使用md5對象裏的update方法md5轉換
        m1.update(md5str.encode("utf-8"))
        token = m1.hexdigest()
        return token

    def text_2_number(self, text=None):
        """字符轉數字字符"""
        if not text:
            text = self.text
        number_str = ''
        for i in text:
            s = str(ord(i))
            number_str += '0' * (7 - len(s)) + s
        return number_str

    @staticmethod
    def number_2_text(number_str):
        """數字轉字符"""
        number_str = str(number_str)
        text_list = []
        y = len(number_str) % 7
        if y:
            number_str = '0' * (7-y) + number_str

        for i in range(0, len(number_str), 7):
            text_list.append(chr(int(number_str[i: i+7])))
        return "".join(text_list)

    def encrypt(self):
        """加密"""
        a = int(self.text_2_number(self.text))
        b = int(self.text_2_number(self.password))
        d = int(len(str(a)) / len(str(b)))
        if d:
            b = int(str(b) * d)

        return str(a ^ b)

    def decrypt(self, number_str):
        """解密"""
        a = int(self.text_2_number(self.password))
        b = int(len(number_str) / len(str(a)))
        if b:
            a = str(a) * b
        n = int(number_str) ^ int(a)
        return self.number_2_text(n)


def get_password():
    """獲取密碼"""
    password1 = input("please enter password1:")
    password2 = input("please enter password2:")
    password3 = input("please enter password3:")

    n = StrNumber(password1, password2)
    text = n.encrypt()

    n = StrNumber(text, password3)
    return n.encrypt()


def _encrypt(password, text=None):
    """加密"""
    if not text:
        with open('account.txt', 'r')as f:
            text = f.read()

    n = StrNumber(text, password)
    text = n.encrypt()

    with open('encryption_account', 'w')as f:
        f.write(text)


def _decrypt(password):
    """解密"""
    with open('encryption_account', 'r')as f:
        text = f.read()

    n = StrNumber(None, password)
    text = n.decrypt(text)

    return text


def main():
    """啓動函數"""
    print('='*20)
    print("說明:")
    print('對文件:account.txt 加密')
    print('加密後存儲到: encryption_account')
    print('='*20)
    password = get_password()
    while True:
        print('=' * 20)
        print('請選擇: 1:加密, 2:查看解密後的內容, 3:添加內容, 4:解密並存儲到account.txt, q:退出')
        result = input('請輸入:')
        if '1' == result:
            _encrypt(password)
        elif '2' == result:
            print()
            print('內容:')
            print('=' * 20)
            print(_decrypt(password))
            print('=' * 20)
            print()

        elif '3' == result:
            text = _decrypt(password)
            text += '\n{}'.format(input('請輸入添加內容:'))
            _encrypt(password, text)
        elif '4' == result:
            text = _decrypt(password)
            with open('account.txt', 'w')as f:
                f.write(text)
        elif 'q' == result:
            print('歡迎使用。已退出')
            exit(1)
        else:
            print('輸入錯誤請重新輸入')

        time.sleep(1)


def rsa_main():
    """rsa 的操作"""
    r = RSA()
    a = r.rsa_encrypt('123456')
    with open('encryption_account', 'wb')as f:
        f.write(a)

    with open('encryption_account', 'rb')as f:
        b = f.read()
    print('加密後的內容:', b)
    print('解密:', r.rsa_decrypt(b))


if __name__ == '__main__':
    main()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章