What is the Crypto algorithm library? Detailed explanation of Crypto algorithm library

不言
Release: 2018-11-15 13:40:43
forward
12511 people have browsed it

The content of this article is about what is the Crypto algorithm library? The detailed explanation of the Crypto algorithm library has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Installation and use

The Crypto algorithm library was originally called pycrypto in python. The author was a bit lazy and did not update it for several years. Later, a big guy wrote an alternative library pycryptodome. This library currently only supports python3, and the installation is very simple, just pip install pycryptodome! For detailed usage, please see the official documentation

Common symmetric passwords are under the Crypto.Cipher library, mainly including: DES 3DES AES RC4 Salsa20
Asymmetric passwords are under the Crypto.PublicKey library, mainly including: RSA ECC DSA
Hash passwords are under the Crypto.Hash library. Commonly used ones are: MD5 SHA-1 SHA-128 SHA-256
Random numbers are under the Crypto.Random library.
Practical gadgets are under the Crypto.Util library. Next
Digital signature is under the Crypto.Signature library

Symmetric password AES

Note: There is an obvious difference between python3 and python2 in terms of strings - There are bytes in python3 String b'byte', there is no byte in python2. Since this library is under python3, encryption and decryption use bytes!

Using this library to encrypt and decrypt is very simple, remember these four steps:

  • Import the required library

from Crypto.Cipher import AES
Copy after login
  • Initialize key

key = b'this_is_a_key'
Copy after login
  • Instantiate encryption and decryption object

aes = AES.new(key,AES.MODE_ECB)
Copy after login
  • Use instance encryption and decryption

text_enc = aes.encrypt(b'helloworld')
Copy after login
from Crypto.Cipher import AES
import base64

key = bytes('this_is_a_key'.ljust(16,' '),encoding='utf8')
aes = AES.new(key,AES.MODE_ECB)

# encrypt
plain_text = bytes('this_is_a_plain'.ljust(16,' '),encoding='utf8')
text_enc = aes.encrypt(plain_text)
text_enc_b64 = base64.b64encode(text_enc)
print(text_enc_b64.decode(encoding='utf8'))

# decrypt
msg_enc = base64.b64decode(text_enc_b64)
msg = aes.decrypt(msg_enc)
print(msg.decode(encoding='utf8'))
Copy after login

Note: The key and plaintext need to be filled to the specified number of digits. You can use ljust or zfill to fill, or you can use pad( in Util ) function fill!

Symmetric password DES

from Crypto.Cipher import DES
import base64

key = bytes('test_key'.ljust(8,' '),encoding='utf8')
des = DES.new(key,DES.MODE_ECB)

# encrypt
plain_text = bytes('this_is_a_plain'.ljust(16,' '),encoding='utf8')
text_enc = des.encrypt(plain_text)
text_enc_b64 = base64.b64encode(text_enc)
print(text_enc_b64.decode(encoding='utf8'))

# decrypt
msg_enc = base64.b64decode(text_enc_b64)
msg = des.decrypt(msg_enc)
print(msg.decode(encoding='utf8'))
Copy after login

Asymmetric password RSA

The RSA of this library is mainly used togeneratepublic key files/private key files orReadPublic key file/private key file
Generate public/private key file:

from Crypto.PublicKey import RSA

rsa = RSA.generate(2048) # 返回的是密钥对象

public_pem = rsa.publickey().exportKey('PEM') # 生成公钥字节流
private_pem = rsa.exportKey('PEM') # 生成私钥字节流

f = open('public.pem','wb')
f.write(public_pem) # 将字节流写入文件
f.close()
f = open('private.pem','wb')
f.write(private_pem) # 将字节流写入文件
f.close()
#
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArreg3IX19DbszqSdBKhR
9cm495XAk9PBQJwHiwjKv6S1Tk5h7xL9/fPZIITy1M1k8LwuoSJPac/zcK6rYgMb
DT9tmVLbi6CdWNl5agvUE2WgsB/eifEcfnZ9KiT9xTrpmj5BJql9H+znseA1AzlP
iTukrH1frD3SzZIVnq/pBly3QbsT13UdUhbmIgeqTo8wL9V0Sj+sMFOIZY+xHscK
IeDOv4/JIxw0q2TMTsE3HRgAX9CXvk6u9zJCH3EEzl0w9EQr8TT7ql3GJg2hJ9SD
biebjImLuUii7Nv20qLOpIJ8qR6O531kmQ1gykiSfqj6AHqxkufxTHklCsHj9B8F
8QIDAQAB
-----END PUBLIC KEY-----

