解密加密

一、RSA

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import rsa
import base64
 
 
# ######### 1. 生成公钥私钥 #########
pub_key_obj, priv_key_obj = rsa.newkeys(256)
 
pub_key_str = pub_key_obj.save_pkcs1()
pub_key_code = base64.standard_b64encode(pub_key_str)
 
priv_key_str = priv_key_obj.save_pkcs1()
priv_key_code = base64.standard_b64encode(priv_key_str)
 
print(pub_key_code)
print(priv_key_code)
 
# ######### 2. 加密 #########
def encrypt(value):
    key_str = base64.standard_b64decode(pub_key_code)
    pk = rsa.PublicKey.load_pkcs1(key_str)
    val = rsa.encrypt(value.encode('utf-8'), pk)
    return val
 
 
# ######### 3. 解密 #########
def decrypt(value):
    key_str = base64.standard_b64decode(priv_key_code)
    pk = rsa.PrivateKey.load_pkcs1(key_str)
    val = rsa.decrypt(value, pk)
    return val
 
 
# ######### 基本使用 #########
if __name__ == '__main__':
    v = 'wupeiqi'
    v1 = encrypt(v)
    print(v1)
    v2 = decrypt(v1)
    print(v2)

二、AES

安装:

pip3 install wheel
pip3 install pycrypto

或者

#手动选择安装包
https://github.com/sfbahr/PyCrypto-Wheels
#安装
pip3 install wheel
pip3 install pycrypto-2.6.1-cp35-none-win32.whl

 

#示例

from Crypto.Cipher import AES


def encrypt(message):
    key = b'dfdsdfsasdfdsdfs'
    cipher = AES.new(key, AES.MODE_CBC, key)
    bmessage = bytearray(message, encoding='utf-8')
    v1 = len(bytes(message, encoding='utf-8'))
    v2 = v1 % 16
    v3 = 16 - v2
    for i in range(v3):
        bmessage.append(32)
    data = bmessage.decode('utf-8')
    msg = cipher.encrypt(data)
    return msg


def decrypt(message):
    key = b'dfdsdfsasdfdsdfs'
    cipher = AES.new(key, AES.MODE_CBC, key)
    result = cipher.decrypt(message)
    return result.decode('utf-8').strip()

v = '我是你爸'
print(len(v))
data = encrypt(v)
print(data)
result = decrypt(data)
print(len(result),result)

 

posted @ 2017-10-02 10:48  luchuangao  阅读(154)  评论(0编辑  收藏  举报