Skip to content

Commit d6194ee

Browse files
committed
Added rsaEncryption for message text field
1 parent 298b39e commit d6194ee

File tree

1 file changed

+33
-7
lines changed

1 file changed

+33
-7
lines changed

src/hooks/useSendMessage.ts

Lines changed: 33 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import { useContext } from "react";
22
import { IMessage } from "react-native-gifted-chat";
3+
import forge from "node-forge";
34
import { sendMessage } from "../utils/socket";
45
import { CommtContext } from "../context/Context";
56
import { addMessage } from "../context/actions/messagesAction";
67
import { updateLastMessage } from "../context/actions/roomsActions";
7-
import forge from "node-forge";
8-
import { aesEncrypt } from "../utils/encryption";
8+
import { aesEncrypt, rsaEncrypt } from "../utils/encryption";
99

1010
interface onSendMessageProps {
1111
message: IMessage;
@@ -16,9 +16,10 @@ interface onSendMessageProps {
1616
const useSendMessage = () => {
1717
const {
1818
state: {
19-
users: { selfUser },
19+
users: { selfUser, users },
20+
rooms,
2021
app: {
21-
configs: { secretKey, apiKey, subscriptionKey, projectName },
22+
configs: { secretKey, apiKey, subscriptionKey, projectName, e2e },
2223
},
2324
},
2425
dispatch,
@@ -32,13 +33,38 @@ const useSendMessage = () => {
3233
senderId: message.user._id,
3334
};
3435

35-
// create iv and encrypt data for each message
36+
let encryptedMessage = messageContent.text;
37+
38+
// If the e2e feature of the client is enabled and the message is not generated by the system
39+
if (e2e && !message.system) {
40+
const room = rooms.find((room) => room.roomId === roomId);
41+
42+
// Find the opposing user ID among one-to-one room participants
43+
const oppositeUserId = room?.groupName
44+
? null
45+
: room?.participants.find(
46+
(id) => id !== selfUser?._id && !id.startsWith("system"),
47+
);
48+
49+
const oppositeUserPck = users.find((user) => user._id === oppositeUserId)
50+
?.publicKey;
51+
52+
// If the opposite user has a public key, the message text is encrypted using RSA.
53+
if (oppositeUserPck) {
54+
encryptedMessage = rsaEncrypt({
55+
message: encryptedMessage,
56+
publicKey: oppositeUserPck,
57+
});
58+
}
59+
}
60+
61+
// AES encryption is the standard encryption method and encrypts every messages. It encrypts data by creating IV
3662
const iv = forge.random.getBytesSync(16);
37-
const encryptedMessage = aesEncrypt({
63+
encryptedMessage = aesEncrypt({
3864
key: secretKey,
3965
iv,
4066
messageData: JSON.stringify({
41-
message: messageContent,
67+
message: { ...messageContent, text: encryptedMessage },
4268
roomId,
4369
chatRoomAuthId,
4470
}),

0 commit comments

Comments
 (0)