温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Linux下Python加密解密技术

发布时间:2024-09-11 21:54:58 来源:亿速云 阅读:78 作者:小樊 栏目:编程语言

在 Linux 下,Python 提供了多种加密和解密的方法

  1. 对称加密:

对称加密是指加密和解密使用相同密钥的加密算法。常见的对称加密算法有 AES、DES 和 3DES 等。

以下是一个使用 AES 加密和解密的 Python 示例:

from Crypto.Cipher import AES
import base64

# 加密函数
def encrypt(plain_text, key):
    cipher = AES.new(key, AES.MODE_ECB)
    encrypted_data = cipher.encrypt(plain_text)
    return base64.b64encode(encrypted_data).decode('utf-8')

# 解密函数
def decrypt(encrypted_data, key):
    encrypted_data = base64.b64decode(encrypted_data)
    cipher = AES.new(key, AES.MODE_ECB)
    return cipher.decrypt(encrypted_data).decode('utf-8')

# 示例
key = b'0123456789abcdef'
plain_text = "Hello, World!"
encrypted_data = encrypt(plain_text.encode('utf-8'), key)
print("Encrypted data:", encrypted_data)

decrypted_data = decrypt(encrypted_data, key)
print("Decrypted data:", decrypted_data)
  1. 非对称加密:

非对称加密是指加密和解密使用不同密钥的加密算法。常见的非对称加密算法有 RSA 和 ECC 等。

以下是一个使用 RSA 加密和解密的 Python 示例:

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

# 生成密钥对
def generate_key_pair():
    key = RSA.generate(2048)
    private_key = key.export_key()
    public_key = key.publickey().export_key()
    return private_key, public_key

# 加密函数
def encrypt(plain_text, public_key):
    rsa_public_key = RSA.import_key(public_key)
    rsa_public_key = PKCS1_OAEP.new(rsa_public_key)
    encrypted_data = rsa_public_key.encrypt(plain_text.encode('utf-8'))
    return base64.b64encode(encrypted_data).decode('utf-8')

# 解密函数
def decrypt(encrypted_data, private_key):
    rsa_private_key = RSA.import_key(private_key)
    rsa_private_key = PKCS1_OAEP.new(rsa_private_key)
    encrypted_data = base64.b64decode(encrypted_data)
    return rsa_private_key.decrypt(encrypted_data).decode('utf-8')

# 示例
private_key, public_key = generate_key_pair()
plain_text = "Hello, World!"
encrypted_data = encrypt(plain_text, public_key)
print("Encrypted data:", encrypted_data)

decrypted_data = decrypt(encrypted_data, private_key)
print("Decrypted data:", decrypted_data)
  1. 哈希和消息认证码:

哈希是将任意长度的输入数据转换为固定长度的输出数据的过程。常见的哈希算法有 MD5、SHA-1、SHA-256 等。

以下是一个使用 SHA-256 哈希的 Python 示例:

import hashlib

def sha256_hash(data):
    return hashlib.sha256(data.encode('utf-8')).hexdigest()

# 示例
data = "Hello, World!"
hash_value = sha256_hash(data)
print("Hash value:", hash_value)

消息认证码(MAC)是一种确保数据完整性和验证身份的技术。常见的 MAC 算法有 HMAC 等。

以下是一个使用 HMAC-SHA256 的 Python 示例:

import hmac
import hashlib

def hmac_sha256(data, key):
    return hmac.new(key.encode('utf-8'), data.encode('utf-8'), hashlib.sha256).hexdigest()

# 示例
data = "Hello, World!"
key = "secret_key"
mac_value = hmac_sha256(data, key)
print("MAC value:", mac_value)

这些示例仅用于演示目的,实际应用中需要根据具体需求选择合适的加密算法和密钥管理策略。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI