Skip to main content

Use encryption to access model inference features

If a request contains sensitive information or is sent over the public network, encrypt the input field in the request body. This prevents data from being intercepted or tampered with during transmission.

Encryption and decryption process

image
This process uses a hybrid encryption mechanism. Data is encrypted with the AES symmetric algorithm. The AES key is securely transmitted using RSA asymmetric encryption.
  1. Prepare the request data.
    • Generate an AES symmetric key. AES is an efficient symmetric encryption algorithm used to encrypt the content of the input field.
      Note:input is the core object in a request to a Large Language Model (LLM) application. It includes parameters such as the conversation messages (messages), and all examples in this topic pass the conversation content through messages.
    • Use the key to encrypt the input content.
    • Encrypt the AES key with an RSA public key. Use the hosted RSA public key from the Alibaba Cloud Model Studio platform to encrypt the AES key. This ensures the secure transmission of the AES key.
      Note: RSA is an asymmetric encryption algorithm that includes a public key and a private key. The public key is used to encrypt data, and the private key is used to decrypt data.
  2. Send the request. When you call the Alibaba Cloud Model Studio platform, pass the encrypted input content and the key information. The key information is encapsulated in the X-DashScope-EncryptionKey request header.
  3. Alibaba Cloud Model Studio processes the request.
    • The data is encrypted throughout the Alibaba Cloud Model Studio inference pipeline.
    • The Alibaba Cloud Model Studio platform decrypts the data during vector recall and model inference.
    • The generated answer is encrypted with the same AES key, and the encrypted inference result is returned.
  4. Process the response. The client receives the response, decrypts the inference result with the AES key, and obtains the plaintext answer.

Prerequisites

Activate the Alibaba Cloud Model Studio service and obtain an API key. For more information, see Obtain an API Key.
Important: Configure the API key as an environment variable to reduce the risk of leakage. For more information, see Set the API key as an environment variable. You can also configure the API key in your code, but this increases the risk of leakage.

DashScope SDK call (automatic encryption, out-of-the-box)

The DashScope SDK handles encryption and decryption. To make encrypted calls, simply enable the encryption feature. You do not need to write your own encryption and decryption code.

Constraints and limits

Procedure

  1. Install the latest version of the DashScope SDK.
  2. Enable the encryption feature.
    • Java SDK
    • Python SDK
    Set enableEncrypt to true to enable the encryption feature.
    GenerationParam param = GenerationParam.builder()
      // ...这里省略其他代码
      // 启用加密功能
      .enableEncrypt(true)
      .build();
    
  3. Call the model. Send the request in the same way as a normal call. The SDK automatically handles encryption and decryption.

Complete SDK code examples

Important: The sample code is for reference only. Do not use it directly in a production environment.
Note: For more information about request parameters, see Qwen API documentation.
  • Java SDK
  • Python SDK
Request example
import java.util.Arrays;
import java.lang.System;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
public class Main {
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("You are a helpful assistant.")
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("你是谁?")
                .build();
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // 此处以qwen-plus为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
                .model("qwen-plus")
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                // 启用加密功能
                .enableEncrypt(true)
                .build();
        return gen.call(param);
    }
    public static void main(String[] args) {
        try {
            GenerationResult result = callWithMessage();
            System.out.println(JsonUtils.toJson(result));
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            // 使用日志框架记录异常信息
            System.err.println("An error occurred while calling the generation service: " + e.getMessage());
        }
        System.exit(0);
    }
}
Response exampleThe DashScope SDK automatically decrypts the response. The returned content is plaintext and does not require manual decryption.
{
    "request_id": "902fee3b-f7f0-9a8c-96a1-6b4ea25af114",
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": "我是Qwen,由阿里云开发的超大规模语言模型。我的目标是帮助用户更高效地获取信息、解决各种问题并激发创造力。无论是回答问题、提供信息还是进行创意性的讨论,我都会尽力提供支持。有什么我可以帮到你的吗?"
                }
            }
        ]
    },
    "usage": {
        "input_tokens": 22,
        "output_tokens": 62,
        "total_tokens": 84
    }
}

HTTP calls (manual key management)

Note: This encrypted call method is a security feature provided by Alibaba Cloud Model Studio. This encryption process applies only to DashScope Endpoints. OpenAI-compatible Endpoints, such as the Chat Completions API and Responses API, do not support this encryption mechanism.

Differences from normal calls

