Usando Service Worker para cargar audio wavejs.js:200:25
Verificando configuración de audio:
Object { nonce: "Presente", url: "https://2upra.com/sample/jazzy-hammond-organ-sample/", origin: "https://2upra.com" }
wavejs.js:174:13
Iniciando carga de audio - PostID: 266762 wavejs.js:242:13
Content-Length obtenido: -1 wavejs.js:287:21
Chunk leído:
Object { done: false, value: Uint8Array(15649) }
wavejs.js:294:25
Procesando chunk:
Object { totalLength: 15649, chunkLength: 8208, dataLength: 15645 }
wavejs.js:344:21
Error en desencriptación de chunk: Error: El chunkLength no coincide con el tamaño de los datos encriptados
Chunk leído:
Object { done: false, value: Uint8Array(16379) }
wavejs.js:294:25
Procesando chunk:
Object { totalLength: 16379, chunkLength: 4093903636, dataLength: 16375 }
wavejs.js:344:21
Error en desencriptación de chunk: Error: El chunkLength no coincide con el tamaño de los datos encriptados
//Asi se incriptan los datos
function encryptChunk(chunk,iv, key)
{
try {
binary_key = hex2bin(key);binary_key === false) {
throw new Exception('Error al convertir la clave hexadecimal a binario');
}
chunk,
'AES-256-CBC',
iv
);
if (length_prefix = pack('N', strlen(final_data = encrypted;
// Obtener el nuevo IV (último bloque de texto cifrado)
encrypted, -16);
return array('data' => new_iv);
} catch (Exception e;
}
}
function audioStreamEnd(data)
{
resumen la parte donde se envia los chunk creo
if (defined('ENABLE_AUDIO_ENCRYPTION') && ENABLE_AUDIO_ENCRYPTION) {
iv = openssl_random_pseudo_bytes(16);
if (iv===false)thrownewException(′NosepudogenerarelIV′)Encryption−IV:′.base64encode(iv));
code
if (!isset($_ENV['AUDIOCLAVE'])) {
throw new Exception('Clave de encriptación no configurada');
}
$key = $_ENV['AUDIOCLAVE'];
if ($length <= $buffer_size) {
$chunk = fread($fp, $length);
$encrypted_chunk = encryptChunk($chunk, $iv, $key);
echo $encrypted_chunk;
} else {
// Para archivos grandes, procesar en chunks
while (!feof($fp) && $sent < $length) {
$remaining = $length - $sent;
$chunk_size = min($buffer_size, $remaining);
$chunk = fread($fp, $chunk_size);
if ($chunk === false) {
break;
}
// Encriptar el chunk y obtener el nuevo IV
$encrypt_result = encryptChunk($chunk, $iv, $key);
$encrypted_chunk = $encrypt_result['data'];
$iv = $encrypt_result['iv']; // Actualizar el IV para el próximo chunk
echo $encrypted_chunk;
$sent += strlen($chunk);
flush();
ob_flush();
}
}
}
const response = await fetch(finalAudioUrl, {
method: 'GET',
credentials: 'same-origin',
headers: {
'X-WP-Nonce': audioSettings.nonce,
'X-Requested-With': 'XMLHttpRequest',
Accept: 'audio/mpeg',
Range: 'bytes=0-'
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const reader = response.body.getReader();
const iv = response.headers.get('X-Encryption-IV');
if (!iv) {
throw new Error('No se recibió el IV en los encabezados de la respuesta');
}
const ivArray = Uint8Array.from(atob(iv), c => c.charCodeAt(0));
let currentIV = ivArray;
const contentLengthHeader = response.headers.get('Content-Length');
const contentLength = contentLengthHeader ? parseInt(contentLengthHeader) : -1;
console.log(`Content-Length obtenido: ${contentLength}`);
let decryptedChunks = [];
let receivedLength = 0;
while (true) {
const { done, value } = await reader.read();
console.log('Chunk leído:', { done, value });
if (done) {
console.log('Transmisión completa');
break;
}
if (value && value.length > 0) {
try {
// Desencriptar el chunk usando el currentIV
const decryptedChunk = await decryptAudioData(value, currentIV, audioSettings.key);
decryptedChunks.push(new Uint8Array(decryptedChunk));
// Obtener los datos encriptados
const encryptedData = value.subarray(4);
// Actualizar el IV para el siguiente chunk
if (encryptedData.byteLength >= 16) {
currentIV = encryptedData.subarray(encryptedData.byteLength - 16);
} else {
throw new Error('encryptedData es demasiado pequeño para obtener el IV');
}
receivedLength += value.length;
console.log(`Procesado ${receivedLength} de ${contentLength} bytes`);
} catch (error) {
console.error('Error desencriptando chunk:', error);
continue;
}
}
}
// Resto del código para combinar chunks y cargar el audio...
} catch (error) {
console.error('Error en loadAndPlayAudioStream:', error);
handleLoadError(error, retryCount, container);
}
}
async function decryptAudioData(value, ivArray, key) {
try {
// Crear DataView considerando el byteOffset y byteLength
const dataView = new DataView(value.buffer, value.byteOffset, value.byteLength);
code
// Leer el chunkLength
const chunkLength = dataView.getUint32(0, false); // Big-endian
// Obtener los datos encriptados
const encryptedData = value.subarray(4);
console.log('Procesando chunk:', {
totalLength: value.byteLength,
chunkLength: chunkLength,
dataLength: encryptedData.byteLength
});
// Verificar que chunkLength coincide con dataLength
if (chunkLength !== encryptedData.byteLength) {
throw new Error('El chunkLength no coincide con el tamaño de los datos encriptados');
}
// Convertir la clave de hex a Uint8Array si aún no lo has hecho
if (!window.cachedKeyArray) {
window.cachedKeyArray = new Uint8Array(key.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
}
const keyArray = window.cachedKeyArray;
// Importar la clave
const cryptoKey = await crypto.subtle.importKey(
'raw',
keyArray.buffer,
{ name: 'AES-CBC', length: 256 },
false,
['decrypt']
);
// Desencriptar chunk
const decryptedData = await crypto.subtle.decrypt(
{ name: 'AES-CBC', iv: ivArray },
cryptoKey,
encryptedData
);
return decryptedData;
} catch (error) {
console.error('Error en desencriptación de chunk:', error);
throw error;
}
}
El problema que estás enfrentando es común cuando trabajas con flujos de datos encriptados y flujos de lectura asíncronos como el ReadableStream de la API Fetch. El error se debe a que estás asumiendo que cada llamada a reader.read() te proporciona un chunk completo que incluye el prefijo de longitud y los datos encriptados, pero esto no siempre es cierto.
Explicación detallada del problema:
Cuando lees datos de un ReadableStream, los chunks que recibes no necesariamente coinciden con los chunks que enviaste desde el servidor. Esto significa que un chunk que produces en el servidor puede dividirse en varios chunks en el cliente, o varios chunks del servidor pueden combinarse en uno solo en el cliente. Por lo tanto, no puedes asumir que cada value que recibes en el bucle while(true) corresponde a un chunk encriptado completo.
Solución propuesta:
Necesitas implementar un búfer en el cliente para acumular los datos recibidos y procesarlos correctamente en función del protocolo que estás utilizando (en este caso, un prefijo de longitud de 4 bytes seguido de los datos encriptados). Aquí te muestro cómo puedes ajustar tu código en el cliente para manejar esto:
javascript
let buffer = new Uint8Array(0);
let receivedLength = 0;
while (true) {
const { done, value } = await reader.read();
console.log('Chunk leído:', { done, value });
if (done) {
console.log('Transmisión completa');
break;
}
if (value && value.length > 0) {
// Añadir los nuevos datos al buffer
let tmp = new Uint8Array(buffer.length + value.length);
tmp.set(buffer, 0);
tmp.set(value, buffer.length);
buffer = tmp;
receivedLength += value.length;
// Procesar el buffer
let offset = 0;
while (buffer.length - offset >= 4) {
// Leer el prefijo de longitud
const lengthView = new DataView(buffer.buffer, buffer.byteOffset + offset, 4);
const chunkLength = lengthView.getUint32(0, false); // Big-endian
// Verificar si tenemos suficientes datos para procesar el chunk
if (buffer.length - offset >= 4 + chunkLength) {
// Extraer los datos encriptados
const encryptedData = buffer.subarray(offset + 4, offset + 4 + chunkLength);
console.log('Procesando chunk:', {
totalLength: buffer.byteLength,
chunkLength: chunkLength,
dataLength: encryptedData.byteLength
});
try {
// Desencriptar el chunk
const decryptedData = await decryptAudioData(encryptedData, currentIV, audioSettings.key);
decryptedChunks.push(new Uint8Array(decryptedData));
// Actualizar el IV (últimos 16 bytes de encryptedData)
if (encryptedData.byteLength >= 16) {
currentIV = encryptedData.subarray(encryptedData.byteLength - 16);
} else {
throw new Error('encryptedData es demasiado pequeño para obtener el IV');
}
} catch (error) {
console.error('Error desencriptando chunk:', error);
throw error;
}
// Mover el offset más allá de este chunk
offset += 4 + chunkLength;
} else {
// No tenemos suficientes datos aún
break;
}
}
// Eliminar los datos procesados del buffer
if (offset > 0) {
buffer = buffer.subarray(offset);
}
console.log(`Procesado ${receivedLength} bytes`);
}
}
Ajustes en la función decryptAudioData:
Ahora, la función decryptAudioData recibirá directamente los datos encriptados sin el prefijo de longitud, por lo que puedes simplificarla:
javascript
async function decryptAudioData(encryptedData, ivArray, key) {
try {
// Convertir la clave hexadecimal a Uint8Array si aún no la has cacheado
if (!window.cachedKeyArray) {
window.cachedKeyArray = new Uint8Array(key.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
}
const keyArray = window.cachedKeyArray;
// Importar la clave
const cryptoKey = await crypto.subtle.importKey(
'raw',
keyArray.buffer,
{ name: 'AES-CBC', length: 256 },
false,
['decrypt']
);
// Desencriptar los datos
const decryptedData = await crypto.subtle.decrypt(
{ name: 'AES-CBC', iv: ivArray },
cryptoKey,
encryptedData
);
return decryptedData;
} catch (error) {
console.error('Error en desencriptación de chunk:', error);
throw error;
}
}
¿Por qué funciona esta solución?
La clave aquí es reconocer que los flujos de datos no preservan las fronteras de los chunks tal y como se envían desde el servidor. Al agregar un buffer y procesar los datos en base al prefijo de longitud, te aseguras de que siempre procesas chunks completos y encriptados correctamente, sin importar cómo lleguen los datos a través del stream.
Resumen:
No asumas que cada reader.read() te da un chunk completo.
Utiliza un buffer para acumular los datos y procesa los chunks basándote en el prefijo de longitud.
Ajusta tu función de desencriptación para trabajar con los datos encriptados específicos.
Con estos cambios, deberías poder resolver el error y procesar correctamente los datos encriptados que recibes del servidor.