首页 > 代码库 > Python-RSA(公私钥制作,加解密,签名)

Python-RSA(公私钥制作,加解密,签名)

  • Signing data with the RSA algorithm


  • Step1. Create private/public keypair (optional)

openssl genrsa -out private.pem 1024  >private.pem

This creates a key file called private.pem. This file actually have both the private and public keys, so you should extract the public one from this file:

openssl rsa -in private.pem -out public.pem -outform PEM -pubout   >public.pem

You‘ll now have public.pem containing just your public key, you can freely share this with 3rd parties.


  • Step2. Create a hash of the data

echo ‘data to sign‘     > data.txt
openssl dgst -md5 data.txt    >data‘s md5 code


  • Step3. Sign the hash using the private key

openssl rsautl -sign -inkey private.pem -keyform PEM  -md5 -out data.sign  data.txt  > signature

The file ‘signature‘ and the actual data ‘data.txt‘ can now be communicated to the receiving end. The hash algorithm (in our case md5) as well as the public key must also be known to the receiving end.


  • Authenticate data using the public key


  • Step4. Create a hash of the data (same as Step 2)


  • Step5. Verify the signature

openssl rsautl -verify -inkey public.pem -keyform PEM -pubin -md5 -signature -signature data.sign data.txt  > verified
diff -s verified hash

If the result of the above command ‘verified‘ matches the hash generated in Step 3.1 (in which case you the result of the diff command would be ‘Files verified and hash are identical‘) then the signature is considered authentic and the integrity/authenticity of the data is proven.


本文出自 “Mr_Computer” 博客,请务必保留此出处http://caochun.blog.51cto.com/4497308/1559636

Python-RSA(公私钥制作,加解密,签名)