-
-
Notifications
You must be signed in to change notification settings - Fork 617
Send encrypted message (encrypt the content) #1767
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Please share your full minimal example. For encryption to work you will need awaited call to https://github.com/matrix-org/matrix-js-sdk#end-to-end-encryption-support |
From element when i send a message in an encrypted room the decryptEvent is working and the message is being recieved properly on simulator so encryption should be working but when i send it from simulator i get this error on element ** Unable to decrypt: Unknown encryption algorithm "undefined". ** because the content is : I don't know if I should encrypt the message or it should be encrypted automatically when using const content = { try { P.S I'm using react native so I can't add global.Olm = require('olm'); but everything related to crypto is working also I'm using |
|
I'm awaiting everything, the send event if the type is m.room.encrypted it should encrypt the message content automatically or i should encrypt it before using it? |
You should be using event type |
If you do not provide a COMPLETE functional yet minimal example you cannot be helped. |
import React, { useEffect } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import matrixSdk, { MemoryStore, MatrixEvent } from 'matrix-js-sdk';
import request from 'xmlhttp-request';
import AsyncStorage from '@react-native-async-storage/async-storage';
import AsyncCryptoStore from './lib/AsyncCryptoStore';
const BASE_URL = 'http://192.168.102.121:30808';
export const MATRIX_CLIENT_START_OPTIONS = {
initialSyncLimit: 10,
request: request,
lazyLoadMembers: true,
pendingEventOrdering: 'detached',
timelineSupport: true,
unstableClientRelationAggregation: true,
store: new MemoryStore({
localStorage: AsyncStorage,
}),
cryptoStore: new AsyncCryptoStore(AsyncStorage),
sessionStore: {
getLocalTrustedBackupPubKey: () => null,
}, // js-sdk complains if this isn't supplied but it's only used for remembering a local trusted backup key
};
export var matrixAlias = {};
export const LoginToChat = async ({ register = false, callBack }) => {
try {
const username = 'dtp18';
const chatPassword = 'Midomek@1';
const registrationClient = await matrixSdk.createClient(BASE_URL);
if (username && chatPassword) {
try {
userRegisterResult = await registrationClient.login(
'm.login.password',
{
user: username,
password: chatPassword,
}
);
} catch (e) {
console.log('error login', e);
}
} else {
return;
}
const matrixClient = await matrixSdk.createClient({
baseUrl: BASE_URL,
userId: userRegisterResult.user_id,
accessToken: userRegisterResult.access_token,
deviceId: userRegisterResult.device_id,
...MATRIX_CLIENT_START_OPTIONS,
});
await matrixClient.initCrypto();
await matrixClient.startClient();
matrixAlias = matrixClient;
matrixAlias.once('sync', async function (state, prevState, res) {
// after client is ready
if (state === 'PREPARED') {
await matrixClient.uploadKeys();
matrixClient.exportRoomKeys();
getTimeline();
callBack && callBack();
}
});
} catch (e) {
printError(e);
}
};
export const sendMessageChat = async ({ message, roomID }) => {
autoVerify(roomID);
const content = {
body: message,
msgtype: 'm.text',
};
try {
const result = await matrixAlias.sendEvent(
roomID,
'm.room.message',
content
);
} catch (err) {
console.log('SEND MESSAGE ERROR ', err);
alert('sending error');
}
};
export const getTimeline = () => {
matrixAlias.on('Room.timeline', async (message, room, toStartOfTimeline) => {
let body = '';
let event;
try {
if (message.event.type === 'm.room.encrypted') {
autoVerify(message.event.room_id);
event = await matrixAlias._crypto.decryptEvent(message);
({ body } = event?.clearEvent?.content ?? '');
} else {
({ body } = message.event.content);
}
if (body) {
console.log(body);
}
} catch (error) {
console.error('RECEIVE MESSAGE ERROR ', error);
}
});
};
export const autoVerify = async (room_id) => {
let room = matrixAlias.getRoom(room_id);
const e2eMembers = await room.getEncryptionTargetMembers();
for (const member of e2eMembers) {
const devices = matrixAlias.getStoredDevicesForUser(member.userId);
for (const device of devices) {
if (device.isUnverified()) {
await verifyDevice(member.userId, device.deviceId);
}
}
}
};
export async function verifyDevice(userId, deviceId) {
if (!userId || typeof userId !== 'string') {
throw new Error('"userId" is required and must be a string.');
}
if (!deviceId || typeof deviceId !== 'string') {
throw new Error('"deviceId" is required and must be a string.');
}
await matrixAlias.setDeviceKnown(userId, deviceId, true);
await matrixAlias.setDeviceVerified(userId, deviceId, true);
}
const testingChat = () => {
useEffect(() => {
LoginToChat({
callBack: () => {
sendMessageChat({
message: 'hello',
roomID: '!NrNMsmxdVaSDSnhzYc:kubernetesMaster.dtp.ae',
});
},
});
}, []);
return null
};
export default testingChat; |
I don't see you awaiting the initial sync in there
|
Check the example now please and really thank you for your time, if it's not sufficient tomorrow i will try to make a better example |
turned out if i send a message from another device the message in timeline will be encrypted but when i send the message from the same device and see it in the timeline the event content will not be encrypted |
Ah, so yes |
@mmeksasi Thanks for sharing the code. Helped me a lot! Now I can't find you loading of the Olm library. RN is complaining about this I've downloaded from here and run a build. I use the legacy version as the version with webassebly seems not to run in RN. Looking for 2 days now into that but I can't manage to run the project. How did you solved this? |
I've got it working by using: import Olm from 'olm/olm_legacy';
global.Olm = Olm; using this in my package.json |
See my sample repo for reference sample repo here |
I'm trying to send a message to an encrypted room but I don't know if the event should send it as encrypted if the room is encrypted the content is being sent as :
but it should be sent as:
Maybe i need to use MegolmEncryption.encryptMessage but i didn't know how to use it if someone can help
The text was updated successfully, but these errors were encountered: