23

PyCryptoを使用してPythonで一部のデータを暗号化したい。

ただし、使用するとエラーが発生しますkey = RSA.importKey(pubkey)

RSA key format is not supported

キーは次のように生成されました:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout mycert.key -out mycert.pem

コードは次のとおりです。

def encrypt(data):
    pubkey = open('mycert.pem').read()
    key = RSA.importKey(pubkey)
    cipher = PKCS1_OAEP.new(key)
    return cipher.encrypt(data)
4

2 に答える 2

38

PyCryptoはX.509証明書をサポートしていません。最初に、次のコマンドを使用して公開鍵を抽出する必要があります。

openssl x509 -inform pem -in mycert.pem -pubkey -noout > publickey.pem

次に、で使用できRSA.importKeyますpublickey.pem


opensslを使用したくない、または使用できない場合は、PEM X.509証明書を取得して、次のように純粋なPythonで実行できます。

from Crypto.Util.asn1 import DerSequence
from Crypto.PublicKey import RSA
from binascii import a2b_base64

# Convert from PEM to DER
pem = open("mycert.pem").read()
lines = pem.replace(" ",'').split()
der = a2b_base64(''.join(lines[1:-1]))

# Extract subjectPublicKeyInfo field from X.509 certificate (see RFC3280)
cert = DerSequence()
cert.decode(der)
tbsCertificate = DerSequence()
tbsCertificate.decode(cert[0])
subjectPublicKeyInfo = tbsCertificate[6]

# Initialize RSA key
rsa_key = RSA.importKey(subjectPublicKeyInfo)
于 2012-10-16T19:14:27.330 に答える
1

これが良い例です:https ://www.dlitz.net/software/pycrypto/api/2.6/Crypto.Cipher.PKCS1_OAEP-module.html

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

# sender side
message = 'To be encrypted'
key = RSA.importKey(open('pubkey.der').read())
cipher = PKCS1_OAEP.new(key)
ciphertext = cipher.encrypt(message)

# receiver side
key = RSA.importKey(open('privkey.der').read())
cipher = PKCS1_OAP.new(key)
message = cipher.decrypt(ciphertext)
于 2017-01-09T19:36:58.523 に答える