|
| 1 | +# Copyright (c) Alibaba, Inc. and its affiliates. |
| 2 | +import base64 |
| 3 | +import json |
| 4 | +from dataclasses import dataclass |
| 5 | +import os |
| 6 | +from typing import Optional |
| 7 | + |
| 8 | +import requests |
| 9 | +from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes |
| 10 | +from cryptography.hazmat.primitives import serialization, hashes |
| 11 | +from cryptography.hazmat.primitives.asymmetric import padding |
| 12 | +from cryptography.hazmat.backends import default_backend |
| 13 | + |
| 14 | +import dashscope |
| 15 | +from dashscope.common.constants import ENCRYPTION_AES_SECRET_KEY_BYTES, ENCRYPTION_AES_IV_LENGTH |
| 16 | +from dashscope.common.logging import logger |
| 17 | + |
| 18 | + |
| 19 | +class Encryption: |
| 20 | + def __init__(self): |
| 21 | + self.pub_key_id: str = '' |
| 22 | + self.pub_key_str: str = '' |
| 23 | + self.aes_key_bytes: bytes = b'' |
| 24 | + self.encrypted_aes_key_str: str = '' |
| 25 | + self.iv_bytes: bytes = b'' |
| 26 | + self.base64_iv_str: str = '' |
| 27 | + self.valid: bool = False |
| 28 | + |
| 29 | + def initialize(self): |
| 30 | + public_keys = self._get_public_keys() |
| 31 | + if not public_keys: |
| 32 | + return |
| 33 | + |
| 34 | + public_key_str = public_keys.get('public_key') |
| 35 | + public_key_id = public_keys.get('public_key_id') |
| 36 | + if not public_key_str or not public_key_id: |
| 37 | + logger.error("public keys data not valid") |
| 38 | + return |
| 39 | + |
| 40 | + aes_key_bytes = self._generate_aes_secret_key() |
| 41 | + iv_bytes = self._generate_iv() |
| 42 | + |
| 43 | + encrypted_aes_key_str = self._encrypt_aes_key_with_rsa(aes_key_bytes, public_key_str) |
| 44 | + base64_iv_str = base64.b64encode(iv_bytes).decode('utf-8') |
| 45 | + |
| 46 | + self.pub_key_id = public_key_id |
| 47 | + self.pub_key_str = public_key_str |
| 48 | + self.aes_key_bytes = aes_key_bytes |
| 49 | + self.encrypted_aes_key_str = encrypted_aes_key_str |
| 50 | + self.iv_bytes = iv_bytes |
| 51 | + self.base64_iv_str = base64_iv_str |
| 52 | + |
| 53 | + self.valid = True |
| 54 | + |
| 55 | + def encrypt(self, dict_plaintext): |
| 56 | + return self._encrypt_text_with_aes(json.dumps(dict_plaintext, ensure_ascii=False), |
| 57 | + self.aes_key_bytes, self.iv_bytes) |
| 58 | + |
| 59 | + def decrypt(self, base64_ciphertext): |
| 60 | + return self._decrypt_text_with_aes(base64_ciphertext, self.aes_key_bytes, self.iv_bytes) |
| 61 | + |
| 62 | + def is_valid(self): |
| 63 | + return self.valid |
| 64 | + |
| 65 | + def get_pub_key_id(self): |
| 66 | + return self.pub_key_id |
| 67 | + |
| 68 | + def get_encrypted_aes_key_str(self): |
| 69 | + return self.encrypted_aes_key_str |
| 70 | + |
| 71 | + def get_base64_iv_str(self): |
| 72 | + return self.base64_iv_str |
| 73 | + |
| 74 | + @staticmethod |
| 75 | + def _get_public_keys(): |
| 76 | + url = dashscope.base_http_api_url + '/public-keys/latest' |
| 77 | + headers = { |
| 78 | + "Authorization": f"Bearer {dashscope.api_key}" |
| 79 | + } |
| 80 | + |
| 81 | + response = requests.get(url, headers=headers) |
| 82 | + if response.status_code != 200: |
| 83 | + logger.error("exceptional public key response: %s" % response) |
| 84 | + return None |
| 85 | + |
| 86 | + json_resp = response.json() |
| 87 | + response_data = json_resp.get('data') |
| 88 | + |
| 89 | + if not response_data: |
| 90 | + logger.error("no valid data in public key response") |
| 91 | + return None |
| 92 | + |
| 93 | + return response_data |
| 94 | + |
| 95 | + @staticmethod |
| 96 | + def _generate_aes_secret_key(): |
| 97 | + return os.urandom(ENCRYPTION_AES_SECRET_KEY_BYTES) |
| 98 | + |
| 99 | + @staticmethod |
| 100 | + def _generate_iv(): |
| 101 | + return os.urandom(ENCRYPTION_AES_IV_LENGTH) |
| 102 | + |
| 103 | + @staticmethod |
| 104 | + def _encrypt_text_with_aes(plaintext, key, iv): |
| 105 | + """使用AES-GCM加密数据""" |
| 106 | + |
| 107 | + # 创建AES-GCM加密器 |
| 108 | + aes_gcm = Cipher( |
| 109 | + algorithms.AES(key), |
| 110 | + modes.GCM(iv, tag=None), |
| 111 | + backend=default_backend() |
| 112 | + ).encryptor() |
| 113 | + |
| 114 | + # 关联数据设为空(根据需求可调整) |
| 115 | + aes_gcm.authenticate_additional_data(b'') |
| 116 | + |
| 117 | + # 加密数据 |
| 118 | + ciphertext = aes_gcm.update(plaintext.encode('utf-8')) + aes_gcm.finalize() |
| 119 | + |
| 120 | + # 获取认证标签 |
| 121 | + tag = aes_gcm.tag |
| 122 | + |
| 123 | + # 组合密文和标签 |
| 124 | + encrypted_data = ciphertext + tag |
| 125 | + |
| 126 | + # 返回Base64编码结果 |
| 127 | + return base64.b64encode(encrypted_data).decode('utf-8') |
| 128 | + |
| 129 | + @staticmethod |
| 130 | + def _decrypt_text_with_aes(base64_ciphertext, aes_key, iv): |
| 131 | + """使用AES-GCM解密响应""" |
| 132 | + |
| 133 | + # 解码Base64数据 |
| 134 | + encrypted_data = base64.b64decode(base64_ciphertext) |
| 135 | + |
| 136 | + # 分离密文和标签(标签长度16字节) |
| 137 | + ciphertext = encrypted_data[:-16] |
| 138 | + tag = encrypted_data[-16:] |
| 139 | + |
| 140 | + # 创建AES-GCM解密器 |
| 141 | + aes_gcm = Cipher( |
| 142 | + algorithms.AES(aes_key), |
| 143 | + modes.GCM(iv, tag), |
| 144 | + backend=default_backend() |
| 145 | + ).decryptor() |
| 146 | + |
| 147 | + # 验证关联数据(与加密时一致) |
| 148 | + aes_gcm.authenticate_additional_data(b'') |
| 149 | + |
| 150 | + # 解密数据 |
| 151 | + decrypted_bytes = aes_gcm.update(ciphertext) + aes_gcm.finalize() |
| 152 | + |
| 153 | + # 明文 |
| 154 | + plaintext = decrypted_bytes.decode('utf-8') |
| 155 | + |
| 156 | + return json.loads(plaintext) |
| 157 | + |
| 158 | + @staticmethod |
| 159 | + def _encrypt_aes_key_with_rsa(aes_key, public_key_str): |
| 160 | + """使用RSA公钥加密AES密钥""" |
| 161 | + |
| 162 | + # 解码Base64格式的公钥 |
| 163 | + public_key_bytes = base64.b64decode(public_key_str) |
| 164 | + |
| 165 | + # 加载公钥 |
| 166 | + public_key = serialization.load_der_public_key( |
| 167 | + public_key_bytes, |
| 168 | + backend=default_backend() |
| 169 | + ) |
| 170 | + |
| 171 | + base64_aes_key = base64.b64encode(aes_key).decode('utf-8') |
| 172 | + |
| 173 | + # 使用RSA加密 |
| 174 | + encrypted_bytes = public_key.encrypt( |
| 175 | + base64_aes_key.encode('utf-8'), |
| 176 | + padding.PKCS1v15() |
| 177 | + ) |
| 178 | + |
| 179 | + return base64.b64encode(encrypted_bytes).decode('utf-8') |
0 commit comments