Son
Son11mo ago

Using crypto in convex functions

i have this utility function... util.ts, stored outside/inside convex folder, same issues.
import crypto from 'crypto';

export function encrypt(text: string) {
const secret = process.env.SECRET;
if (!secret) {
throw new Error('Secret for encryption is not defined');
}
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(secret), Buffer.alloc(16));
let encrypted = cipher.update(text, 'utf8', 'base64');
encrypted += cipher.final('base64');
return encrypted;
}
import crypto from 'crypto';

export function encrypt(text: string) {
const secret = process.env.SECRET;
if (!secret) {
throw new Error('Secret for encryption is not defined');
}
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(secret), Buffer.alloc(16));
let encrypted = cipher.update(text, 'utf8', 'base64');
encrypted += cipher.final('base64');
return encrypted;
}
which i want to use in a query like this
export const createMessage = mutation({
args: { author: v.string(), body: v.string() },
handler: async (ctx, { author, body }) => {

const encryptedText = encrypt(body);

const response = await ctx.db.insert('messages', { author, body: encryptedText });

if (!response) {
return 'failed';
}

return 'success';
}
});
export const createMessage = mutation({
args: { author: v.string(), body: v.string() },
handler: async (ctx, { author, body }) => {

const encryptedText = encrypt(body);

const response = await ctx.db.insert('messages', { author, body: encryptedText });

if (!response) {
return 'failed';
}

return 'success';
}
});
This does not work because the code is running on the client side and the crypto module only exists on the sever, this might be a silly question but where can i write the sever code to encrypt my messages.
No description
5 Replies
jamwt
jamwt11mo ago
Convex actions support web crypto, not node.js style crypto
jamwt
jamwt11mo ago
MDN Web Docs
Web Crypto API - Web APIs | MDN
The Web Crypto API is an interface allowing a script to use cryptographic primitives in order to build systems using cryptography.
jamwt
jamwt11mo ago
this article demonstrates using web crypto apis to do AES encryption: https://medium.com/@tony.infisical/guide-to-web-crypto-api-for-encryption-decryption-1a2c698ebc25
Medium
Guide to Web Crypto API for encryption/decryption
Depending on your environment and requirements, the Web Crypto API may be needed required or suitable to perform cryptographic operations…
Son
SonOP11mo ago
Thank you

Did you find this page helpful?