如何使用Python进行字符串的加密和解密
发布时间:2023-12-18 12:48:39
Python中可以使用多种方法进行字符串的加密和解密,常见的方法包括使用哈希函数、对称加密和非对称加密。
1. 哈希函数
哈希函数可以将任意长度的输入通过散列运算,转化为固定长度的输出,通常用于验证数据的完整性。Python中常用的哈希函数有MD5和SHA1。
使用MD5进行加密和解密的示例代码如下:
import hashlib
def encrypt_md5(text):
md5 = hashlib.md5()
md5.update(text.encode('utf-8'))
return md5.hexdigest()
text = 'Hello, World!'
encrypted_text = encrypt_md5(text)
print("加密后的字符串:", encrypted_text)
使用SHA1进行加密和解密的示例代码如下:
import hashlib
def encrypt_sha1(text):
sha1 = hashlib.sha1()
sha1.update(text.encode('utf-8'))
return sha1.hexdigest()
text = 'Hello, World!'
encrypted_text = encrypt_sha1(text)
print("加密后的字符串:", encrypted_text)
2. 对称加密
对称加密是指加密和解密使用同样的密钥的加密方法。Python中常用的对称加密算法有AES和DES。
使用AES进行加密和解密的示例代码如下:
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64
def encrypt_aes(text, key):
cipher = AES.new(key, AES.MODE_ECB)
encrypted_text = cipher.encrypt(pad(text.encode('utf-8'), AES.block_size))
return base64.b64encode(encrypted_text).decode('utf-8')
def decrypt_aes(encrypted_text, key):
cipher = AES.new(key, AES.MODE_ECB)
decrypted_text = cipher.decrypt(base64.b64decode(encrypted_text))
return unpad(decrypted_text, AES.block_size).decode('utf-8')
text = 'Hello, World!'
key = '0123456789abcdef'
encrypted_text = encrypt_aes(text, key)
print("加密后的字符串:", encrypted_text)
decrypted_text = decrypt_aes(encrypted_text, key)
print("解密后的字符串:", decrypted_text)
3. 非对称加密
非对称加密是指加密和解密使用不同的密钥的加密方法。Python中常用的非对称加密算法有RSA和ECC。
使用RSA进行加密和解密的示例代码如下:
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64
def generate_rsa_key():
key = RSA.generate(2048)
private_key = key.exportKey()
public_key = key.publickey().exportKey()
return private_key, public_key
def encrypt_rsa(text, public_key):
key = RSA.importKey(public_key)
cipher = PKCS1_v1_5.new(key)
encrypted_text = cipher.encrypt(text.encode('utf-8'))
return base64.b64encode(encrypted_text).decode('utf-8')
def decrypt_rsa(encrypted_text, private_key):
key = RSA.importKey(private_key)
cipher = PKCS1_v1_5.new(key)
decrypted_text = cipher.decrypt(base64.b64decode(encrypted_text), None)
return decrypted_text.decode('utf-8')
text = 'Hello, World!'
private_key, public_key = generate_rsa_key()
print("私钥:", private_key)
print("公钥:", public_key)
encrypted_text = encrypt_rsa(text, public_key)
print("加密后的字符串:", encrypted_text)
decrypted_text = decrypt_rsa(encrypted_text, private_key)
print("解密后的字符串:", decrypted_text)
以上是Python中常见的字符串加密和解密方法的示例代码,根据具体需求选择不同的方法,并根据需要调整密钥长度、填充方式等参数。
