Cryptography-with-python-symmetric-and-asymmetric-cryptography

提供:Dev Guides
移動先:案内検索

対称および非対称暗号化

この章では、対称暗号化と非対称暗号化について詳しく説明します。

対称暗号化

このタイプでは、暗号化および復号化プロセスは同じキーを使用します。 *秘密鍵暗号*とも呼ばれます。 対称暗号の主な特徴は次のとおりです-

  • よりシンプルで高速です。
  • 両者は安全な方法で鍵を交換します。

欠点

対称暗号化の主な欠点は、キーが侵入者に漏洩した場合、メッセージが簡単に変更される可能性があり、これがリスク要因と見なされることです。

データ暗号化標準(DES)

最も一般的な対称鍵アルゴリズムはデータ暗号化標準(DES)であり、PythonにはDESアルゴリズムの背後にあるロジックを含むパッケージが含まれています。

インストール

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

DESアルゴリズムの実装ごとにすべてのパッケージを取得し、指定された方法で暗号化と復号化を行う変数 padmode を呼び出します。

出力

あなたは上記のコードの結果として次の出力を見ることができます-

DESアルゴリズム

非対称暗号化

  • 公開鍵暗号方式とも呼ばれます。対称暗号方式の逆の方法で機能します。 これは、暗号化用と復号化用の2つのキーが必要であることを意味します。 公開鍵は暗号化に使用され、秘密鍵は復号化に使用されます。

欠点

  • キーの長さにより、暗号化速度が低下します。
  • キー管理は非常に重要です。

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

出力

上記のコードを実行すると、次の出力を見つけることができます-

RSA