Как реализовать шифрование веб-криптографии k6 так же, как функция PHP openssl_encryptPhp

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Как реализовать шифрование веб-криптографии k6 так же, как функция PHP openssl_encrypt

Сообщение Anonymous »

У меня есть код для шифрования текста на PHP, он выглядит так:
$key = '1234aaaff80b56233525ac2355ac3456'; // something like this
$utf16Content = \mb_convert_encoding('Some text', 'UTF-16LE');
$cipher = 'aes-256-gcm';
$nonceLength = \openssl_cipher_iv_length($cipher);
$nonce = \openssl_random_pseudo_bytes($nonceLength);

$encryptedContent = \openssl_encrypt($utf16Content, $cipher, $key, $options=0, $nonce, $tag);

echo 'Nonce: '.\base64_encode($nonce);
echo 'Auth Tag: '.\base64_encode($tag);
echo 'Content: '.$encryptedContent;

Как я могу реализовать такое же поведение в JS webcrypto? (Мне это нужно для тестов k6) Я нашел документацию, но она мне не понятна.
На данный момент у меня есть такой код, но я не могу его успешно расшифровать, поэтому думаю, что-то не так.
const rawKey = Uint8Array.from(new String('1234aaaff80b56233525ac2355ac3456'), (x) => x.charCodeAt(0));

const key = await crypto.subtle.importKey(
'raw',
rawKey,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt']
);
const nonce = crypto.getRandomValues(new Uint8Array(12));

const encrypted = await crypto.subtle.encrypt({
name: 'AES-GCM',
iv: nonce,
tagLength: 128,
},
key,
stringToArrayBuffer('Some text')
);

const sentData = {};
sentData.content = b64encode(encrypted);
sentData.nonce = b64encode(nonce);
sentData.authTag = b64encode(GetTag(encrypted, 128));

function stringToArrayBuffer(str) {
const buf = new ArrayBuffer(str.length * 2);
const bufView = new Uint16Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView = str.charCodeAt(i);
}
return buf;
}

function GetTag(encrypted, tagLength) {
if (tagLength === void 0) tagLength = 128;
return encrypted.slice(encrypted.byteLength - ((tagLength + 7) >> 3))
}

Я думаю, что основная проблема заключается в создании правильного authTag и изменении String rawKey на ArrayBuffer.
Кстати, код дешифрования выглядит следующим образом (PHP):
// $content, $nonce, $authenticationTag - from PHP encryption script output
$content = \base64_decode($content, true);
$nonce = \base64_decode($nonce, true);
$authenticationTag = \base64_decode($authenticationTag, true);

$result = \openssl_decrypt(
$content,
'aes-256-gcm',
'1234aaaff80b56233525ac2355ac3456',
\OPENSSL_RAW_DATA,
$nonce,
$authenticationTag
);


Подробнее здесь: https://stackoverflow.com/questions/783 ... pt-functio
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»