Skip to content

Commit c83f5b4

Browse files
committed
iv generation moved into aes function
1 parent e6df7af commit c83f5b4

File tree

2 files changed

+12
-14
lines changed

2 files changed

+12
-14
lines changed

src/hooks/useSendMessage.ts

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { useContext } from "react";
22
import { IMessage } from "react-native-gifted-chat";
3-
import forge from "node-forge";
43
import { sendMessage } from "../utils/socket";
54
import { CommtContext } from "../context/Context";
65
import { addMessage } from "../context/actions/messagesAction";
@@ -61,10 +60,8 @@ const useSendMessage = () => {
6160
}
6261

6362
// AES encryption is the standard encryption method and encrypts every messages. It encrypts data by generating IV.
64-
const iv = forge.random.getBytesSync(16);
65-
encryptedMessage = aesEncrypt({
63+
const { encryptedMessage: encryptedMsg, iv } = aesEncrypt({
6664
key: secretKey,
67-
iv,
6865
messageData: JSON.stringify({
6966
message: { ...messageContent, text: encryptedMessage },
7067
roomId,
@@ -74,8 +71,8 @@ const useSendMessage = () => {
7471

7572
sendMessage(
7673
{
77-
message: encryptedMessage,
78-
iv: forge.util.bytesToHex(iv),
74+
message: encryptedMsg,
75+
iv,
7976
},
8077
(status) => {
8178
// If the message sending succesfully

src/utils/encryption.ts

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ import forge, { pki } from "node-forge";
22

33
interface KeyProps {
44
key: string;
5-
iv: string;
65
}
76

87
interface AesEncryptProps extends KeyProps {
@@ -11,6 +10,7 @@ interface AesEncryptProps extends KeyProps {
1110

1211
interface AesDecryptProps extends KeyProps {
1312
encryptedMessageData: string;
13+
iv: string;
1414
}
1515

1616
interface RsaEncryptProps {
@@ -23,18 +23,19 @@ interface RsaDecryptProps {
2323
privateKey: string;
2424
}
2525

26-
export const aesEncrypt = ({
27-
messageData,
28-
key,
29-
iv,
30-
}: AesEncryptProps): string => {
26+
export const aesEncrypt = ({ messageData, key }: AesEncryptProps) => {
27+
let iv = forge.random.getBytesSync(16);
3128
const cipher = forge.cipher.createCipher("AES-CBC", key);
3229

3330
cipher.start({ iv });
3431
cipher.update(forge.util.createBuffer(messageData, "utf8"));
3532
cipher.finish();
36-
// return encrypted data
37-
return cipher.output.toHex();
33+
34+
const encryptedMessage = cipher.output.toHex();
35+
iv = forge.util.bytesToHex(iv);
36+
37+
// return encrypted message and iv
38+
return { encryptedMessage, iv };
3839
};
3940

4041
export const aesDecrypt = ({

0 commit comments

Comments
 (0)