
對稱加密和非對稱加密
本章我們將詳細討論對稱加密和非對稱加密。
對稱加密
在這種型別中,加密和解密過程使用相同的金鑰。它也稱為**秘密金鑰加密**。對稱加密的主要特點如下:
- 它更簡單、更快。
- 雙方以安全的方式交換金鑰。
缺點
對稱加密的主要缺點是,如果金鑰洩露給入侵者,訊息可以很容易地被更改,這被認為是一個風險因素。
資料加密標準 (DES)
最流行的對稱金鑰演算法是資料加密標準 (DES),Python 包含一個包含 DES 演算法背後邏輯的包。
安裝
在 Python 中安裝 DES 包**pyDES** 的命令是:
pip install pyDES

DES 演算法的簡單程式實現如下:
import pyDes data = "DES Algorithm Implementation" k = pyDes.des("DESCRYPT", pyDes.CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=pyDes.PAD_PKCS5) d = k.encrypt(data) print "Encrypted: %r" % d print "Decrypted: %r" % k.decrypt(d) assert k.decrypt(d) == data
它呼叫變數**padmode**,該變數根據 DES 演算法實現獲取所有包,並以指定的方式執行加密和解密。
輸出
您可以看到上面給出的程式碼產生的以下輸出:

非對稱加密
它也稱為**公鑰加密**。它的工作方式與對稱加密相反。這意味著它需要兩個金鑰:一個用於加密,另一個用於解密。公鑰用於加密,私鑰用於解密。
缺點
- 由於其金鑰長度,它導致較低的加密速度。
- 金鑰管理至關重要。
以下 Python 程式程式碼說明了使用 RSA 演算法及其實現的非對稱加密的工作原理:
from Crypto import Random from Crypto.PublicKey import RSA import base64 def generate_keys(): # key length must be a multiple of 256 and >= 1024 modulus_length = 256*4 privatekey = RSA.generate(modulus_length, Random.new().read) publickey = privatekey.publickey() return privatekey, publickey def encrypt_message(a_message , publickey): encrypted_msg = publickey.encrypt(a_message, 32)[0] encoded_encrypted_msg = base64.b64encode(encrypted_msg) return encoded_encrypted_msg def decrypt_message(encoded_encrypted_msg, privatekey): decoded_encrypted_msg = base64.b64decode(encoded_encrypted_msg) decoded_decrypted_msg = privatekey.decrypt(decoded_encrypted_msg) return decoded_decrypted_msg a_message = "This is the illustration of RSA algorithm of asymmetric cryptography" privatekey , publickey = generate_keys() encrypted_msg = encrypt_message(a_message , publickey) decrypted_msg = decrypt_message(encrypted_msg, privatekey) print "%s - (%d)" % (privatekey.exportKey() , len(privatekey.exportKey())) print "%s - (%d)" % (publickey.exportKey() , len(publickey.exportKey())) print " Original content: %s - (%d)" % (a_message, len(a_message)) print "Encrypted message: %s - (%d)" % (encrypted_msg, len(encrypted_msg)) print "Decrypted message: %s - (%d)" % (decrypted_msg, len(decrypted_msg))
輸出
執行上面給出的程式碼時,您可以找到以下輸出:

廣告