Encrypted calls require three extra steps compared to normal calls. For more information, see Integration process.
  1. Add the X-DashScope-EncryptionKey request header. The value of the X-DashScope-EncryptionKey request header is a JSON string. The following table describes the parameters.
    • public_key_id: The public key ID.
    • encrypt_key: The AES key encrypted with an RSA public key.
    • iv: The initialization vector (IV).
    For more information about how to generate these parameters, see the Integration process section.
  2. Encrypt the content of the input request parameter. The following table shows the difference between the request data for a normal call and an encrypted call.
    {
        ...
        "input": {
            "messages": [
                {
                    "role": "system",
                    "content": "You are a helpful assistant."
                },
                {
                    "role": "user",
                    "content": "你是谁? "
                }
            ]
        }
        ...
    }
    
  3. Decrypt the response data.

Integration process

The integration process consists of three stages: first prepare the request data (generate the AES key, generate the IV, encrypt the input data, and encrypt the AES key), then build and send the encrypted request, and finally decrypt the response data.

1. Prepare the request data

  1. Generate an AES key
    • Algorithm: AES
    • Key specifications:
      • Length: 128 bits (16 bytes), 192 bits (24 bytes), or 256 bits (32 bytes)
        Note: Longer keys provide higher security but also increase computational overhead. A 256 bit key offers the highest security and is suitable for protecting highly sensitive data, such as core financial data.
      • Randomness: Generate the key using a cryptographically secure random source.
      • Uniqueness: The key must be unique for each request and must not be reused.
    • Example code:
private static SecretKey generateAesSecretKey() throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        SecureRandom secureRandom = new SecureRandom();
        keyGen.init(256, secureRandom);
        return keyGen.generateKey();
}
def generate_aes_secret_key():
    """生成256位AES密钥"""
    return os.urandom(32)  # 32字节 = 256位
  1. Generate an initialization vector (IV) Generate the random initialization vector (IV) required for GCM encryption: use a secure random number generator to create a 12-byte random byte sequence, which serves as the IV itself. Base64-encode the IV only for transmission in the request header. Example code:
private static final int GCM_IV_LENGTH = 12; // 12 字节 IV
private static byte[] generateIv() {
    byte[] iv = new byte[GCM_IV_LENGTH];
    SecureRandom secureRandom = new SecureRandom(); // 随机生成确保唯一性
    secureRandom.nextBytes(iv);
    return iv;
}
# 常量定义
GCM_IV_LENGTH = 12       # 12字节IV
def generate_iv():
    """生成12字节随机IV"""
    return os.urandom(GCM_IV_LENGTH)
  1. Encrypt the input data
    • Algorithm: AES-GCM (authentication tag length: 128 bits)
    • Parameters:
      • Key: The AES key generated in step 1.
      • IV: The initialization vector generated in step 2.
    • Processing flow:
      1. Serialize the input value into a JSON string: serialize the highlighted part of the following example (that is, {"messages":[......]}).
curl --location "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-g..." \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
    "model": "qwen-plus",
    "input":{
        "messages":[
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "user",
                "content": "你是谁? "
            }
        ]
    },
    "parameters": {
        "result_format": "message"
    }
}'
  1. Perform AES-GCM encryption on the serialized input.
  2. Convert the encryption result to a string. This string will be used as the value for the input field when you build and send the request.
  • Example code:
private static final int GCM_TAG_LENGTH = 128; // 128 位 Tag(16 字节)
private static String encryptInputWithAes(SecretKey aesSecretKey,byte[] iv, String input) throws Exception {
        byte[] content = input.getBytes(StandardCharsets.UTF_8);
        Cipher aesCipher = Cipher.getInstance("AES/GCM/NoPadding");
        GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);
        aesCipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aesSecretKey.getEncoded(), "AES"), gcmParameterSpec);
        byte[] encryptedBytes = aesCipher.doFinal(content);
        return Base64.encodeBase64String(encryptedBytes);
}
def encrypt_input_with_aes(aes_key, iv, plaintext):
    """使用AES-GCM加密数据"""
    # 创建AES-GCM加密器
    aesgcm = Cipher(
        algorithms.AES(aes_key),
        modes.GCM(iv, tag=None),
        backend=default_backend()
    ).encryptor()
    # 关联数据设为空(根据需求可调整)
    aesgcm.authenticate_additional_data(b'')
    # 加密数据
    ciphertext = aesgcm.update(plaintext.encode('utf-8')) + aesgcm.finalize()
    # 获取认证标签
    tag = aesgcm.tag
    # 组合密文和标签
    encrypted_data = ciphertext + tag
    # 返回Base64编码结果
    return base64.b64encode(encrypted_data).decode('utf-8')
  1. Encrypt the AES key with an RSA public key
    • Algorithm: RSA
    • Processing flow:
      1. Base64-encode the original AES key generated in step 1.
      2. Encrypt the encoded AES key using the RSA public key. For more information about how to obtain the public_key and public_key_id from Alibaba Cloud Model Studio, see Obtain an RSA public key.
        You do not need to fetch the RSA public key for every request. You can cache the public key on the client side to reduce the number of API calls in high queries-per-second (QPS) scenarios. A cache duration of 1 minute is recommended.The public key does not change under normal circumstances. It is rotated only in case of a security incident. Therefore, manage the public key cache using the following policy:
        • Normal scenario: Use the cached public key. After the cache expires, automatically fetch the latest public key.
        • Error scenario: If the error code BadRequest.IllegalInput is returned with the error message The input parameter can not be decoded., the public key is invalid. In this case, you must immediately fetch the latest public key to minimize service disruption.
        With this policy, even if an emergency public key rotation occurs, the service disruption is theoretically limited to a few minutes.
      3. Base64-encode the encryption result.
    • Example code:
