#How would I use web crypto to encrypt a json object inside a mutation?
5 messages · Page 1 of 1 (latest)
Hi @fringe gorge. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Yes, you can use the Web Crypto APIs provided by the Convex runtime to encrypt a JSON object inside a mutation. The Web Crypto APIs available include crypto (https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API), CryptoKey (https://developer.mozilla.org/en-US/docs/Web/API/CryptoKey), and SubtleCrypto (https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) (source (https://docs.convex.dev/functions/runtimes#web-crypto-apis)).
Here's a general example of how you might use these APIs to encrypt data:
const encoder = new TextEncoder();
const data = encoder.encode(JSON.stringify(yourJsonObject));
const key = await crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 },
true,
["encrypt", "decrypt"]
);
const iv = crypto.getRandomValues(new Uint8Array(12));
const encryptedData = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv: iv },
key,
data
);
This code generates a new AES-GCM key, then uses it to encrypt the JSON object. The iv (initialization vector) is a random value that's used to ensure each encryption operation produces unique output, even when the same key and data are used.
You can then store the encrypted data in your mutation. For example:
export const createEncryptedObject = mutation({
args: {
encryptedData: v.any(),
},
handler: async (ctx, { encryptedData }) => {
// Store the encrypted data
const newObject = await ctx.db.insert("object", {
encryptedData,
});
},
});
In this mutation, encryptedData is the encrypted JSON object. The v.any() validator is used because the encrypted data can be any type.
Remember that you'll also need to securely store the key and iv used for encryption, as you'll need them to decrypt the data later. You should not store these in the same place as the encrypted data.
Please note that this is a simplified example and may not cover all security considerations for your specific use case. Always ensure you follow best practices for encryption and key management.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@fringe gorge kapa.ai is still learning and improving, please let us know how it did by reacting below