У меня есть код для шифрования текста на 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
Как реализовать шифрование веб-криптографии k6 так же, как функция PHP openssl_encrypt ⇐ Php
Кемеровские программисты php общаются здесь
1764605295
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[i] = 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
);
Подробнее здесь: [url]https://stackoverflow.com/questions/78341127/how-to-implement-k6-webcrypto-encryption-same-way-as-php-openssl-encrypt-functio[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия