# ccav_app/ccav_utils.py
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import padding as sym_padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import base64
import os
def pad(data):
padder = padding.PKCS7(128).padder()
padded_data = padder.update(data) + padder.finalize()
return padded_data
def unpad(data):
unpadder = padding.PKCS7(128).unpadder()
unpadded_data = unpadder.update(data) + unpadder.finalize()
return unpadded_data
def derive_key(secret_key):
salt = os.urandom(16) # Generate a random salt (16 bytes)
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
iterations=100000,
salt=salt,
length=32, # Use 32 bytes for a 256-bit key
backend=default_backend()
)
key = base64.urlsafe_b64encode(kdf.derive(secret_key.encode()))
return key
def encrypt(plain_text, secret_key):
key = derive_key(secret_key)
iv = os.urandom(16)
cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
encryptor = cipher.encryptor()
encrypted_text = encryptor.update(plain_text.encode()) + encryptor.finalize()
return base64.b64encode(iv + encrypted_text).decode()
def decrypt(cipher_text, secret_key):
key = derive_key(secret_key)
data = base64.b64decode(cipher_text.encode())
iv = data[:16]
cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
decryptor = cipher.decryptor()
decrypted_text = decryptor.update(data[16:]) + decryptor.finalize()
return unpad(decrypted_text).decode()
这是我的ccavutil.py文件,我通过加密和解密获取数据和密钥
但出错
ValueError at /cc/
Invalid key size (352) for AES.
请求方法:POSTRequest URL:http://127.0.0.1:8000/cc/Django版本:4.2.1异常类型:ValueErrorException值:AES的密钥大小无效(352)。
我想在我的网站集成ccavenue支付网关,但得到错误
1条答案
按热度按时间anauzrmj1#
可能是secret key或derive_key函数中的问题