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

2024-04-18 00:55:57 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我用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

打印如下内容:

^{pr2}$

b)用这个公钥加密字符串

c)用私钥解密加密字符串

我想看看一些代码示例。请只使用OpenSSL,不使用包装器。在


Tags: key字符串closereadcertbufferopencrypto
1条回答
网友
1楼 · 发布于 2024-04-18 00:55:57

这是你想要的吗?它使用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

密钥文件包含公共/私有部分,因此加密/解密模块将知道该怎么做。在

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

请注意,使用非对称加密时,可以加密的最大字符数取决于密钥中使用的modulus。在上面的示例中,如果使用常规的RSA密钥(SHA-1,模数为20字节),则对于大于214字节的字符串,将出现错误。正如cyroxx在评论中指出的,该算法没有理论上的局限性(可以用非常长密钥加密长字符串),但它所需的计算时间使其在实际应用中非常不受欢迎。在

如果您需要对大数据块进行加密,您可能需要使用对称算法(如AES)加密该数据,并在传输的数据中发送使用RSA(非对称)密钥加密的密码。。。但这与其他一些问题不同:—)

相关问题 更多 >

    热门问题