Table of Contents
Installation and use
Symmetric password AES
Symmetric password DES
Asymmetric password RSA
Hash algorithm
Digital signature
Random number
Other functions
Home Backend Development Python Tutorial What is the Crypto algorithm library? Detailed explanation of Crypto algorithm library

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

Nov 15, 2018 pm 01:40 PM
Crypto python Cryptography

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles