Skip to main content
 首页 » 编程设计

python之如何将公钥打印为字符串并用它加密

2025年05月04日19zhenyulu

所以我用 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,不要使用包装器。

请您参考如下方法:

这是你想要的吗?它使用 PyCrypto , 不是 PyOpenSSL (当你提到没有包装器时,我不确定这是否是你想要避免的)

#!/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 

key 文件包含公共(public)/私有(private)部分,因此加密/解密模块将知道该做什么。

您是否需要将公钥/私钥放在两个单独的文件中(应该很简单,对吧)?

请注意,使用非对称加密时,您可以加密的最大字符数取决于 modulus在你的 key 中使用。在上面的示例中,如果您使用常规 RSA key (SHA-1,模数为 20 字节),您将收到大于 214 字节的字符串的错误。作为cyroxx在评论中指出,该算法没有理论上的限制(您可以使用非常长的 key 加密长字符串)但它所花费的计算时间使其在实际应用中非常不可行。

如果您需要加密大块数据,您可能希望使用对称算法(如 AES)加密该数据,并在传输的数据中发送使用 RSA(非对称) key 加密的密码...但这与许多其他问题不同 :-)