private static String encryptAesKeyWithRsaPublicKey(SecretKey aesSecretKey, String publicKey) throws Exception {
        byte[] aesKeyBytes = aesSecretKey.getEncoded();
        String base64AesKey = Base64.encodeBase64String(aesKeyBytes);
        byte[] publicKeyBytes = Base64.decodeBase64(publicKey);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey pubKey = kf.generatePublic(spec);
        Cipher rsaCipher = Cipher.getInstance("RSA");
        rsaCipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] encryptedBytes = rsaCipher.doFinal(base64AesKey.getBytes());
        return Base64.encodeBase64String(encryptedBytes);
}
def encrypt_aes_key_with_rsa(aes_key, public_key_str):
    """使用RSA公钥加密AES密钥"""
    # 解码Base64格式的公钥
    public_key_bytes = base64.b64decode(public_key_str)
    # 加载公钥
    public_key = serialization.load_der_public_key(
        public_key_bytes,
        backend=default_backend()
    )
    # 先对AES密钥进行Base64编码
    base64_aes_key = base64.b64encode(aes_key).decode('utf-8')
    # 使用RSA加密
    encrypted_bytes = public_key.encrypt(
        base64_aes_key.encode('utf-8'),
        padding.PKCS1v15()
    )
    # 返回Base64编码的加密结果
    return base64.b64encode(encrypted_bytes).decode('utf-8')

2. Build and send the request

Add the X-DashScope-EncryptionKey request header and replace the original input value with the encrypted input. Then, send the request in the same way as a normal call. The following list describes the parameters for the X-DashScope-EncryptionKey request header. The values for these parameters are generated during the data preparation stage.
  • public_key_id: The public key ID.
  • encrypt_key: The AES key encrypted with an RSA public key.
  • iv: The initialization vector (IV).
The final HTTP request sent to the Large Language Model (LLM) has the following format:
curl --location "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--header "X-DashScope-EncryptionKey: {\"public_key_id\": \"17xxx0\", \"encrypt_key\": \"F3WT...sR9UGIw==\", \"iv\": \"oxxxlouK/\"}" \
--data '{
    "model": "qwen-plus",
    "input":"+J2aT8GNBUD9rFBsBL0dRP60fZpmDuUAAoHQPXoGUL7/xskvxY9BMyJWm2rtNK2siPHkW12p9wgQEaEZcdM5xp3zCKlUvzCw",
    "parameters": {
        "result_format": "message"
    }
}'
Example code:
java
private static String sendEncryptedRequest(String apiKey, String publicKeyId, String encryptedAesKey, byte[] iv, String encryptedInput) throws Exception {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder().build();
        JSONObject requestBodyJson = new JSONObject();
        requestBodyJson.put("model", "qwen-plus");
        requestBodyJson.put("input", encryptedInput);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestBodyJson.toJSONString());
        JSONObject headerJson = new JSONObject();
        headerJson.put("Content-Type", "application/json");
        headerJson.put("Accept", "application/json");
        headerJson.put("Authorization","Bearer " + apiKey);
        String encryptionHeader = String.format("{\"public_key_id\": \"%s\", \"encrypt_key\": \"%s\", \"iv\": \"%s\"}", publicKeyId, encryptedAesKey, Base64.encodeBase64String(iv));
        headerJson.put("X-DashScope-EncryptionKey", encryptionHeader);
        Headers headers = Headers.of(JSONObject.parseObject(headerJson.toString(), Map.class));
        String url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .headers(headers)
                .build();
        return okHttpClient.newCall(request).execute().body().string();
}

