目录

对称和非对称密码学(Symmetric & Asymmetric Cryptography)

在本章中,我们将详细讨论对称和非对称密码术。

对称密码学

在这种类型中,加密和解密过程使用相同的密钥。 它也被称为secret key cryptography 。 对称密码术的主要特征如下 -

  • 它更简单,更快捷。
  • 双方以安全的方式交换钥匙。

缺点 (Drawback)

对称加密的主要缺点是,如果密钥泄漏给入侵者,则可以轻松更改消息,这被视为风险因素。

Data Encryption Standard (DES)

最流行的对称密钥算法是数据加密标准(DES),Python包括一个包含DES算法背后的逻辑的包。

安装 (Installation)

在Python中安装DES包pyDES的命令是 -

pip install pyDES

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算法实现获取所有包,并以指定方式遵循加密和解密。

输出 (Output)

作为上面给出的代码的结果,您可以看到以下输出 -

DES算法

不对称密码学

它也被称为public key cryptography. 它以对称密码学的相反方式工作。 这意味着它需要两个密钥:一个用于加密,另一个用于解密。 公钥用于加密,私钥用于解密。

缺点 (Drawback)

  • 由于其密钥长度,它提供较低的加密速度。
  • 密钥管理至关重要。

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))

输出 (Output)

执行上面给出的代码时,您可以找到以下输出 -

RSA
↑回到顶部↑
WIKI教程 @2018