-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEArreg3IX19DbszqSdBKhR9cm495XAk9PBQJwHiwjKv6S1Tk5h
7xL9/fPZIITy1M1k8LwuoSJPac/zcK6rYgMbDT9tmVLbi6CdWNl5agvUE2WgsB/e
ifEcfnZ9KiT9xTrpmj5BJql9H+znseA1AzlPiTukrH1frD3SzZIVnq/pBly3QbsT
13UdUhbmIgeqTo8wL9V0Sj+sMFOIZY+xHscKIeDOv4/JIxw0q2TMTsE3HRgAX9CX
vk6u9zJCH3EEzl0w9EQr8TT7ql3GJg2hJ9SDbiebjImLuUii7Nv20qLOpIJ8qR6O
531kmQ1gykiSfqj6AHqxkufxTHklCsHj9B8F8QIDAQABAoI...
-----END RSA PRIVATE KEY-----
Copy after login

Read public/private key file encryption and decryption:

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64

def rsa_encrypt(plain):
    with open('public.pem','rb') as f:
        data = f.read()
        key = RSA.importKey(data)
        rsa = PKCS1_v1_5.new(key)
        cipher = rsa.encrypt(plain)
        return base64.b64encode(cipher)

def rsa_decrypt(cipher):
    with open('private.pem','rb') as f:
        data = f.read()
        key = RSA.importKey(data)
        rsa = PKCS1_v1_5.new(key)
        plain = rsa.decrypt(base64.b64decode(cipher),'ERROR') # 'ERROR'必需
        return plain

if __name__ == '__main__':
    plain_text = b'This_is_a_test_string!'
    cipher = rsa_encrypt(plain_text)
    print(cipher)
    plain = rsa_decrypt(cipher)
    print(plain)
Copy after login

Note: RSA has two filling methods, one is PKCS1_v1_5, the other is PKCS1_OAEP

Hash algorithm

is similar to the hashlib library. First instantiate a Hash algorithm, and then use update( ) just call it!

Specific example:

from Crypto.Hash import SHA1,MD5

sha1 = SHA1.new()
sha1.update(b'sha1_test')
print(sha1.digest()) # 返回字节串
print(sha1.hexdigest()) # 返回16进制字符串
md5 = MD5.new()
md5.update(b'md5_test')
print(md5.hexdigest())
Copy after login

Digital signature

The sender uses the private key to sign, and the verifier uses the public key to verify

from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA

# 签名
message = 'To be signed'
key = RSA.import_key(open('private_key.der').read())
h = SHA256.new(message)
signature = pkcs1_15.new(key).sign(h)

# 验证
key = RSA.import_key(open('public_key.der').read())
h = SHA.new(message)
try:
    pkcs1_15.new(key).verify(h, signature):
    print "The signature is valid."
    except (ValueError, TypeError):
        print "The signature is not valid."
Copy after login

Random number

Similar to the random library. The first function is very commonly used

import Crypto.Random
import Crypto.Random.random

print(Crypto.Random.get_random_bytes(4)) # 得到n字节的随机字节串
print(Crypto.Random.random.randrange(1,10,1)) # x到y之间的整数,可以给定step
print(Crypto.Random.random.randint(1,10)) # x到y之间的整数
print(Crypto.Random.random.getrandbits(16)) # 返回一个最大为N bit的随机整数
Copy after login

Other functions

Thepad()function in Util is commonly used to fill in the key

from Crypto.Util.number import *
from Crypto.Util.Padding import *

# 按照规定的几种类型 pad,自定义 pad可以用 ljust()或者 zfill()
str1 = b'helloworld'
pad_str1 = pad(str1,16,'pkcs7') # 填充类型默认为'pkcs7',还有'iso7816'和'x923'
print(unpad(pad_str1,16))
# number
print(GCD(11,143)) # 最大公约数
print(bytes_to_long(b'hello')) # 字节转整数
print(long_to_bytes(0x41424344)) # 整数转字节
print(getPrime(16)) # 返回一个最大为 N bit 的随机素数
print(getStrongPrime(512)) # 返回强素数
print(inverse(10,5)) # 求逆元
print(isPrime(1227)) # 判断是不是素数
Copy after login


The above is the detailed content of What is the Crypto algorithm library? Detailed explanation of Crypto algorithm library. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template