3. Decrypt the response data

  • Algorithm: AES-GCM
  • Parameters:
    • Key: The AES key generated in step 1 of the data preparation stage.
    • IV: The initialization vector used in step 2 of the data preparation stage.
  • Processing flow:
    1. Use AES-GCM to decrypt the content of the output field.
    2. Return the plaintext result.
  • Example code:
private static String decryptResponseWithAes(SecretKey aesSecretKey, byte[] iv, String response) throws Exception {
        JSONObject responseJson = JSONObject.parseObject(response, JSONObject.class);
        String encryptedOutput = responseJson.getString("output");
        Cipher aesCipher = Cipher.getInstance("AES/GCM/NoPadding");
        GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);
        aesCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aesSecretKey.getEncoded(), "AES"), gcmParameterSpec);
        byte[] decryptedBytes = aesCipher.doFinal(Base64.decodeBase64(encryptedOutput));
        return new String(decryptedBytes);
}
def decrypt_response_with_aes(aes_key, iv, response_data):
    """使用AES-GCM解密响应"""
    # 提取加密的输出
    encrypted_output = response_data.get("output")
    if not encrypted_output:
        raise ValueError("Response missing 'output' field")
    # 解码Base64数据
    encrypted_data = base64.b64decode(encrypted_output)
    # 分离密文和标签(标签长度16字节)
    ciphertext = encrypted_data[:-16]
    tag = encrypted_data[-16:]
    # 创建AES-GCM解密器
    aesgcm = Cipher(
        algorithms.AES(aes_key),
        modes.GCM(iv, tag),
        backend=default_backend()
    ).decryptor()
    # 验证关联数据(与加密时一致)
    aesgcm.authenticate_additional_data(b'')
    # 解密数据
    decrypted_bytes = aesgcm.update(ciphertext) + aesgcm.finalize()
    return decrypted_bytes.decode('utf-8')

Complete HTTP example code

