python crypto rsa 加密運用


首先安裝必須包,pycrypto..

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP, PKCS1_v1_5 #生成對象

然后定義一個生成公私鑰的函數:

 def getRSAKeys(self,keyLength):
        '''keylength 指定長度 如:1024,2048'''
        private = RSA.generate(keyLength)
        public  = private.publickey()
        privateKey = private.exportKey()
        publicKey = public.exportKey()
        return privateKey, publicKey #生成一對公私鑰匙

定義加密函數:

def rsaPubEncrypt(pubKey, data, length=200): 
    '''按照生成公私鑰匙長度定義length,1024 length = 100,2048 length = 200'''
    publicKey = RSA.importKey(pubKey)
    cipher = PKCS1_v1_5.new(publicKey)  #
    data = json.dumps(data) # 看情況 #encryptedData = cipher.encrypt(data)  一般加密
    encryptedData = []  # 長字符串加密
    for i in range(0, len(data), length):
        encryptedData.append(cipher.encrypt(data[i:i + length]))
    print encryptedData
    return "".join(encryptedData)
    # return encryptedData    一般加密返回

 

定義解密函數:

def rsaPrivateDecrypt(privKey, data,length=256):  # 解密
    '''解密length 根據加密length 100 對應128 200 對應 256'''
    privateKey = RSA.importKey(privKey)
    cipher = PKCS1_v1_5.new(privateKey)
    decryptedData = []
    for i in range(0, len(data), length):
        json_data = data[i:i + length]
        len_da = len(json_data)
        json_data = cipher.decrypt(json_data,'xyz')
        decryptedData.append(json_data)
    data = ''.join(decryptedData)
    return data
#對於長字符串加解密
def
rsa_long_encrypt(pub_key_str, msg, length=100): """ 單次加密串的長度最大為 (key_size/8)-11 1024bit的證書用100, 2048bit的證書用 200 """ pubobj = rsa.importKey(pub_key_str) pubobj = PKCS1_v1_5.new(pubobj) res = [] for i in range(0, len(msg), length): res.append(pubobj.encrypt(msg[i:i+length])) return "".join(res) def rsa_long_decrypt(priv_key_str, msg, length=128): """ 1024bit的證書用128,2048bit證書用256位 """ privobj = rsa.importKey(priv_key_str) privobj = PKCS1_v1_5.new(privobj) res = [] for i in range(0, len(msg), length): res.append(privobj.decrypt(msg[i:i+length], 'xyz')) return "".join(res)

 

 

 

 

以上就是對crypto的簡單運用,,,,,,


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM