且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用密钥加密字符串

更新时间:2023-11-15 17:58:34

我的博文(John Boker的答案中的passingcuriosity.com链接)使用M2Crypto库执行AES - 对称加密算法。 M2Crypto是围绕OpenSSL的Python包装器。 API几乎是将OpenSSL转换为Python的一个直接的翻译,所以稍微粗略的文档不应该是太多的问题。如果您需要使用的公钥加密算法由M2Crypto支持,那么您可以很好地使用它来进行公钥加密。

My blog post (the passingcuriosity.com link in John Boker's answer) does AES -- a symmetric encryption algorithm -- using the M2Crypto library. M2Crypto is a Python wrapper around OpenSSL. The API is pretty much a straight translation of OpenSSL's into Python, so the somewhat sketchy documentation shouldn't be too much of a problem. If the public key encryption algorithm you need to use is supported by M2Crypto, then you could very well use it to do your public key cryptography.

我发现 M2Crypto测试套件是使用其API的有用示例。特别是,RSA(在test_rsa.py),PGP(在test_pgp.py)和EVP(在test_evp.py)测试将帮助您了解如何设置和使用库。请注意,它们是单元测试,所以确定哪些代码是必需的,什么是作为测试的工件可能有点棘手。

I found the M2Crypto test suite to be a useful example of using its API. In particular, the RSA (in test_rsa.py), PGP (in test_pgp.py), and EVP (in test_evp.py) tests will help you figure out how to set up and use the library. Do be aware that they are unit-tests, so it can be a little tricky to figure out exactly what code is necessary and what is an artefact of being a test.

PS:我是新的,我的帖子只能包含一个链接,所以我不得不删除大部分链接。对不起,

PS: As I'm new, my posts can only contain one link so I had to delete most of them. Sorry.

from M2Crypto import RSA

rsa = RSA.load_pub_key('rsa.pub.pem')
encrypted = rsa.public_encrypt('your message', RSA.pkcs1_oaep_padding)
print encrypted.encode('base64')



输出



Output


X3iTasRwRdW0qPRQBXiKN5zvPa3LBiCDnA3HLH172wXTEr4LNq2Kl32PCcXpIMxh7j9CmysLyWu5
GLQ18rUNqi9ydG4ihwz3v3xeNMG9O3/Oc1XsHqqIRI8MrCWTTEbAWaXFX1YVulVLaVy0elODECKV
4e9gCN+5dx/aG9LtPOE=