This section provides complete Java and Python code examples. These examples combine all the steps from the integration process into a runnable program. If you use another programming language, you can follow the integration process to implement the logic.
Tip: If you need an implementation in another programming language, you can use an LLM to convert the following code to your target language.
Important: The example code is for reference only. Do not use it directly in a production environment.
Note: For more information about request parameters, see the Qwen API documentation.
Request example
java
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.X509EncodedKeySpec;
import java.util.Map;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import com.alibaba.fastjson.JSONObject;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
public class Main {
    // 采用AES-GCM 加密模式,以提升数据安全和完整性保护,在此指定IV、Tag长度
    private static final int GCM_TAG_LENGTH = 128; // 128 位 Tag(16 字节)
    private static final int GCM_IV_LENGTH = 12; // 12 字节 IV
    public static void main(String[] args) throws Exception {
        String publicKeyId = "xxx"; // 需要替换为实际获取到的RSA公钥 public_key_id 值
        String publicKey = "xxx"; // 需要替换为实际获取到的RSA公钥 public_key 值
        // 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:String apiKey = "sk-xxx",但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        String apiKey = System.getenv("DASHSCOPE_API_KEY");
        // 生成 AES 密钥
        SecretKey aesSecretKey = generateAesSecretKey();
        // 生成唯一性iv
        byte[] iv = generateIv();
        // 加密 input 数据
        String input = "{\"messages\": [{\"role\":\"user\",\"content\":\"你是谁?\"}]}";
        String encryptedInput = encryptInputWithAes(aesSecretKey, iv, input);
        // 使用 RSA 公钥加密 AES 密钥
        String encryptedAesKey = encryptAesKeyWithRsaPublicKey(aesSecretKey, publicKey);
        // 构建并发送请求
        String response = sendEncryptedRequest(apiKey, publicKeyId, encryptedAesKey, iv, encryptedInput);
        // 解密响应内容
        String decryptOutput = decryptResponseWithAes(aesSecretKey, iv, response);
        System.out.println("输出的内容是: " + decryptOutput);
    }
    private static SecretKey generateAesSecretKey() throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        SecureRandom secureRandom = new SecureRandom();
        keyGen.init(256, secureRandom); // AES密钥长度支持128、192、256 位。
        return keyGen.generateKey();
    }
    private static byte[] generateIv() {
        byte[] iv = new byte[GCM_IV_LENGTH];
        SecureRandom secureRandom = new SecureRandom(); // 随机生成确保唯一性
        secureRandom.nextBytes(iv);
        return iv;
    }
    private static String encryptAesKeyWithRsaPublicKey(SecretKey aesSecretKey, String publicKey) throws Exception {
        byte[] aesKeyBytes = aesSecretKey.getEncoded();
        String base64AesKey = Base64.encodeBase64String(aesKeyBytes);
        byte[] publicKeyBytes = Base64.decodeBase64(publicKey);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey pubKey = kf.generatePublic(spec);
        Cipher rsaCipher = Cipher.getInstance("RSA");
        rsaCipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] encryptedBytes = rsaCipher.doFinal(base64AesKey.getBytes());
        return Base64.encodeBase64String(encryptedBytes);
    }
    private static String encryptInputWithAes(SecretKey aesSecretKey, byte[] iv, String input) throws Exception {
        byte[] content = input.getBytes(StandardCharsets.UTF_8);
        Cipher aesCipher = Cipher.getInstance("AES/GCM/NoPadding");
        GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);
        aesCipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aesSecretKey.getEncoded(), "AES"), gcmParameterSpec);
        byte[] encryptedBytes = aesCipher.doFinal(content);
        return Base64.encodeBase64String(encryptedBytes);
    }
    private static String sendEncryptedRequest(String apiKey, String publicKeyId, String encryptedAesKey, byte[] iv, String encryptedInput) throws Exception {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder().build();
        JSONObject requestBodyJson = new JSONObject();
        requestBodyJson.put("model", "qwen-plus");
        requestBodyJson.put("input", encryptedInput);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestBodyJson.toJSONString());
        JSONObject headerJson = new JSONObject();
        headerJson.put("Content-Type", "application/json");
        headerJson.put("Accept", "application/json");
        headerJson.put("Authorization","Bearer " + apiKey);
        String encryptionHeader = String.format("{\"public_key_id\": \"%s\", \"encrypt_key\": \"%s\", \"iv\": \"%s\"}", publicKeyId, encryptedAesKey, Base64.encodeBase64String(iv));
        headerJson.put("X-DashScope-EncryptionKey", encryptionHeader);
        Headers headers = Headers.of(JSONObject.parseObject(headerJson.toString(), Map.class));
        String url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .headers(headers)
                .build();
        return okHttpClient.newCall(request).execute().body().string();
    }
    private static String decryptResponseWithAes(SecretKey aesSecretKey, byte[] iv,String response) throws Exception {
        JSONObject responseJson = JSONObject.parseObject(response, JSONObject.class);
        String encryptedOutput = responseJson.getString("output");
        Cipher aesCipher = Cipher.getInstance("AES/GCM/NoPadding");
        GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);
        aesCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aesSecretKey.getEncoded(), "AES"), gcmParameterSpec);
        byte[] decryptedBytes = aesCipher.doFinal(Base64.decodeBase64(encryptedOutput));
        return new String(decryptedBytes);
    }
}
Response example The output field returned by an HTTP call is Base64-encoded ciphertext and must be manually decrypted as described in the preceding "3. Decrypt the response data" section. The following is an example of the decrypted output content:
{
    "choices": [
        {
            "finish_reason": "stop",
            "message": {
                "role": "assistant",
                "content": "我是Qwen,由阿里云开发的超大规模语言模型。我的目标是帮助用户更高效地获取信息、解决各种问题并激发创造力。无论是回答问题、提供信息还是进行创意性的讨论,我都会尽力提供支持。有什么我可以帮到你的吗?"
            }
        }
    ]
}

FAQ

Q: Why do I receive the error "Invalid AES key Length: 294 bytes" during code execution? A: AES keys must be 128 bits (16 bytes), 192 bits (24 bytes), or 256 bits (32 bytes) long. Check your key length setting. Q: Do the OpenAI-compatible Endpoints for the Chat Completions API and Responses API support encrypted inference? A: No, they do not. The encryption flow described in this topic applies only to the DashScope SDK and HTTP Endpoints. Q: Do I need to fetch the RSA public key for each request? A: No, you do not. You should cache the RSA public key on the client for a recommended duration of 1 minute. The public key does not change under normal circumstances. It is only rotated in an emergency, such as a security incident. If a request returns the error code BadRequest.IllegalInput (The input parameter can not be decoded.), the public key is invalid. Immediately fetch the latest public key.

Error codes

If a call fails, an error message is returned. For troubleshooting information, see Error messages.