Format code (prettier)

This commit is contained in:
Nicola Benaglia 2025-05-17 00:25:13 +02:00
parent b0274b4cb7
commit b6f8b190c0
5 changed files with 612 additions and 482 deletions

View File

@ -216,7 +216,9 @@ export const DownloadWallet = ({
</Box> </Box>
} }
/> />
<Spacer height="20px" /> <Spacer height="20px" />
{!keepCurrentPassword && ( {!keepCurrentPassword && (
<> <>
<CustomLabel htmlFor="standard-adornment-password"> <CustomLabel htmlFor="standard-adornment-password">
@ -226,11 +228,13 @@ export const DownloadWallet = ({
</CustomLabel> </CustomLabel>
<Spacer height="5px" /> <Spacer height="5px" />
<PasswordField <PasswordField
id="standard-adornment-password" id="standard-adornment-password"
value={newPassword} value={newPassword}
onChange={(e) => setNewPassword(e.target.value)} onChange={(e) => setNewPassword(e.target.value)}
/> />
<Spacer height="20px" /> <Spacer height="20px" />
</> </>
)} )}

View File

@ -351,7 +351,7 @@ export const GroupAnnouncements = ({
} }
}; };
const getAnnouncements = React.useCallback( const getAnnouncements = useCallback(
async (selectedGroup, isPrivate) => { async (selectedGroup, isPrivate) => {
try { try {
const offset = 0; const offset = 0;
@ -387,7 +387,7 @@ export const GroupAnnouncements = ({
[secretKey] [secretKey]
); );
React.useEffect(() => { useEffect(() => {
if (!secretKey && isPrivate) return; if (!secretKey && isPrivate) return;
if ( if (
selectedGroup && selectedGroup &&
@ -432,7 +432,7 @@ export const GroupAnnouncements = ({
const theme = useTheme(); const theme = useTheme();
const checkNewMessages = React.useCallback(async () => { const checkNewMessages = useCallback(async () => {
try { try {
const identifier = `grp-${selectedGroup}-anc-`; const identifier = `grp-${selectedGroup}-anc-`;
const url = `${getBaseApiReact()}${getArbitraryEndpointReact()}?mode=ALL&service=DOCUMENT&identifier=${identifier}&limit=20&includemetadata=false&offset=${0}&reverse=true&prefix=true`; const url = `${getBaseApiReact()}${getArbitraryEndpointReact()}?mode=ALL&service=DOCUMENT&identifier=${identifier}&limit=20&includemetadata=false&offset=${0}&reverse=true&prefix=true`;

View File

@ -37,7 +37,8 @@ export const QortPayment = ({ balance, show, onSuccess, defaultPaymentTo }) => {
setSendPaymentError('Please enter your wallet password'); setSendPaymentError('Please enter your wallet password');
return; return;
} }
const fee = await getFee('PAYMENT');
const fee = await getFee('PAYMENT'); // TODO translate
await show({ await show({
message: `Would you like to transfer ${Number(paymentAmount)} QORT?`, message: `Would you like to transfer ${Number(paymentAmount)} QORT?`,
@ -148,7 +149,7 @@ export const QortPayment = ({ balance, show, onSuccess, defaultPaymentTo }) => {
<Spacer height="6px" /> <Spacer height="6px" />
<CustomLabel htmlFor="standard-adornment-password"> <CustomLabel htmlFor="standard-adornment-password">
Confirm Wallet Password Confirm wallet password
</CustomLabel> </CustomLabel>
<Spacer height="5px" /> <Spacer height="5px" />

View File

@ -1,57 +1,58 @@
// @ts-nocheck // @ts-nocheck
import Base58 from "../../deps/Base58" import Base58 from '../../deps/Base58';
import ed2curve from "../../deps/ed2curve" import ed2curve from '../../deps/ed2curve';
import nacl from "../../deps/nacl-fast" import nacl from '../../deps/nacl-fast';
export function base64ToUint8Array(base64: string) { export function base64ToUint8Array(base64: string) {
const binaryString = atob(base64) const binaryString = atob(base64);
const len = binaryString.length const len = binaryString.length;
const bytes = new Uint8Array(len) const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) { for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i) bytes[i] = binaryString.charCodeAt(i);
} }
return bytes return bytes;
} }
export function uint8ArrayToBase64(uint8Array: any) { export function uint8ArrayToBase64(uint8Array: any) {
const length = uint8Array.length const length = uint8Array.length;
let binaryString = '' let binaryString = '';
const chunkSize = 1024 * 1024; // Process 1MB at a time const chunkSize = 1024 * 1024; // Process 1MB at a time
for (let i = 0; i < length; i += chunkSize) { for (let i = 0; i < length; i += chunkSize) {
const chunkEnd = Math.min(i + chunkSize, length) const chunkEnd = Math.min(i + chunkSize, length);
const chunk = uint8Array.subarray(i, chunkEnd) const chunk = uint8Array.subarray(i, chunkEnd);
binaryString += Array.from(chunk, byte => String.fromCharCode(byte)).join('') binaryString += Array.from(chunk, (byte) => String.fromCharCode(byte)).join(
''
);
} }
return btoa(binaryString) return btoa(binaryString);
} }
export function objectToBase64(obj: Object) { export function objectToBase64(obj: Object) {
// Step 1: Convert the object to a JSON string // Step 1: Convert the object to a JSON string
const jsonString = JSON.stringify(obj) const jsonString = JSON.stringify(obj);
// Step 2: Create a Blob from the JSON string // Step 2: Create a Blob from the JSON string
const blob = new Blob([jsonString], { type: 'application/json' }) const blob = new Blob([jsonString], { type: 'application/json' });
// Step 3: Create a FileReader to read the Blob as a base64-encoded string // Step 3: Create a FileReader to read the Blob as a base64-encoded string
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const reader = new FileReader() const reader = new FileReader();
reader.onloadend = () => { reader.onloadend = () => {
if (typeof reader.result === 'string') { if (typeof reader.result === 'string') {
// Remove 'data:application/json;base64,' prefix // Remove 'data:application/json;base64,' prefix
const base64 = reader.result.replace( const base64 = reader.result.replace(
'data:application/json;base64,', 'data:application/json;base64,',
'' ''
) );
resolve(base64) resolve(base64);
} else { } else {
reject(new Error('Failed to read the Blob as a base64-encoded string')) reject(new Error('Failed to read the Blob as a base64-encoded string'));
}
} }
};
reader.onerror = () => { reader.onerror = () => {
reject(reader.error) reject(reader.error);
} };
reader.readAsDataURL(blob) reader.readAsDataURL(blob);
}) });
} }
// Function to create a symmetric key and nonce // Function to create a symmetric key and nonce
@ -59,95 +60,131 @@ export const createSymmetricKeyAndNonce = () => {
const messageKey = new Uint8Array(32); // 32 bytes for the symmetric key const messageKey = new Uint8Array(32); // 32 bytes for the symmetric key
crypto.getRandomValues(messageKey); crypto.getRandomValues(messageKey);
return { messageKey: uint8ArrayToBase64(messageKey) };
return { messageKey: uint8ArrayToBase64(messageKey)};
}; };
export const encryptDataGroup = ({
data64,
publicKeys,
privateKey,
userPublicKey,
customSymmetricKey,
}: any) => {
let combinedPublicKeys = [...publicKeys, userPublicKey];
const decodedPrivateKey = Base58.decode(privateKey);
const publicKeysDuplicateFree = [...new Set(combinedPublicKeys)];
export const encryptDataGroup = ({ data64, publicKeys, privateKey, userPublicKey, customSymmetricKey }: any) => { const Uint8ArrayData = base64ToUint8Array(data64);
let combinedPublicKeys = [...publicKeys, userPublicKey]
const decodedPrivateKey = Base58.decode(privateKey)
const publicKeysDuplicateFree = [...new Set(combinedPublicKeys)]
const Uint8ArrayData = base64ToUint8Array(data64)
if (!(Uint8ArrayData instanceof Uint8Array)) { if (!(Uint8ArrayData instanceof Uint8Array)) {
throw new Error("The Uint8ArrayData you've submitted is invalid") throw new Error("The Uint8ArrayData you've submitted is invalid");
} }
try { try {
// Generate a random symmetric key for the message. // Generate a random symmetric key for the message.
let messageKey let messageKey;
if(customSymmetricKey){ if (customSymmetricKey) {
messageKey = base64ToUint8Array(customSymmetricKey) messageKey = base64ToUint8Array(customSymmetricKey);
} else { } else {
messageKey = new Uint8Array(32) messageKey = new Uint8Array(32);
crypto.getRandomValues(messageKey) crypto.getRandomValues(messageKey);
} }
if(!messageKey) throw new Error('Cannot create symmetric key') if (!messageKey) throw new Error('Cannot create symmetric key');
const nonce = new Uint8Array(24) const nonce = new Uint8Array(24);
crypto.getRandomValues(nonce) crypto.getRandomValues(nonce);
// Encrypt the data with the symmetric key. // Encrypt the data with the symmetric key.
const encryptedData = nacl.secretbox(Uint8ArrayData, nonce, messageKey) const encryptedData = nacl.secretbox(Uint8ArrayData, nonce, messageKey);
// Generate a keyNonce outside of the loop. // Generate a keyNonce outside of the loop.
const keyNonce = new Uint8Array(24) const keyNonce = new Uint8Array(24);
crypto.getRandomValues(keyNonce) crypto.getRandomValues(keyNonce);
// Encrypt the symmetric key for each recipient. // Encrypt the symmetric key for each recipient.
let encryptedKeys = [] let encryptedKeys = [];
publicKeysDuplicateFree.forEach((recipientPublicKey) => { publicKeysDuplicateFree.forEach((recipientPublicKey) => {
const publicKeyUnit8Array = Base58.decode(recipientPublicKey) const publicKeyUnit8Array = Base58.decode(recipientPublicKey);
const convertedPrivateKey = ed2curve.convertSecretKey(decodedPrivateKey) const convertedPrivateKey = ed2curve.convertSecretKey(decodedPrivateKey);
const convertedPublicKey = ed2curve.convertPublicKey(publicKeyUnit8Array) const convertedPublicKey = ed2curve.convertPublicKey(publicKeyUnit8Array);
const sharedSecret = new Uint8Array(32) const sharedSecret = new Uint8Array(32);
// the length of the sharedSecret will be 32 + 16 // the length of the sharedSecret will be 32 + 16
// When you're encrypting data using nacl.secretbox, it's adding an authentication tag to the result, which is 16 bytes long. This tag is used for verifying the integrity and authenticity of the data when it is decrypted // When you're encrypting data using nacl.secretbox, it's adding an authentication tag to the result, which is 16 bytes long. This tag is used for verifying the integrity and authenticity of the data when it is decrypted
nacl.lowlevel.crypto_scalarmult(sharedSecret, convertedPrivateKey, convertedPublicKey) nacl.lowlevel.crypto_scalarmult(
sharedSecret,
convertedPrivateKey,
convertedPublicKey
);
// Encrypt the symmetric key with the shared secret. // Encrypt the symmetric key with the shared secret.
const encryptedKey = nacl.secretbox(messageKey, keyNonce, sharedSecret) const encryptedKey = nacl.secretbox(messageKey, keyNonce, sharedSecret);
encryptedKeys.push(encryptedKey) encryptedKeys.push(encryptedKey);
}) });
const str = "qortalGroupEncryptedData" const str = 'qortalGroupEncryptedData';
const strEncoder = new TextEncoder() const strEncoder = new TextEncoder();
const strUint8Array = strEncoder.encode(str) const strUint8Array = strEncoder.encode(str);
// Convert sender's public key to Uint8Array and add to the message // Convert sender's public key to Uint8Array and add to the message
const senderPublicKeyUint8Array = Base58.decode(userPublicKey) const senderPublicKeyUint8Array = Base58.decode(userPublicKey);
// Combine all data into a single Uint8Array. // Combine all data into a single Uint8Array.
// Calculate size of combinedData // Calculate size of combinedData
let combinedDataSize = strUint8Array.length + nonce.length + keyNonce.length + senderPublicKeyUint8Array.length + encryptedData.length + 4 let combinedDataSize =
let encryptedKeysSize = 0 strUint8Array.length +
nonce.length +
keyNonce.length +
senderPublicKeyUint8Array.length +
encryptedData.length +
4;
let encryptedKeysSize = 0;
encryptedKeys.forEach((key) => { encryptedKeys.forEach((key) => {
encryptedKeysSize += key.length encryptedKeysSize += key.length;
}) });
combinedDataSize += encryptedKeysSize combinedDataSize += encryptedKeysSize;
let combinedData = new Uint8Array(combinedDataSize) let combinedData = new Uint8Array(combinedDataSize);
combinedData.set(strUint8Array) combinedData.set(strUint8Array);
combinedData.set(nonce, strUint8Array.length) combinedData.set(nonce, strUint8Array.length);
combinedData.set(keyNonce, strUint8Array.length + nonce.length) combinedData.set(keyNonce, strUint8Array.length + nonce.length);
combinedData.set(senderPublicKeyUint8Array, strUint8Array.length + nonce.length + keyNonce.length) combinedData.set(
combinedData.set(encryptedData, strUint8Array.length + nonce.length + keyNonce.length + senderPublicKeyUint8Array.length) senderPublicKeyUint8Array,
strUint8Array.length + nonce.length + keyNonce.length
);
combinedData.set(
encryptedData,
strUint8Array.length +
nonce.length +
keyNonce.length +
senderPublicKeyUint8Array.length
);
// Initialize offset for encryptedKeys // Initialize offset for encryptedKeys
let encryptedKeysOffset = strUint8Array.length + nonce.length + keyNonce.length + senderPublicKeyUint8Array.length + encryptedData.length let encryptedKeysOffset =
strUint8Array.length +
nonce.length +
keyNonce.length +
senderPublicKeyUint8Array.length +
encryptedData.length;
encryptedKeys.forEach((key) => { encryptedKeys.forEach((key) => {
combinedData.set(key, encryptedKeysOffset) combinedData.set(key, encryptedKeysOffset);
encryptedKeysOffset += key.length encryptedKeysOffset += key.length;
}) });
const countArray = new Uint8Array(new Uint32Array([publicKeysDuplicateFree.length]).buffer) const countArray = new Uint8Array(
combinedData.set(countArray, combinedData.length - 4) new Uint32Array([publicKeysDuplicateFree.length]).buffer
return uint8ArrayToBase64(combinedData) );
combinedData.set(countArray, combinedData.length - 4);
return uint8ArrayToBase64(combinedData);
} catch (error) { } catch (error) {
console.log('error', error) console.log('error', error);
throw new Error("Error in encrypting data") throw new Error('Error in encrypting data');
} }
} };
export const encryptSingle = async ({ data64, secretKeyObject, typeNumber = 2 }: any) => { export const encryptSingle = async ({
data64,
secretKeyObject,
typeNumber = 2,
}: any) => {
// Find the highest key in the secretKeyObject // Find the highest key in the secretKeyObject
const highestKey = Math.max(...Object.keys(secretKeyObject).filter(item => !isNaN(+item)).map(Number)); const highestKey = Math.max(
...Object.keys(secretKeyObject)
.filter((item) => !isNaN(+item))
.map(Number)
);
const highestKeyObject = secretKeyObject[highestKey]; const highestKeyObject = secretKeyObject[highestKey];
// Convert data and keys from base64 // Convert data and keys from base64
@ -189,48 +226,57 @@ export const encryptSingle = async ({ data64, secretKeyObject, typeNumber = 2 }:
// Concatenate the highest key, type number, nonce, and encrypted data (new format) // Concatenate the highest key, type number, nonce, and encrypted data (new format)
const highestKeyStr = highestKey.toString().padStart(10, '0'); // Fixed length of 10 digits const highestKeyStr = highestKey.toString().padStart(10, '0'); // Fixed length of 10 digits
const highestKeyBytes = new TextEncoder().encode(highestKeyStr.padStart(10, '0')); const highestKeyBytes = new TextEncoder().encode(
const typeNumberBytes = new TextEncoder().encode(typeNumberStr.padStart(3, '0')); highestKeyStr.padStart(10, '0')
);
const typeNumberBytes = new TextEncoder().encode(
typeNumberStr.padStart(3, '0')
);
// Step 3: Concatenate all binary // Step 3: Concatenate all binary
const combinedBinary = new Uint8Array( const combinedBinary = new Uint8Array(
highestKeyBytes.length + typeNumberBytes.length + nonce.length + encryptedData.length highestKeyBytes.length +
); typeNumberBytes.length +
nonce.length +
encryptedData.length
);
// finalEncryptedData = btoa(highestKeyStr) + btoa(typeNumberStr) + nonceBase64 + encryptedDataBase64; // finalEncryptedData = btoa(highestKeyStr) + btoa(typeNumberStr) + nonceBase64 + encryptedDataBase64;
combinedBinary.set(highestKeyBytes, 0); combinedBinary.set(highestKeyBytes, 0);
combinedBinary.set(typeNumberBytes, highestKeyBytes.length); combinedBinary.set(typeNumberBytes, highestKeyBytes.length);
combinedBinary.set(nonce, highestKeyBytes.length + typeNumberBytes.length); combinedBinary.set(nonce, highestKeyBytes.length + typeNumberBytes.length);
combinedBinary.set(encryptedData, highestKeyBytes.length + typeNumberBytes.length + nonce.length); combinedBinary.set(
encryptedData,
highestKeyBytes.length + typeNumberBytes.length + nonce.length
);
// Step 4: Base64 encode once // Step 4: Base64 encode once
finalEncryptedData = uint8ArrayToBase64(combinedBinary); finalEncryptedData = uint8ArrayToBase64(combinedBinary);
} }
return finalEncryptedData; return finalEncryptedData;
}; };
export const decodeBase64ForUIChatMessages = (messages) => {
export const decodeBase64ForUIChatMessages = (messages)=> { let msgs = [];
for (const msg of messages) {
let msgs = []
for(const msg of messages){
try { try {
const decoded = atob(msg?.data); const decoded = atob(msg?.data);
const parseDecoded =JSON.parse(decodeURIComponent(escape(decoded))) const parseDecoded = JSON.parse(decodeURIComponent(escape(decoded)));
msgs.push({ msgs.push({
...msg, ...msg,
...parseDecoded ...parseDecoded,
}) });
} catch (error) {}
} catch (error) {
} }
} return msgs;
return msgs };
}
export const decryptSingle = async ({ data64, secretKeyObject, skipDecodeBase64 }: any) => { export const decryptSingle = async ({
data64,
secretKeyObject,
skipDecodeBase64,
}: any) => {
// First, decode the base64-encoded input (if skipDecodeBase64 is not set) // First, decode the base64-encoded input (if skipDecodeBase64 is not set)
const decodedData = skipDecodeBase64 ? data64 : atob(data64); const decodedData = skipDecodeBase64 ? data64 : atob(data64);
@ -263,26 +309,31 @@ export const decryptSingle = async ({ data64, secretKeyObject, skipDecodeBase64
} else { } else {
if (hasTypeNumber) { if (hasTypeNumber) {
// const typeNumberStr = new TextDecoder().decode(typeNumberBytes); // const typeNumberStr = new TextDecoder().decode(typeNumberBytes);
if(decodeForNumber.slice(10, 13) !== '001'){ if (decodeForNumber.slice(10, 13) !== '001') {
const decodedBinary = base64ToUint8Array(decodedData); const decodedBinary = base64ToUint8Array(decodedData);
const highestKeyBytes = decodedBinary.slice(0, 10); // if ASCII digits only const highestKeyBytes = decodedBinary.slice(0, 10); // if ASCII digits only
const highestKeyStr = new TextDecoder().decode(highestKeyBytes); const highestKeyStr = new TextDecoder().decode(highestKeyBytes);
const nonce = decodedBinary.slice(13, 13 + 24); const nonce = decodedBinary.slice(13, 13 + 24);
const encryptedData = decodedBinary.slice(13 + 24); const encryptedData = decodedBinary.slice(13 + 24);
const highestKey = parseInt(highestKeyStr, 10); const highestKey = parseInt(highestKeyStr, 10);
const messageKey = base64ToUint8Array(secretKeyObject[+highestKey].messageKey); const messageKey = base64ToUint8Array(
const decryptedBytes = nacl.secretbox.open(encryptedData, nonce, messageKey); secretKeyObject[+highestKey].messageKey
);
const decryptedBytes = nacl.secretbox.open(
encryptedData,
nonce,
messageKey
);
// Check if decryption was successful // Check if decryption was successful
if (!decryptedBytes) { if (!decryptedBytes) {
throw new Error("Decryption failed"); throw new Error('Decryption failed');
} }
// Convert the decrypted Uint8Array back to a Base64 string // Convert the decrypted Uint8Array back to a Base64 string
return uint8ArrayToBase64(decryptedBytes); return uint8ArrayToBase64(decryptedBytes);
} }
// New format: Extract type number and nonce // New format: Extract type number and nonce
typeNumberStr = possibleTypeNumberStr; // Extract type number typeNumberStr = possibleTypeNumberStr; // Extract type number
@ -309,201 +360,275 @@ const decryptedBytes = nacl.secretbox.open(encryptedData, nonce, messageKey);
// Check if decryption was successful // Check if decryption was successful
if (!decryptedData) { if (!decryptedData) {
throw new Error("Decryption failed"); throw new Error('Decryption failed');
} }
// Convert the decrypted Uint8Array back to a Base64 string // Convert the decrypted Uint8Array back to a Base64 string
return uint8ArrayToBase64(decryptedData); return uint8ArrayToBase64(decryptedData);
}; };
export const decryptGroupEncryptionWithSharingKey = async ({
data64EncryptedData,
key,
export const decryptGroupEncryptionWithSharingKey = async ({ data64EncryptedData, key }: any) => { }: any) => {
const allCombined = base64ToUint8Array(data64EncryptedData);
const allCombined = base64ToUint8Array(data64EncryptedData) const str = 'qortalGroupEncryptedData';
const str = "qortalGroupEncryptedData" const strEncoder = new TextEncoder();
const strEncoder = new TextEncoder() const strUint8Array = strEncoder.encode(str);
const strUint8Array = strEncoder.encode(str)
// Extract the nonce // Extract the nonce
const nonceStartPosition = strUint8Array.length const nonceStartPosition = strUint8Array.length;
const nonceEndPosition = nonceStartPosition + 24 // Nonce is 24 bytes const nonceEndPosition = nonceStartPosition + 24; // Nonce is 24 bytes
const nonce = allCombined.slice(nonceStartPosition, nonceEndPosition) const nonce = allCombined.slice(nonceStartPosition, nonceEndPosition);
// Extract the shared keyNonce // Extract the shared keyNonce
const keyNonceStartPosition = nonceEndPosition const keyNonceStartPosition = nonceEndPosition;
const keyNonceEndPosition = keyNonceStartPosition + 24 // Nonce is 24 bytes const keyNonceEndPosition = keyNonceStartPosition + 24; // Nonce is 24 bytes
const keyNonce = allCombined.slice(keyNonceStartPosition, keyNonceEndPosition) const keyNonce = allCombined.slice(
keyNonceStartPosition,
keyNonceEndPosition
);
// Extract the sender's public key // Extract the sender's public key
const senderPublicKeyStartPosition = keyNonceEndPosition const senderPublicKeyStartPosition = keyNonceEndPosition;
const senderPublicKeyEndPosition = senderPublicKeyStartPosition + 32 // Public keys are 32 bytes const senderPublicKeyEndPosition = senderPublicKeyStartPosition + 32; // Public keys are 32 bytes
// Calculate count first // Calculate count first
const countStartPosition = allCombined.length - 4 // 4 bytes before the end, since count is stored in Uint32 (4 bytes) const countStartPosition = allCombined.length - 4; // 4 bytes before the end, since count is stored in Uint32 (4 bytes)
const countArray = allCombined.slice(countStartPosition, countStartPosition + 4) const countArray = allCombined.slice(
const count = new Uint32Array(countArray.buffer)[0] countStartPosition,
countStartPosition + 4
);
const count = new Uint32Array(countArray.buffer)[0];
// Then use count to calculate encryptedData // Then use count to calculate encryptedData
const encryptedDataStartPosition = senderPublicKeyEndPosition // start position of encryptedData const encryptedDataStartPosition = senderPublicKeyEndPosition; // start position of encryptedData
const encryptedDataEndPosition = allCombined.length - ((count * (32 + 16)) + 4) const encryptedDataEndPosition = allCombined.length - (count * (32 + 16) + 4);
const encryptedData = allCombined.slice(encryptedDataStartPosition, encryptedDataEndPosition) const encryptedData = allCombined.slice(
encryptedDataStartPosition,
encryptedDataEndPosition
);
const symmetricKey = base64ToUint8Array(key); const symmetricKey = base64ToUint8Array(key);
// Decrypt the data using the nonce and messageKey // Decrypt the data using the nonce and messageKey
const decryptedData = nacl.secretbox.open(encryptedData, nonce, symmetricKey) const decryptedData = nacl.secretbox.open(encryptedData, nonce, symmetricKey);
// Check if decryption was successful // Check if decryption was successful
if (!decryptedData) { if (!decryptedData) {
throw new Error("Decryption failed"); throw new Error('Decryption failed');
} }
// Convert the decrypted Uint8Array back to a Base64 string // Convert the decrypted Uint8Array back to a Base64 string
return uint8ArrayToBase64(decryptedData); return uint8ArrayToBase64(decryptedData);
}; };
export function decryptGroupDataQortalRequest(data64EncryptedData, privateKey) {
const allCombined = base64ToUint8Array(data64EncryptedData);
export function decryptGroupDataQortalRequest(data64EncryptedData, privateKey) { const str = 'qortalGroupEncryptedData';
const allCombined = base64ToUint8Array(data64EncryptedData) const strEncoder = new TextEncoder();
const str = "qortalGroupEncryptedData" const strUint8Array = strEncoder.encode(str);
const strEncoder = new TextEncoder()
const strUint8Array = strEncoder.encode(str)
// Extract the nonce // Extract the nonce
const nonceStartPosition = strUint8Array.length const nonceStartPosition = strUint8Array.length;
const nonceEndPosition = nonceStartPosition + 24 // Nonce is 24 bytes const nonceEndPosition = nonceStartPosition + 24; // Nonce is 24 bytes
const nonce = allCombined.slice(nonceStartPosition, nonceEndPosition) const nonce = allCombined.slice(nonceStartPosition, nonceEndPosition);
// Extract the shared keyNonce // Extract the shared keyNonce
const keyNonceStartPosition = nonceEndPosition const keyNonceStartPosition = nonceEndPosition;
const keyNonceEndPosition = keyNonceStartPosition + 24 // Nonce is 24 bytes const keyNonceEndPosition = keyNonceStartPosition + 24; // Nonce is 24 bytes
const keyNonce = allCombined.slice(keyNonceStartPosition, keyNonceEndPosition) const keyNonce = allCombined.slice(
keyNonceStartPosition,
keyNonceEndPosition
);
// Extract the sender's public key // Extract the sender's public key
const senderPublicKeyStartPosition = keyNonceEndPosition const senderPublicKeyStartPosition = keyNonceEndPosition;
const senderPublicKeyEndPosition = senderPublicKeyStartPosition + 32 // Public keys are 32 bytes const senderPublicKeyEndPosition = senderPublicKeyStartPosition + 32; // Public keys are 32 bytes
const senderPublicKey = allCombined.slice(senderPublicKeyStartPosition, senderPublicKeyEndPosition) const senderPublicKey = allCombined.slice(
senderPublicKeyStartPosition,
senderPublicKeyEndPosition
);
// Calculate count first // Calculate count first
const countStartPosition = allCombined.length - 4 // 4 bytes before the end, since count is stored in Uint32 (4 bytes) const countStartPosition = allCombined.length - 4; // 4 bytes before the end, since count is stored in Uint32 (4 bytes)
const countArray = allCombined.slice(countStartPosition, countStartPosition + 4) const countArray = allCombined.slice(
const count = new Uint32Array(countArray.buffer)[0] countStartPosition,
countStartPosition + 4
);
const count = new Uint32Array(countArray.buffer)[0];
// Then use count to calculate encryptedData // Then use count to calculate encryptedData
const encryptedDataStartPosition = senderPublicKeyEndPosition // start position of encryptedData const encryptedDataStartPosition = senderPublicKeyEndPosition; // start position of encryptedData
const encryptedDataEndPosition = allCombined.length - ((count * (32 + 16)) + 4) const encryptedDataEndPosition = allCombined.length - (count * (32 + 16) + 4);
const encryptedData = allCombined.slice(encryptedDataStartPosition, encryptedDataEndPosition) const encryptedData = allCombined.slice(
encryptedDataStartPosition,
encryptedDataEndPosition
);
// Extract the encrypted keys // Extract the encrypted keys
// 32+16 = 48 // 32+16 = 48
const combinedKeys = allCombined.slice(encryptedDataEndPosition, encryptedDataEndPosition + (count * 48)) const combinedKeys = allCombined.slice(
encryptedDataEndPosition,
encryptedDataEndPosition + count * 48
);
if (!privateKey) { if (!privateKey) {
throw new Error("Unable to retrieve keys") throw new Error('Unable to retrieve keys');
} }
const decodedPrivateKey = Base58.decode(privateKey) const decodedPrivateKey = Base58.decode(privateKey);
const convertedPrivateKey = ed2curve.convertSecretKey(decodedPrivateKey) const convertedPrivateKey = ed2curve.convertSecretKey(decodedPrivateKey);
const convertedSenderPublicKey = ed2curve.convertPublicKey(senderPublicKey) const convertedSenderPublicKey = ed2curve.convertPublicKey(senderPublicKey);
const sharedSecret = new Uint8Array(32) const sharedSecret = new Uint8Array(32);
nacl.lowlevel.crypto_scalarmult(sharedSecret, convertedPrivateKey, convertedSenderPublicKey) nacl.lowlevel.crypto_scalarmult(
sharedSecret,
convertedPrivateKey,
convertedSenderPublicKey
);
for (let i = 0; i < count; i++) { for (let i = 0; i < count; i++) {
const encryptedKey = combinedKeys.slice(i * 48, (i + 1) * 48) const encryptedKey = combinedKeys.slice(i * 48, (i + 1) * 48);
// Decrypt the symmetric key. // Decrypt the symmetric key.
const decryptedKey = nacl.secretbox.open(encryptedKey, keyNonce, sharedSecret) const decryptedKey = nacl.secretbox.open(
encryptedKey,
keyNonce,
sharedSecret
);
// If decryption was successful, decryptedKey will not be null. // If decryption was successful, decryptedKey will not be null.
if (decryptedKey) { if (decryptedKey) {
// Decrypt the data using the symmetric key. // Decrypt the data using the symmetric key.
const decryptedData = nacl.secretbox.open(encryptedData, nonce, decryptedKey) const decryptedData = nacl.secretbox.open(
encryptedData,
nonce,
decryptedKey
);
// If decryption was successful, decryptedData will not be null. // If decryption was successful, decryptedData will not be null.
if (decryptedData) { if (decryptedData) {
return decryptedData return decryptedData;
} }
} }
} }
throw new Error("Unable to decrypt data") throw new Error('Unable to decrypt data');
} }
export function decryptGroupData(
export function decryptGroupData(data64EncryptedData: string, privateKey: string) { data64EncryptedData: string,
const allCombined = base64ToUint8Array(data64EncryptedData) privateKey: string
const str = "qortalGroupEncryptedData" ) {
const strEncoder = new TextEncoder() const allCombined = base64ToUint8Array(data64EncryptedData);
const strUint8Array = strEncoder.encode(str) const str = 'qortalGroupEncryptedData';
const strEncoder = new TextEncoder();
const strUint8Array = strEncoder.encode(str);
// Extract the nonce // Extract the nonce
const nonceStartPosition = strUint8Array.length const nonceStartPosition = strUint8Array.length;
const nonceEndPosition = nonceStartPosition + 24 // Nonce is 24 bytes const nonceEndPosition = nonceStartPosition + 24; // Nonce is 24 bytes
const nonce = allCombined.slice(nonceStartPosition, nonceEndPosition) const nonce = allCombined.slice(nonceStartPosition, nonceEndPosition);
// Extract the shared keyNonce // Extract the shared keyNonce
const keyNonceStartPosition = nonceEndPosition const keyNonceStartPosition = nonceEndPosition;
const keyNonceEndPosition = keyNonceStartPosition + 24 // Nonce is 24 bytes const keyNonceEndPosition = keyNonceStartPosition + 24; // Nonce is 24 bytes
const keyNonce = allCombined.slice(keyNonceStartPosition, keyNonceEndPosition) const keyNonce = allCombined.slice(
keyNonceStartPosition,
keyNonceEndPosition
);
// Extract the sender's public key // Extract the sender's public key
const senderPublicKeyStartPosition = keyNonceEndPosition const senderPublicKeyStartPosition = keyNonceEndPosition;
const senderPublicKeyEndPosition = senderPublicKeyStartPosition + 32 // Public keys are 32 bytes const senderPublicKeyEndPosition = senderPublicKeyStartPosition + 32; // Public keys are 32 bytes
const senderPublicKey = allCombined.slice(senderPublicKeyStartPosition, senderPublicKeyEndPosition) const senderPublicKey = allCombined.slice(
senderPublicKeyStartPosition,
senderPublicKeyEndPosition
);
// Calculate count first // Calculate count first
const countStartPosition = allCombined.length - 4 // 4 bytes before the end, since count is stored in Uint32 (4 bytes) const countStartPosition = allCombined.length - 4; // 4 bytes before the end, since count is stored in Uint32 (4 bytes)
const countArray = allCombined.slice(countStartPosition, countStartPosition + 4) const countArray = allCombined.slice(
const count = new Uint32Array(countArray.buffer)[0] countStartPosition,
countStartPosition + 4
);
const count = new Uint32Array(countArray.buffer)[0];
// Then use count to calculate encryptedData // Then use count to calculate encryptedData
const encryptedDataStartPosition = senderPublicKeyEndPosition // start position of encryptedData const encryptedDataStartPosition = senderPublicKeyEndPosition; // start position of encryptedData
const encryptedDataEndPosition = allCombined.length - ((count * (32 + 16)) + 4) const encryptedDataEndPosition = allCombined.length - (count * (32 + 16) + 4);
const encryptedData = allCombined.slice(encryptedDataStartPosition, encryptedDataEndPosition) const encryptedData = allCombined.slice(
encryptedDataStartPosition,
encryptedDataEndPosition
);
// Extract the encrypted keys // Extract the encrypted keys
// 32+16 = 48 // 32+16 = 48
const combinedKeys = allCombined.slice(encryptedDataEndPosition, encryptedDataEndPosition + (count * 48)) const combinedKeys = allCombined.slice(
encryptedDataEndPosition,
encryptedDataEndPosition + count * 48
);
if (!privateKey) { if (!privateKey) {
throw new Error("Unable to retrieve keys") throw new Error('Unable to retrieve keys');
} }
const decodedPrivateKey = Base58.decode(privateKey) const decodedPrivateKey = Base58.decode(privateKey);
const convertedPrivateKey = ed2curve.convertSecretKey(decodedPrivateKey) const convertedPrivateKey = ed2curve.convertSecretKey(decodedPrivateKey);
const convertedSenderPublicKey = ed2curve.convertPublicKey(senderPublicKey) const convertedSenderPublicKey = ed2curve.convertPublicKey(senderPublicKey);
const sharedSecret = new Uint8Array(32) const sharedSecret = new Uint8Array(32);
nacl.lowlevel.crypto_scalarmult(sharedSecret, convertedPrivateKey, convertedSenderPublicKey) nacl.lowlevel.crypto_scalarmult(
sharedSecret,
convertedPrivateKey,
convertedSenderPublicKey
);
for (let i = 0; i < count; i++) { for (let i = 0; i < count; i++) {
const encryptedKey = combinedKeys.slice(i * 48, (i + 1) * 48) const encryptedKey = combinedKeys.slice(i * 48, (i + 1) * 48);
// Decrypt the symmetric key. // Decrypt the symmetric key.
const decryptedKey = nacl.secretbox.open(encryptedKey, keyNonce, sharedSecret) const decryptedKey = nacl.secretbox.open(
encryptedKey,
keyNonce,
sharedSecret
);
// If decryption was successful, decryptedKey will not be null. // If decryption was successful, decryptedKey will not be null.
if (decryptedKey) { if (decryptedKey) {
// Decrypt the data using the symmetric key. // Decrypt the data using the symmetric key.
const decryptedData = nacl.secretbox.open(encryptedData, nonce, decryptedKey) const decryptedData = nacl.secretbox.open(
encryptedData,
nonce,
decryptedKey
);
// If decryption was successful, decryptedData will not be null. // If decryption was successful, decryptedData will not be null.
if (decryptedData) { if (decryptedData) {
return {decryptedData, count} return { decryptedData, count };
} }
} }
} }
throw new Error("Unable to decrypt data") throw new Error('Unable to decrypt data');
} }
export function uint8ArrayStartsWith(uint8Array, string) { export function uint8ArrayStartsWith(uint8Array, string) {
const stringEncoder = new TextEncoder() const stringEncoder = new TextEncoder();
const stringUint8Array = stringEncoder.encode(string) const stringUint8Array = stringEncoder.encode(string);
if (uint8Array.length < stringUint8Array.length) { if (uint8Array.length < stringUint8Array.length) {
return false return false;
} }
for (let i = 0; i < stringUint8Array.length; i++) { for (let i = 0; i < stringUint8Array.length; i++) {
if (uint8Array[i] !== stringUint8Array[i]) { if (uint8Array[i] !== stringUint8Array[i]) {
return false return false;
} }
} }
return true return true;
} }
export function decryptDeprecatedSingle(uint8Array, publicKey, privateKey) { export function decryptDeprecatedSingle(uint8Array, publicKey, privateKey) {
const combinedData = uint8Array const combinedData = uint8Array;
const str = "qortalEncryptedData" const str = 'qortalEncryptedData';
const strEncoder = new TextEncoder() const strEncoder = new TextEncoder();
const strUint8Array = strEncoder.encode(str) const strUint8Array = strEncoder.encode(str);
const strData = combinedData.slice(0, strUint8Array.length) const strData = combinedData.slice(0, strUint8Array.length);
const nonce = combinedData.slice(strUint8Array.length, strUint8Array.length + 24) const nonce = combinedData.slice(
const _encryptedData = combinedData.slice(strUint8Array.length + 24) strUint8Array.length,
strUint8Array.length + 24
);
const _encryptedData = combinedData.slice(strUint8Array.length + 24);
const _publicKey = window.parent.Base58.decode(publicKey) const _publicKey = window.parent.Base58.decode(publicKey);
if (!privateKey || !_publicKey) { if (!privateKey || !_publicKey) {
throw new Error("Unable to retrieve keys") throw new Error('Unable to retrieve keys');
} }
const convertedPrivateKey = ed2curve.convertSecretKey(privateKey) const convertedPrivateKey = ed2curve.convertSecretKey(privateKey);
const convertedPublicKey = ed2curve.convertPublicKey(_publicKey) const convertedPublicKey = ed2curve.convertPublicKey(_publicKey);
const sharedSecret = new Uint8Array(32) const sharedSecret = new Uint8Array(32);
nacl.lowlevel.crypto_scalarmult(sharedSecret, convertedPrivateKey, convertedPublicKey) nacl.lowlevel.crypto_scalarmult(
const _chatEncryptionSeed = new window.parent.Sha256().process(sharedSecret).finish().result sharedSecret,
const _decryptedData = nacl.secretbox.open(_encryptedData, nonce, _chatEncryptionSeed) convertedPrivateKey,
convertedPublicKey
);
const _chatEncryptionSeed = new window.parent.Sha256()
.process(sharedSecret)
.finish().result;
const _decryptedData = nacl.secretbox.open(
_encryptedData,
nonce,
_chatEncryptionSeed
);
if (!_decryptedData) { if (!_decryptedData) {
throw new Error("Unable to decrypt") throw new Error('Unable to decrypt');
} }
return uint8ArrayToBase64(_decryptedData) return uint8ArrayToBase64(_decryptedData);
} }

View File

@ -228,5 +228,5 @@ export const CustomLabel = styled(InputLabel)(({ theme }) => ({
fontFamily: 'Inter', fontFamily: 'Inter',
fontSize: '15px', fontSize: '15px',
fontWeight: 400, fontWeight: 400,
lineHeight: '12px', lineHeight: '24px',
})); }));