python Crypto库

学习python的Crypto库

安装

windows10安装

开始想在python3.6安装,直接pip install pycrypto,发现报错,后来在网上找了一种简单的在python2安装这个库的:

http://www.voidspace.org.uk/python/pycrypto-2.6.1/下载对应python版本的文件,由于用的是python2.7,则这里下载的是pycrypto-2.6.1.win-amd64-py2.7.exe;之后直接移动到python2.7文件夹下,双击exe安装即可

安装好后可以测试导入这个库,不报错则说明安装成功了:

Ubuntu安装

在Ubuntu直接安装:

sudo apt-get install python3-crypto

使用

使用help()命令查看使用方法

1.Crypto.Cipher

Secret-key (AES, DES, ARC4) and public-key encryption (RSA PKCS#1) algorithms

AES

>>> from Crypto.Cipher import AES
>>> secret = "12345678912345678912345678912345" # AES key must be either 16, 24, or 32 bytes long
>>> cipher = AES.new(secret)
>>> cipher
<Crypto.Cipher.AES.AESCipher object at 0x7f19e939a630>
>>> s = cipher.encrypt("1234567891234567")  
>>> s
b'\xbbvQ\xe4\xc1\xe1\x98\xbb[v\x87\x18k\x1f\xb9\xe9'
>>> cipher.decrypt(s)
b'1234567891234567'

DES

from Crypto.Cipher import DES
>>> secret = "11111111" # Key must be 8 bytes long
>>> cipher = DES.new(secret)
>>> s = cipher.encrypt("1234567891234567")
>>> s
b'\x85\x8b\x17m\xa8\xb1%\x03\xc2\xa4J\xf5Dn\xf2B'
>>> cipher.decrypt(s)
b'1234567891234567'

2.Crypto.Hash

Hashing algorithms (MD5, SHA, HMAC)

MD5

>>> from Crypto.Hash import MD5
>>> h = MD5.new()
>>> h.update(b'Hello')
>>> s = h.hexdigest()
'8b1a9953c4611296a827abf8c47804d7'

3.Crypto.Protocol

Cryptographic protocols (Chaffing, all-or-nothing transform, key derivation functions). This package does not contain any network protocols.

4.Crypto.PublicKey

Public-key encryption and signature algorithms (RSA, DSA)

从公钥文件中提取n和e:

from Crypto.PublicKey import RSA

public_key = RSA.importKey(open('pubkey.pem').read())
n = public_key.n
e = public_key.e

生成私钥文件:

keypair = RSA.generate(1024)
keypair.p = p
keypair.q = q
keypair.e = e
keypair.n = n
keypair.d = d

private_key = keypair.exportKey().decode('utf-8')
f = open('private.pem', 'w')
f.write(private_key)

5.Crypto.Signature

Public-key signature algorithms (RSA PKCS#1)

6.Crypto.Util

Various useful modules and functions (long-to-string conversion, random number generation, number theoretic functions)

(1)Crypto.Util.number

Number-theoretic functions (primality testing, etc.)

GCD(x, y)

GCD(x:long, y:long): long

Return the GCD of x and y.

bytes_to_long(s)

bytes_to_long(string) : long

Convert a byte string to a long integer.

This is (essentially) the inverse of long_to_bytes().

getPrime(N, randfunc=None)

getPrime(N:int, randfunc:callable):long

Return a random N-bit prime number.

If randfunc is omitted, then Random.new().read is used.

inverse(u, v)

inverse(u:long, v:long):long

Return the inverse of u mod v.

isPrime(N:long):bool

Return true if N is prime.

(2)Crypto.Util.strxor

strxor(…)

strxor(a:str, b:str) -> str

Return a XOR b. Both a and b must have the same length.

strxor_c(…)

strxor_c(s:str, c:int) -> str

Return s XOR chr(c). c must be in range(256).