python加密

常用加密

# -*- coding:utf-8 -*-
import rsa
from binascii import b2a_hex, a2b_hex

class rsacrypt():
    def __init__(self, pubkey, prikey):
        self.pubkey = pubkey
        self.prikey = prikey

    def encrypt(self, text):
        self.ciphertext = rsa.encrypt(text.encode(), self.pubkey)
        return b2a_hex(self.ciphertext)

    def decrypt(self, text):
        decrypt_text = rsa.decrypt(a2b_hex(text), prikey)
        return decrypt_text


if __name__ == '__main__':
    pubkey, prikey = rsa.newkeys(256)   #生成公钥 和 私钥
    print(pubkey)
    print('111111111111111')
    print(prikey)
    rs_obj = rsacrypt(pubkey,prikey)
    text='hello'
    ency_text = rs_obj.encrypt(text)
    print(ency_text)
    print(rs_obj.decrypt(ency_text))

AES加密

# -*- coding:utf-8 -*-
from Crypto.Cipher import AES
from binascii import b2a_hex,a2b_hex
class MyCrypt():
    def __init__(self, key):
        self.key = key
        self.mode = AES.MODE_CBC
    def myencrypt(self, text):
        length = 16
        count = len(text)
        print count
        if count < length:
            add = length - count
            text= text + ('\0' * add)
        elif count > length:
            add = (length -(count % length))
            text= text + ('\0' * add)
        # print len(text)
        cryptor = AES.new(self.key, self.mode, b'0000000000000000')
        self.ciphertext = cryptor.encrypt(text)
        return b2a_hex(self.ciphertext)

    def mydecrypt(self, text):
        cryptor = AES.new(self.key, self.mode, b'0000000000000000')
        plain_text = cryptor.decrypt(a2b_hex(text))
        return plain_text.rstrip('\0')
if __name__ == '__main__':
    mycrypt = MyCrypt('abcdefghjklmnopq')
    e = mycrypt.myencrypt('hello,world!')
    d = mycrypt.mydecrypt(e)
    print e
    print d

AES加密(有key和vi)

# -*- coding:utf-8 -*-
from Crypto.Cipher import AES  
from ba import b2a_hex, a2b_hex  
import sys,time


class prpcrypt():  
    def __init__(self):  
        self.key = 'xxx'  
        self.iv  = 'xxx'  
        self.mode = AES.MODE_CBC  
        self.BS = AES.block_size  
        self.pad = lambda s: s + (self.BS - len(s) % self.BS) * chr(self.BS - len(s) % self.BS)   
        self.unpad = lambda s : s[0:-ord(s[-1])]  
       
    def encrypt(self,text):  
        text = self.pad(text)  
        cryptor = AES.new(self.key,self.mode,self.iv)  
        #目前AES-128 足够目前使用  
        ciphertext = cryptor.encrypt(text)  
        #把加密后的字符串转化为16进制字符串  
        return b2a_hex(ciphertext)  
       
    #解密后,去掉补足的空格用strip() 去掉  
    def decrypt(self,text):  
        cryptor = AES.new(self.key,self.mode, self.iv)  
        plain_text  = cryptor.decrypt(a2b_hex(text))  
        return self.unpad(plain_text.rstrip('\0'))  
  
   
if __name__ == '__main__':
    

    pc = prpcrypt() #初始化密钥 和 iv 
   
    text='111111111'   
    e = pc.encrypt(text) #加密  
    d = pc.decrypt(e) #解密  
    print "加密:",e  
    print "解密:",d  
    print "长度:",len(d)  

你可能感兴趣的:(python加密)