To enhance the data security of your retrieval-augmented generation (RAG) knowledge base, you can encrypt text chunks and vectors. Because vectors can also leak original semantics, encrypting them lets you store and transmit data as ciphertext. Vector encryption requires a special algorithm that supports similarity searches on encrypted vectors. This topic uses the LangChain framework in a Data Science Workshop (DSW) development environment as an example to demonstrate how to build a RAG application that supports knowledge base encryption.
Solution overview
The key process is as follows:
-
Encrypted storage: Parse, chunk, and vectorize the document. Then, encrypt the resulting text chunks and embeddings and store the ciphertext in a vector database.
This topic uses the Python
rai_samlibrary for encryption and decryption. The encryption methods are as follows:-
Text chunk encryption: Uses the industry-standard Advanced Encryption Standard (AES)-CTR-256 encryption algorithm.
-
Vector encryption: Uses the DCPE encryption algorithm. This algorithm supports similarity calculations and sorting for encrypted vectors and provides higher security than order-preserving encryption. For more information about its security, see the DCPE paper.
-
-
Decryption and inference: Vectorize and encrypt the user's query, and then search the vector database. The inference service decrypts the search results (ciphertext) and inputs the decrypted results and the original query into a large language model (LLM) to generate a response.
1. Prepare the development environment
-
Open the DSW development environment. You can also use a local development environment or another environment of your choice.
-
Create a DSW instance. This topic uses a DSW instance with the following configurations:
-
Alibaba Cloud Image:
modelscope:1.26.0-pytorch2.3.1tensorflow2.16.1-gpu-py311-cu121-ubuntu22.04. -
Resource Specification:
ecs.gn7i-c8g1.2xlarge.
-
-
On the Data Science Workshop (DSW) page, click Open in the Actions column for the target instance.
-
On the Notebook tab, click Create Notebook.

-
-
Install the dependencies required to run the code.
!pip install -U langchain langchain-community langchain_huggingface !pip install -U pypdf !pip install -U modelscope !pip install -U alibabacloud-ha3engine-vector !pip install -U pymilvus !pip install -U rai_sam !pip install -U flask -
Download the embedding model to convert text chunks into vectors. This topic uses bge-large-zh-v1.5. You can choose another embedding model based on your data type, language, or specific domain, such as the legal field.
from modelscope import snapshot_download model_dir = snapshot_download('BAAI/bge-large-zh-v1.5', cache_dir='.') -
Prepare the encryption key. To encrypt data using the `rai_sam` module, you need a custom encryption key (4 to 48 bytes) and a key ID (4 to 128 bytes). This topic uses `LD_Secret_0123456789` as the key and `LD_ID_123456` as the key ID. You can configure them as environment variables to be retrieved later. For production applications, you must manage your keys more securely, such as using Key Management Service (KMS).
import os # Custom key ID (4 to 48 bytes) os.environ["SAM_KEY_ID"] = "LD_ID_123456" # Custom key (4 to 128 bytes) os.environ["SAM_KEY_SECRET"] = "LD_Secret_0123456789"
2. Process the document and store it with encryption
This section describes how to encrypt a file and store it in a vector database.
3. Deploy the model service
For data security, the vector search results retrieved from the model service are ciphertext. This data must be decrypted before it is sent to the LLM for inference. You can refer to the sample `app.py` file to modify your online prediction code to work with the encrypted knowledge base.
For testing purposes, this section uses the preceding app.py file to start an inference service in the DSW development environment.
-
Download the model code.
# Download the model. from modelscope import snapshot_download model_dir = snapshot_download('Qwen/Qwen2.5-3B-Instruct', cache_dir='/mnt/workspace/') -
Start the inference service. Open a terminal and run the following command in the directory where `app.py` is located:
# Set temporary environment variables. export SAM_KEY_ID=LD_ID_123456 export SAM_KEY_SECRET=LD_Secret_0123456789 # Run the Python code file. python app.pyThe following output indicates that the service started successfully.
4. Vector search and inference
Production environment applications
To use this solution in a production environment, you can use an Alibaba Cloud vector database and deploy a securely encrypted inference service in PAI-EAS. This practice enhances your application's security.
Use an Alibaba Cloud vector database
The following code shows how to use Alibaba Cloud vector databases, such as Milvus, OpenSearch, and Elasticsearch, to store and retrieve encrypted data.
Alibaba Cloud Milvus
The following describes the key configuration parameters:
-
demo_collection_name: The name of the collection in the Milvus instance, such as `milvus_demo_collection`.
-
uri: The endpoint of the Milvus instance. Both private network and public network access are supported. The format is
http://<endpoint>:<port>. -
token: The authentication token. The format is
username:password, which corresponds toMilvus instance username:Milvus instance password. -
db_name: The name of an existing database, such as `default`.
Alibaba Cloud OpenSearch
Where:
-
instance_id: The ID of the OpenSearch instance.
-
table_name: The name of the OpenSearch index table.
-
access_user_name: The username for the OpenSearch instance.
-
access_pass_word: The password for the OpenSearch instance.
Alibaba Cloud Elasticsearch
The parameters are as follows:
-
index_name: The name of the index. To customize the index name, you must update the YML file on the Elasticsearch instance page to allow automatic index creation.
-
<Elasticsearch_URL>: The endpoint of the Elasticsearch instance. This endpoint supports both private network and public network access. The format is
http://<address>:<port>. -
<YourPassword>: The logon password for the Elasticsearch instance.
Deploy a PAI-EAS model service
PAI-EAS lets you configure a secure and encrypted environment. Using the system trust management service, you can ensure that information such as data, models, and code is securely encrypted during service deployment and invocation. This enables a secure and verifiable inference service. For more information, see Secure and encrypted inference service.