如何使用公钥加密数据并在python中使用base64对其进行编码?

发布于 2025-01-16 16:34:44 字数 1489 浏览 3 评论 0原文

我想使用python实现以下功能,它使用公钥来加密密码,然后使用base64对其进行编码。我搜索了很多答案,但没有找到解决方案,我想可能是我不理解它们。您能给我一些建议吗?

// # java code
public static String encryptRSA(String password, String publicKey) {
        try {
            byte[] decoded = Base64.decode(publicKey);
            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA")
                    .generatePublic(new X509EncodedKeySpec(decoded));
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            String outStr = Base64.encode(cipher.doFinal(password.getBytes("UTF-8")));
            return outStr;
        } catch (Exception e) {
        }
        return null;
    }

我使用以下代码,但它引发错误 M2Crypto.RSA.RSAError

# python code
import base64

import M2Crypto

pub = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQClnY+3rAf/az9t2bxC80TObpZ2ZCH1xSjPt9QtXl6k6UtD7mQcI2CWSwnDgKJr2m2WnM1kR6X+oOL61lXO0gSuuD8tWOx/knZA2VaSTLdsHBDLOX3e6Fo/O3CtoLVwO5FYFBIFHXMoikPkR8tFIOLWsX0y3slLQQShwSJAHytP4QIDAQAB"
password = 123


def public_encrypt(public_key, password):
    rsa_pub = M2Crypto.RSA.load_key_string(public_key.encode('utf-8'))
    ctxt_pub = rsa_pub.public_encrypt(password.encode(), M2Crypto.RSA.pkcs1_padding)
    ctxt64_pub = base64.b64encode(ctxt_pub).decode()
    return ctxt64_pub


res = public_encrypt(pub, password)
print('res:', res)

I want to implement the following function using python, it uses public key to encrypt the password and then using base64 to encode it. I have searched many answers but I didn't find a solution, I think probably I didn't understand them. Would you please give me some advice?

// # java code
public static String encryptRSA(String password, String publicKey) {
        try {
            byte[] decoded = Base64.decode(publicKey);
            RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA")
                    .generatePublic(new X509EncodedKeySpec(decoded));
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            String outStr = Base64.encode(cipher.doFinal(password.getBytes("UTF-8")));
            return outStr;
        } catch (Exception e) {
        }
        return null;
    }

I use the following code, but it raises error M2Crypto.RSA.RSAError.

# python code
import base64

import M2Crypto

pub = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQClnY+3rAf/az9t2bxC80TObpZ2ZCH1xSjPt9QtXl6k6UtD7mQcI2CWSwnDgKJr2m2WnM1kR6X+oOL61lXO0gSuuD8tWOx/knZA2VaSTLdsHBDLOX3e6Fo/O3CtoLVwO5FYFBIFHXMoikPkR8tFIOLWsX0y3slLQQShwSJAHytP4QIDAQAB"
password = 123


def public_encrypt(public_key, password):
    rsa_pub = M2Crypto.RSA.load_key_string(public_key.encode('utf-8'))
    ctxt_pub = rsa_pub.public_encrypt(password.encode(), M2Crypto.RSA.pkcs1_padding)
    ctxt64_pub = base64.b64encode(ctxt_pub).decode()
    return ctxt64_pub


res = public_encrypt(pub, password)
print('res:', res)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦里的微风 2025-01-23 16:34:44

完整错误信息为:M2Crypto.RSA.RSAError: no start line,说明密钥导入不正确。

load_key_string() 需要 PKCS#1 或 PKCS#8 格式的 PEM 编码私钥,但不需要公钥。可以使用 load_pub_key_bio()

根据发布的 X.509/SPKI 密钥,可以通过在每 64 个字符后添加换行符并添加相应的页眉和页脚来创建 PEM 编码密钥:

import M2Crypto

x509 = '''-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQClnY+3rAf/az9t2bxC80TObpZ2
ZCH1xSjPt9QtXl6k6UtD7mQcI2CWSwnDgKJr2m2WnM1kR6X+oOL61lXO0gSuuD8t
WOx/knZA2VaSTLdsHBDLOX3e6Fo/O3CtoLVwO5FYFBIFHXMoikPkR8tFIOLWsX0y
3slLQQShwSJAHytP4QIDAQAB
-----END PUBLIC KEY-----'''

bio = M2Crypto.BIO.MemoryBuffer(x509)
rsa_pub = M2Crypto.RSA.load_pub_key_bio(bio)

另一个问题是没有定义 encode()对于一个整数,但大概 password 应该是一个字符串,这只是一个复制/粘贴错误。

通过这些更改,代码就可以工作了。

请注意,如今 1024 位 RSA 密钥(如您的密钥)是不安全的,长度应 >= 2048 位。

The full error message is: M2Crypto.RSA.RSAError: no start line, indicating that the key is imported incorrectly.

load_key_string() requires a PEM-encoded private key in PKCS#1 or PKCS#8 format, but no public key. A PEM encoded public key in X.509/SPKI format can be imported with load_pub_key_bio().

From the posted X.509/SPKI key a PEM encoded key can be created by adding a newline after every 64 characters and adding a corresponding header and footer:

import M2Crypto

x509 = '''-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQClnY+3rAf/az9t2bxC80TObpZ2
ZCH1xSjPt9QtXl6k6UtD7mQcI2CWSwnDgKJr2m2WnM1kR6X+oOL61lXO0gSuuD8t
WOx/knZA2VaSTLdsHBDLOX3e6Fo/O3CtoLVwO5FYFBIFHXMoikPkR8tFIOLWsX0y
3slLQQShwSJAHytP4QIDAQAB
-----END PUBLIC KEY-----'''

bio = M2Crypto.BIO.MemoryBuffer(x509)
rsa_pub = M2Crypto.RSA.load_pub_key_bio(bio)

Another issue is that there is no encode() defined for an integer, but presumably password is supposed to be a string and this is just a copy/paste error.

With these changes the code works.

Note that a 1024 bits RSA key (like yours) is insecure nowadays, instead the length should be >= 2048 bits.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文