星期一, 7月 03, 2017

pycryptco in python3

最近需要做 public/private key 的加解密,所以找到 pycryptco 。
使用的例子可以參考 Python and cryptography with pycrypto
但使用時,卻遇到 unsupported operand type(s) for pow() 的問題,經過一番查找,才找到問題所在,詳情可以看這篇:Error with encrypt message with RSA python - Stack Overflow
主要是因為 Python 3 的字串預設是 unicode 字串,而 encrypt 沒辦法處理,所以得先 encode 為 utf-8 字串才行:
# -*- coding: utf-8 -*-
import os
import base64
from Crypto.PublicKey import RSA
from Crypto import Random
from Crypto.Cipher import PKCS1_OAEP, AES
from pprint import pprint


# Generate key
if os.path.exists('mykey.pem'):
    with open('mykey.pem', 'rb') as fin:
        key = RSA.importKey(fin.read())
else:
    random_generator = Random.new().read
    key = RSA.generate(1024, random_generator)
    with open('mykey.pem', 'wb') as fout:
        fout.write(key.exportKey('PEM'))

# Display key information
print("key = {}".format(key))
print("can_encrypt = {}".format(key.can_encrypt()))
print("can_sign = {}".format(key.can_sign()))
print("can_private = {}".format(key.has_private()))

# show public key
pprint(dir(key.publickey()))

# Encrypt
enc_data = key.publickey().encrypt("abcdef".encode('utf-8'), 32)
pprint(enc_data)

# Decrypt
print(key.decrypt(enc_data))

沒有留言: