41、常見的加密方式


常見的加密方式

1. Base64

1.1 介紹

Base64是一種用64個字符來表示任意二進制數據的方法。base64是一種編碼方式而不是加密算法。只是看上去像是加密

Base64使用A-Z,a-z,0-9,+,/ 64個字符實現對數據進行加密

1.2 Python使用

import base64
base64.b64encode(b'sxt')
b'YmluYXJ5AHN0cmluZw=='
base64.b64decode(b'YmluYXJ5AHN0cmluZw==')

2. MD5加密

2.1 介紹

MD5信息摘要算法(英語:MD5 Message-Digest Algorithm),一種被廣泛使用的密碼散列函數,可以產生出一個128位(16字節)的散列值(hash value),用於確保信息傳輸完整一致

當我們需要保存某些密碼信息以用於身份確認時,如果直接將密碼信息以明碼方式保存在數據庫中,不使用任何保密措施,系統管理員就很容易能得到原來的密碼信息,這些信息一旦泄露, 密碼也很容易被破譯。為了增加安全性,有必要對數據庫中需要保密的信息進行加密,這樣,即使有人得到了整個數據庫,如果沒有解密算法,也不能得到原來的密碼信息

2.2 Python介紹

import hashlib

def test_md51():
    m = hashlib.md5()
    m.update(b'sxt')
    pwd = m.hexdigest()
    print(pwd)

def test_md52():
    pwd = hashlib.new('md5', b'sxt').hexdigest()
    print(pwd)

def test_md53():
    data ='你好'
    pwd = hashlib.md5(data.encode(encoding='UTF-8')).hexdigest()
    print(pwd)

3. AES/DES

https://pycryptodome.readthedocs.io/en/latest/src/introduction.html

3.1 介紹

DES全稱為Data Encryption Standard,即數據加密標准,是一種使用密鑰加密的算法。該加密算法是一種對稱加密方式,其加密運算、解密運算需要使用的是同樣的密鑰(一組字符串)即可

注意:

現在用AES這個標准來替代原先先的DES

AES與DES的區別:

  • 加密后密文長度不同:
    • DES加密后密文長度是8的整數倍
    • AES加密后密文長度是16的整數倍
  • 應用場景的不同:
    • 企業級開發使用DES足夠安全
    • 如果要求使用AES

使用DES/AES進行數據交互時要求雙方都擁有相同的私鑰

3.2 安裝

pip3 install pycryptodome

3.3 Python使用

DES

import base64
from Crypto.Cipher import DES


class EncryptDate:
    def __init__(self, key):
        self.key = key.encode("utf-8")  # 初始化**
        self.length = DES.block_size  # 初始化數據塊大小
        self.aes = DES.new(self.key, DES.MODE_ECB)  # 初始化AES,ECB模式的實例
  
    def pad(self, text):
        """
        #填充函數,使被加密數據的字節碼長度是block_size的整數倍
        """
        # count = len(text.encode('utf-8'))
        # add = self.length - (count % self.length)
        # entext = text + (chr(add) * add)
        # return entext
        args = text.encode('utf-8')
        while len(args) % DES.block_size != 0:
                args += b'\x00'
        return args.decode()

    def encrypt(self, encrData):  # 加密函數
        res = self.aes.encrypt(self.pad(encrData).encode("utf8"))
        msg = str(base64.b64encode(res), encoding="utf8")
        return msg

    def decrypt(self, decrData):  # 解密函數
        res = base64.decodebytes(decrData.encode("utf8"))
        msg = self.aes.decrypt(res).decode("utf8")
        return msg


eg = EncryptDate("12345678")  # 這里**的長度必須是16的倍數
data = {"name": "sxt123", "realname": "尚學堂", "sex": "1"}
res = eg.encrypt(str(data))
print(res)
print(eg.decrypt(res))

AES

import base64
from Crypto.Cipher import AES


class EncryptDate:
    def __init__(self, key):
        self.key = key.encode("utf-8")  # 初始化**
        self.length = AES.block_size  # 初始化數據塊大小
        self.aes = AES.new(self.key, AES.MODE_ECB)  # 初始化AES,ECB模式的實例
  
    def pad(self, text):
        """
        #填充函數,使被加密數據的字節碼長度是block_size的整數倍
        """
        # count = len(text.encode('utf-8'))
        # add = self.length - (count % self.length)
        # entext = text + (chr(add) * add)
        # return entext
        args = text.encode('utf-8')
        while len(args) % AES.block_size != 0:
                args += b'\x00'
        return args.decode()

    def encrypt(self, encrData):  # 加密函數
        res = self.aes.encrypt(self.pad(encrData).encode("utf8"))
        msg = str(base64.b64encode(res), encoding="utf8")
        return msg

    def decrypt(self, decrData):  # 解密函數
        res = base64.decodebytes(decrData.encode("utf8"))
        msg = self.aes.decrypt(res).decode("utf8")
        return msg


eg = EncryptDate("1234567890123456")  # 這里**的長度必須是16的倍數
data = {"name": "sxt123", "realname": "尚學堂", "sex": "1"}
res = eg.encrypt(str(data))
print(res)
print(eg.decrypt(res))

4. RSA

4.1 介紹

RSA加密算法是一種非對稱加密算法。在公開密鑰加密和電子商業中RSA被廣泛使用

RSA算法需要兩個密鑰:

  • 公開密鑰(publickey)
  • 私有密鑰(privatekey)
  • 公鑰與私鑰是一對,如果用公鑰對數據進行加密,只有用對應的私鑰才能解密。因為加密和解密使用的是兩個不同的密鑰,所以這種算法叫作非對稱加密算法

使用時都是使用公鑰加密,使用私鑰解密。公鑰可以公開,私鑰自己保留。

算法強度復雜、安全性依賴算法與密鑰但是由於其算法復雜,而使得加密解密速度沒有對稱加密速度快。

4.2 Python使用

class EncryptDate():
    def encrypt_data(self,msg,pb):
        key = RSA.importKey(pb)
        cipher = PKCS1_cipher.new(key)
        encrypt_text = base64.b64encode(cipher.encrypt(bytes(msg.encode("utf-8"))))
        return encrypt_text.decode('utf-8')

    def decrypt_data(self,msg,pv):
        key = RSA.importKey(pv)
        cipher = PKCS1_cipher.new(key)
        back_text = cipher.decrypt(base64.b64decode(msg), 0)
        return back_text.decode('utf-8')

if __name__ == '__main__':
    enc = EncryptDate()
    tmp = enc.encrypt_data('123',public_key)
    print(enc.decrypt_data(tmp,private_key))


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM