2

そこで、OpenSSLを使用して自己署名証明書と秘密鍵を生成しました。

今私はしようとしています:

a)公開鍵を文字列として出力します。これ:

f = open(CERT_FILE)
cert_buffer = f.read()
f.close()
cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_buffer)
pub_key = cert.get_pubkey()
print pub_key

次のようなものを印刷します:

<OpenSSL.crypto.PKey object at 0x7f059864d058>

b)この公開鍵で文字列を暗号化する

c)暗号化された文字列を秘密鍵で復号化する

いくつかのコード例を見たいです。OpenSSLのみを使用し、ラッパーは使用しないでください。

4

1 に答える 1

2

これは、あなたの望むことですか?PyOpenSSLではなくPyCryptoを使用します(ラッパーがないと言ったときにこれが避けたいかどうかはわかりません)

#!/usr/bin/env python

from Crypto.Cipher import AES
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA

def step1():
    rsaKey = RSA.importKey(open("./myKey.der", 'r'))
    print "Step 1: This is my rsa-key:\n%s" % rsaKey.exportKey()

def step2_encrypt(string):
    rsaKey = RSA.importKey(open("./myKey.der", 'r'))
    pkcs1CipherTmp = PKCS1_OAEP.new(rsaKey)
    encryptedString = pkcs1CipherTmp.encrypt(string)
    print "Step 2: encrypted %s is %s" % (string, encryptedString)
    return encryptedString

def step3_decrypt(encryptedString):
    rsaKey = RSA.importKey(open("./myKey.der", 'r'))
    pkcs1CipherTmp = PKCS1_OAEP.new(rsaKey)
    decryptedString = pkcs1CipherTmp.decrypt(encryptedString)
    print "Step 3: decryptedString %s is %s" % (encryptedString, decryptedString)
    return decryptedString


if __name__ == "__main__":
    step1()
    encryptedString = step2_encrypt("hello, duuude")
    decryptedString = step3_decrypt(encryptedString)
    print "Tadaaaa: %s" % decryptedString

キーファイルにはパブリック/プライベート部分が含まれているため、暗号化/復号化モジュールは何をすべきかを認識します。

2つの別々のファイルに公開/秘密鍵が必要ですか(簡単なはずですよね)?

非対称暗号化を使用する場合、暗号化できる最大文字数は、キーで使用されているモジュラスによって異なることに注意してください。上記の例では、通常のRSAキー(SHA-1、モジュラス20バイト)を使用すると、214バイトを超える文字列に対してエラーが発生します。cyroxxがコメントで指摘しているように、アルゴリズムに理論的な制限はありません(非常に長いキーで長い文字列を暗号化できますが、計算にかかる時間により、実用的な目的ではかなり実行不可能になります。

If you need to cypher big chunks of data, you'll probably want to encrypt that data with a symmetric algorithm (like AES) and send the password encrypted with the RSA (asymmetric) keys along in the transferred data... but that's a different matter with a number of other issues :-)

于 2012-08-02T15:33:51.373 に答える