python implements the RSA encryption and signature, and encryption and decryption program segment

python achieve RSA encryption and signature solution plus sign

1, for generating a secret key

In terms of presentation here to generate a manual key pair (secret key projects to be generated by the development would directly give to us)

Generating a secret key of the time, you can specify the length of the secret key generated, usually recommended 1024bit, 1024bit rsa the public key data is encrypted, the encrypted data can only 117byte a), the data amount exceeds this number, the data needs to be segment encryption, but now the secret key 1024bit length has been proven safe enough, try using a secret key 2048bit length. 2048bit secret key length, the data length of up 245byte

Calculated as follows:

The maximum length of encryption keys (unit :)

Here one pair of keys generated in 1024bit

from Crypto Import the Random
 from Crypto.PublicKey Import the RSA 
# pseudo-random number generator 
random_gen = Random.new () Read. 
# Private keys for the object instance: the secret key length is 1024 
RSA = RSA.generate (1024 , random_gen ) 
# obtain the public key, saved to a file 
private_pem = rsa.exportKey () 
with Open ( ' private.pem ' , ' wb ' ) AS f: 
    f.write (private_pem) 
# get the private key saved to a file 
public_pem = rsa .publickey (). exportKey () 
with Open ( 'public.pem', 'wb') as f:
    f.write(public_pem)

 

 

 

 

2, encryption and decryption

1, public key encryption
Import Base64
 from Crypto.PublicKey Import the RSA
 from Crypto.Cipher Import PKCS1_v1_5 
MSG = " to be encrypted plaintext content " # public file is read 
Key = Open ( ' public.pem ' ) .read () 
the publickey = the RSA .importKey (Key)
 # encrypted 
PK = PKCS1_v1_5.new (the publickey) 
encrypt_text = pk.encrypt (msg.encode ())
 # encrypted encoded by Base64 
Result = base64.b64encode (encrypt_text)
 Print (Result)

 

2, private key to decrypt
import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
# 密文
msg='bAlnUNEJeDLnWikQs1ejwqPTo4qZ7RWxgFwoO4Bfg3C7EY+1HN5UvJYJ2h6047K6vNjG+TiIxc0udTR7a12MivSA+DwoGjwFIb25u3zc+M8KTCaCT5GdSumDOto2tsKYaVDKCPZpdwYdzYwlVijr6cPcchQTlD1yfKk2khhNchU='# base64解码
msg = base64.b64decode(msg)
# 获取私钥
privatekey = open('private.pem').read()
rsakey = RSA.importKey(privatekey)
# 进行解密
cipher =PKCS1_v1_5.new (rsakey) 
text = cipher.decrypt (MSG, ' DecryptError ' )
 # decrypted out of the byte code format, decodee converted to a string 
Print (text.decode ())

 

 

3, encryption and decryption segment

Private keys are generated when the above-mentioned encrypted in our time, if the data length exceeds the current secret key can handle the maximum length, the encryption need be segmented,

Encryption segment: plain talk is a long list of the original data into a plurality of segments, each segment size is within the maximum number of encryption keys, the data is then encrypted finished after splicing.
Subparagraph decrypt: encrypted data through segmentation, we have time during the decryption will it be divided into multiple sections, and then splicing can get the original data content after decryption.

Segment encryption and decryption code is as follows:

Import Base64
 from Crypto.PublicKey Import the RSA
 from Crypto.Cipher Import PKCS1_v1_5 
DEF cipher (MSG):
     "" " 
    Public key encryption 
    : param msg: To the encrypted content 
    : return: after being encrypted ciphertext 
    " "" 
    # Get well Key 
    Key = Open ( ' public.pem ' ) .read () 
    the publickey = RSA.importKey (Key)
     # segment encrypted 
    PK = PKCS1_v1_5.new (the publickey) 
    encrypt_text = []
     for I inRange (0, len (MSG), 100 ): 
        CONT = MSG [I: I + 100 ] 
        encrypt_text.append (pk.encrypt (cont.encode ())) 
    # encryption End splicing 
    Cipher_Text = B '' .join ( encrypt_text)
     # Base64 encoding 
    Result = base64.b64encode (Cipher_Text)
     return result.decode () 
DEF the decrypt (MSG):
     "" " 
    decrypt the private key 
    : param msg: ciphertext: string type 
    after decryption:: return content 
    "" " 
    # Base64 decoding 
    MSG = base64.b64decode (MSG)
     # acquires the private key 
    PrivateKey = Open ( 'private.pem').read()
    rsakey = RSA.importKey(privatekey)
    cipher =  PKCS1_v1_5.new(rsakey)
    # 进行解密
    text = []
    for i in range(0,len(msg),128):
        cont = msg[i:i+128]
        text.append(cipher.decrypt(cont,1))
    text = b''.join(text)
    return text.decode()

 

3, signature and signed inspection

1, private key signature
from Crypto.Hash Import the SHA
 from Crypto.Signature Import PKCS1_v1_5 AS Sig_pk
 from Crypto.PublicKey Import the RSA
 Import Base64 
# to be signed content 
name = " Musen " 
# Get the private key 
Key = Open ( ' private.pem ' , ' R & lt ' ) .read () 
rsakey = RSA.importKey (Key)
 # according to sha signed content processing algorithm (hash algorithm here is not necessarily sha, look at the development of) 
the Data = SHA.new (name.encode ())
 # private key for signing 
sig_pk =Sig_pk.new (rsakey) 
Sign = sig_pk.sign (Data)
 # contents of the signature, is converted to base64 encoded 
Result = base64.b64encode (Sign)
 # signature data is converted into a string 
Data = result.decode ()
 Print (Data )

 

2, public inspection sign
from Crypto.Hash Import the SHA
 from Crypto.Signature Import PKCS1_v1_5 AS Sig_pk
 from Crypto.PublicKey Import the RSA
 Import Base64 
# previous signed content 
name = " Musen " # signature data 
Data = " X3Gg PGCyZFUrG + + + wd7UDh4X8ra 6jDeQt6ajMA0EjwoDwxlddLzYoS4dtjQ2q5WCcRhxcp8fjEyoPXBmJE9rMKDjEIeE / VO0sskbJiO65fU8hgcqdWdgbVqRryhOw KIH + + n9JlOELcxLRdLo3vx6dw I6RIeNRYnOB8GkGD8Qca + = " # Base64 decoding 
Data = base64.b64decode (Data)
 # obtains the public key


= Open Key ( ' public.pem ' ) .read () 
rsakey = RSA.importKey (Key)
 # The content hash signature before processing 
sha_name = SHA.new (name.encode ())
 # verify the signature 
Signer = Sig_pk. new new (rsakey) 
Result = signer.verify (sha_name, Data)
 # authentication not by returning through the return True False 
Print (Result)

 

Guess you like

Origin www.cnblogs.com/zhaoyingjie/p/12017275.html
Recommended