4
1
mirror of https://github.com/Qortal/qortal-ui.git synced 2025-02-11 17:55:51 +00:00

clean up code

This commit is contained in:
Phillip 2023-05-12 23:09:15 +03:00
parent bc5031c194
commit 53a3e0e183
2 changed files with 22 additions and 64 deletions

View File

@ -103,8 +103,8 @@ export const encryptData = ({ data64, recipientPublicKey }) => {
} }
} }
export const encryptDataGroup = ({ data64, recipientPublicKeys }) => { export const encryptDataGroup = ({ data64, publicKeys }) => {
console.log({ recipientPublicKeys, data64 }) const publicKeysDuplicateFree = [...new Set(publicKeys)];
const Uint8ArrayData = base64ToUint8Array(data64) const Uint8ArrayData = base64ToUint8Array(data64)
if (!(Uint8ArrayData instanceof Uint8Array)) { if (!(Uint8ArrayData instanceof Uint8Array)) {
@ -121,15 +121,15 @@ export const encryptDataGroup = ({ data64, recipientPublicKeys }) => {
const messageKey = new Uint8Array(32); const messageKey = new Uint8Array(32);
window.crypto.getRandomValues(messageKey); window.crypto.getRandomValues(messageKey);
// Encrypt the message with the symmetric key.
const nonce = new Uint8Array(24); const nonce = new Uint8Array(24);
window.crypto.getRandomValues(nonce); window.crypto.getRandomValues(nonce);
// Encrypt the data with the symmetric key.
const encryptedData = nacl.secretbox(Uint8ArrayData, nonce, messageKey); const encryptedData = nacl.secretbox(Uint8ArrayData, nonce, messageKey);
console.log('front', { encryptedData })
// Encrypt the symmetric key for each recipient. // Encrypt the symmetric key for each recipient.
let encryptedKeys = []; let encryptedKeys = [];
recipientPublicKeys.forEach((recipientPublicKey) => { publicKeysDuplicateFree.forEach((recipientPublicKey) => {
const publicKeyUnit8Array = window.parent.Base58.decode(recipientPublicKey) const publicKeyUnit8Array = window.parent.Base58.decode(recipientPublicKey)
const convertedPrivateKey = ed2curve.convertSecretKey(privateKey) const convertedPrivateKey = ed2curve.convertSecretKey(privateKey)
@ -138,12 +138,12 @@ export const encryptDataGroup = ({ data64, recipientPublicKeys }) => {
const sharedSecret = new Uint8Array(32) const sharedSecret = new Uint8Array(32)
nacl.lowlevel.crypto_scalarmult(sharedSecret, convertedPrivateKey, convertedPublicKey) nacl.lowlevel.crypto_scalarmult(sharedSecret, convertedPrivateKey, convertedPublicKey)
// Encrypt the symmetric key with the shared secret.
const keyNonce = new Uint8Array(24); const keyNonce = new Uint8Array(24);
window.crypto.getRandomValues(keyNonce); window.crypto.getRandomValues(keyNonce);
const encryptedKey = nacl.secretbox(messageKey, keyNonce, sharedSecret);
console.log('100', { keyNonce, recipientPublicKey, encryptedKey }) // Encrypt the symmetric key with the shared secret.
const encryptedKey = nacl.secretbox(messageKey, keyNonce, sharedSecret);
encryptedKeys.push({ encryptedKeys.push({
recipientPublicKey, recipientPublicKey,
@ -155,7 +155,7 @@ export const encryptDataGroup = ({ data64, recipientPublicKeys }) => {
const str = "qortalEncryptedData"; const str = "qortalEncryptedData";
const strEncoder = new TextEncoder(); const strEncoder = new TextEncoder();
const strUint8Array = strEncoder.encode(str); const strUint8Array = strEncoder.encode(str);
console.log('hello4')
// 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 + encryptedData.length + 4; let combinedDataSize = strUint8Array.length + nonce.length + encryptedData.length + 4;
@ -172,30 +172,23 @@ export const encryptDataGroup = ({ data64, recipientPublicKeys }) => {
combinedData.set(strUint8Array); combinedData.set(strUint8Array);
combinedData.set(nonce, strUint8Array.length); combinedData.set(nonce, strUint8Array.length);
combinedData.set(encryptedData, strUint8Array.length + nonce.length); combinedData.set(encryptedData, strUint8Array.length + nonce.length);
console.log('encrypt start', strUint8Array.length + nonce.length)
console.log('encryptedLength2', encryptedData.length)
// Initialize offset for encryptedKeys // Initialize offset for encryptedKeys
let encryptedKeysOffset = strUint8Array.length + nonce.length + encryptedData.length; let encryptedKeysOffset = strUint8Array.length + nonce.length + encryptedData.length;
console.log('encrypt end', encryptedKeysOffset)
encryptedKeys.forEach((key) => { encryptedKeys.forEach((key) => {
combinedData.set(key.keyNonce, encryptedKeysOffset); combinedData.set(key.keyNonce, encryptedKeysOffset);
console.log('key.keyNonce', key.keyNonce.length)
encryptedKeysOffset += key.keyNonce.length; encryptedKeysOffset += key.keyNonce.length;
combinedData.set(key.encryptedKey, encryptedKeysOffset); combinedData.set(key.encryptedKey, encryptedKeysOffset);
console.log('key.encryptedKey', key.encryptedKey.length)
encryptedKeysOffset += key.encryptedKey.length; encryptedKeysOffset += key.encryptedKey.length;
}); });
const countArray = new Uint8Array(new Uint32Array([recipientPublicKeys.length]).buffer); const countArray = new Uint8Array(new Uint32Array([publicKeysDuplicateFree.length]).buffer);
console.log({ countArray })
combinedData.set(countArray, combinedData.length - 4); combinedData.set(countArray, combinedData.length - 4);
console.log('totalLength 2', combinedData.length)
const uint8arrayToData64 = uint8ArrayToBase64(combinedData) const uint8arrayToData64 = uint8ArrayToBase64(combinedData)
return uint8arrayToData64; return uint8arrayToData64;
} catch (error) { } catch (error) {
console.log({ error })
throw new Error("Error in encrypting data") throw new Error("Error in encrypting data")
} }
} }

View File

@ -625,7 +625,7 @@ class WebBrowser extends LitElement {
} }
case actions.DECRYPT_DATA_GROUP: { case actions.DECRYPT_DATA_GROUP: {
const requiredFields = ['encryptedData', 'publicKeys']; const requiredFields = ['encryptedData'];
const missingFields = []; const missingFields = [];
requiredFields.forEach((field) => { requiredFields.forEach((field) => {
@ -643,11 +643,9 @@ class WebBrowser extends LitElement {
break break
} }
const { encryptedData: data64EncryptedData, publicKeys } = data const { encryptedData: data64EncryptedData } = data
console.log({ publicKeys, data64EncryptedData })
try { try {
const allCombined = base64ToUint8Array(data64EncryptedData); const allCombined = base64ToUint8Array(data64EncryptedData);
console.log('total length', allCombined.length)
const str = "qortalEncryptedData"; const str = "qortalEncryptedData";
const strEncoder = new TextEncoder(); const strEncoder = new TextEncoder();
const strUint8Array = strEncoder.encode(str); const strUint8Array = strEncoder.encode(str);
@ -660,47 +658,35 @@ class WebBrowser extends LitElement {
// 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(countStartPosition, countStartPosition + 4);
console.log({ countArray })
const count = new Uint32Array(countArray.buffer)[0]; const count = new Uint32Array(countArray.buffer)[0];
console.log({ count })
// Then use count to calculate encryptedData // Then use count to calculate encryptedData
const encryptedDataStartPosition = nonceEndPosition; // start position of encryptedData const encryptedDataStartPosition = nonceEndPosition; // start position of encryptedData
console.log({ encryptedDataStartPosition })
const encryptedDataEndPosition = allCombined.length - ((count * (24 + 32 + 16)) + 4); const encryptedDataEndPosition = allCombined.length - ((count * (24 + 32 + 16)) + 4);
console.log({ encryptedDataEndPosition })
const encryptedData = allCombined.slice(encryptedDataStartPosition, encryptedDataEndPosition); const encryptedData = allCombined.slice(encryptedDataStartPosition, encryptedDataEndPosition);
console.log('back', { encryptedData })
console.log({ encryptedLength: encryptedData.length })
// Extract the encrypted keys // Extract the encrypted keys
const combinedKeys = allCombined.slice(encryptedDataEndPosition, encryptedDataEndPosition + (count * (24 + 48))); const combinedKeys = allCombined.slice(encryptedDataEndPosition, encryptedDataEndPosition + (count * (24 + 48)));
const privateKey = window.parent.reduxStore.getState().app.selectedAddress.keyPair.privateKey const privateKey = window.parent.reduxStore.getState().app.selectedAddress.keyPair.privateKey
const senderPublicKey = window.parent.Base58.decode(publicKeys[0]) // Assuming the sender's public key is the first one const publicKey = window.parent.reduxStore.getState().app.selectedAddress.keyPair.publicKey
if (!privateKey || !senderPublicKey) { if (!privateKey || !publicKey) {
data['error'] = "Unable to retrieve keys" data['error'] = "Unable to retrieve keys"
response = JSON.stringify(data); response = JSON.stringify(data);
break break
} }
const recipientPrivateKeyUint8Array = privateKey const convertedPrivateKey = ed2curve.convertSecretKey(privateKey)
const senderPublicKeyUint8Array = senderPublicKey const convertedPublicKey = ed2curve.convertPublicKey(publicKey)
const convertedPrivateKey = ed2curve.convertSecretKey(recipientPrivateKeyUint8Array)
const convertedPublicKey = ed2curve.convertPublicKey(senderPublicKeyUint8Array)
const sharedSecret = new Uint8Array(32) const sharedSecret = new Uint8Array(32)
nacl.lowlevel.crypto_scalarmult(sharedSecret, convertedPrivateKey, convertedPublicKey) nacl.lowlevel.crypto_scalarmult(sharedSecret, convertedPrivateKey, convertedPublicKey)
console.log({ sharedSecret })
for (let i = 0; i < count; i++) { for (let i = 0; i < count; i++) {
const keyNonce = combinedKeys.slice(i * (24 + 48), i * (24 + 48) + 24); const keyNonce = combinedKeys.slice(i * (24 + 48), i * (24 + 48) + 24);
const encryptedKey = combinedKeys.slice(i * (24 + 48) + 24, (i + 1) * (24 + 48)); const encryptedKey = combinedKeys.slice(i * (24 + 48) + 24, (i + 1) * (24 + 48));
console.log({ keyNonce, encryptedKey })
// Decrypt the symmetric key. // Decrypt the symmetric key.
const decryptedKey = nacl.secretbox.open(encryptedKey, keyNonce, sharedSecret); const decryptedKey = nacl.secretbox.open(encryptedKey, keyNonce, sharedSecret);
console.log({ decryptedKey })
// If decryption was successful, decryptedKey will not be null. // If decryption was successful, decryptedKey will not be null.
if (decryptedKey) { if (decryptedKey) {
@ -709,12 +695,8 @@ class WebBrowser extends LitElement {
// If decryption was successful, decryptedData will not be null. // If decryption was successful, decryptedData will not be null.
if (decryptedData) { if (decryptedData) {
console.log({ decryptedData })
const decryptedDataToBase64 = uint8ArrayToBase64(decryptedData) const decryptedDataToBase64 = uint8ArrayToBase64(decryptedData)
console.log({ decryptedDataToBase64 })
response = JSON.stringify(decryptedDataToBase64); response = JSON.stringify(decryptedDataToBase64);
break; break;
} }
} }
@ -952,6 +934,7 @@ class WebBrowser extends LitElement {
return; return;
case actions.PUBLISH_QDN_RESOURCE: { case actions.PUBLISH_QDN_RESOURCE: {
console.log({ data })
// optional fields: encrypt:boolean recipientPublicKey:string // optional fields: encrypt:boolean recipientPublicKey:string
const requiredFields = ['service', 'name']; const requiredFields = ['service', 'name'];
const missingFields = []; const missingFields = [];
@ -994,9 +977,9 @@ class WebBrowser extends LitElement {
identifier = 'default'; identifier = 'default';
} }
if (data.encrypt && !data.recipientPublicKey) { if (data.encrypt && (!data.publicKeys || (Array.isArray(data.publicKeys) && data.publicKeys.length === 0))) {
let data = {}; let data = {};
data['error'] = "Encrypting data requires the recipient's public key"; data['error'] = "Encrypting data requires public keys";
response = JSON.stringify(data); response = JSON.stringify(data);
break break
} }
@ -1007,28 +990,10 @@ class WebBrowser extends LitElement {
break break
} }
if (data.encrypt && (!data.type || data.type !== 'group')) { if (data.encrypt) {
try {
const encryptDataResponse = encryptData({
data64, recipientPublicKey: data.recipientPublicKey
})
if (encryptDataResponse.encryptedData) {
data64 = encryptDataResponse.encryptedData
}
} catch (error) {
const obj = {};
const errorMsg = error.message || 'Upload failed due to failed encryption';
obj['error'] = errorMsg;
response = JSON.stringify(obj);
break
}
}
if (data.encrypt && data.type && data.type === 'group') {
try { try {
const encryptDataResponse = encryptDataGroup({ const encryptDataResponse = encryptDataGroup({
data64, recipientPublicKeys: data.recipientPublicKeys data64, publicKeys: data.publicKeys
}) })
if (encryptDataResponse) { if (encryptDataResponse) {
data64 = encryptDataResponse data64 = encryptDataResponse