Best JavaScript code snippet using wpt
index.js
Source:index.js
1import crypto from 'crypto';2import fs from 'fs';3import helmet from "helmet";4import http from 'http';5import https from 'https';6import cors from 'cors';7import cron from 'node-cron';8import dotenv from 'dotenv';9import express from 'express';10import log4js from 'log4js';11import nedb from 'nedb-promises';12import path from 'path';13import randomstring from 'randomstring';14import str2ab from 'str2ab';1516import FSL from '@s1r-j/fido2server-lib';17const {18 AttestationCreationOptionsBuilder,19 AttestationExpectationBuilder,20 AttestationResponseVerifier,21 AttestationResponseParser,22 AssertionRequestOptionsBuilder,23 AssertionExpectationBuilder,24 AssertionResponseVerifier,25 AssertionResponseParser,26} = FSL;272829import RequestValidateUtil from './util/requestValidateUtil.js';30import MdsUtil from './util/mdsUtil.js';3132dotenv.config();3334const RP_ORIGIN = new URL(process.env.SCHEME + '://' + process.env.HOSTNAME + ':' + process.env.PORT);35const RP_ID = RP_ORIGIN.hostname;36const RP_NAME = process.env.RP_NAME || RP_ID;37const ALGS = (process.env.ALGS || '-7').split(',').map(a => Number(a));3839// log40log4js.configure({41 appenders: {42 fido2: {43 type: 'file',44 filename: process.env.LOG_FILE || './log/app.log',45 }46 },47 categories: {48 default: {49 appenders: ['fido2'],50 level: process.env.LOG_LEVEL || 'warn'51 }52 }53});54const logger = log4js.getLogger('fido2');5556// db57const datastore = nedb.create(process.env.DB_FILE || './data/database.db');5859// cron60if (cron.validate(process.env.DB_RESET)) {61 console.log(`Set DB reset cron: ${process.env.DB_RESET}`);62 cron.schedule(process.env.DB_RESET, () => {63 fs.writeFileSync(process.env.DB_FILE || './data/database.db', '');64 });65}66if (cron.validate(process.env.LOG_ROTATE)) {67 console.log(`Set log rotate cron: ${process.env.LOG_ROTATE}`);68 cron.schedule(process.env.LOG_ROTATE, () => {69 fs.writeFileSync(process.env.LOG_FILE || './log/app.log', '');70 });71}7273// FIDO metadata74let addonEntries = [];75if (process.env.FIDO_METADATA_DIR) {76 const fileNames = fs.readdirSync(process.env.FIDO_METADATA_DIR);77 addonEntries = fileNames.map(fn => {78 if (fn === '.gitkeep') {79 return [];80 }81 const filepath = path.resolve(process.env.FIDO_METADATA_DIR, fn);82 const stats = fs.lstatSync(filepath);83 if (!stats.isFile()) {84 return [];85 }86 const file = fs.readFileSync(filepath, 'utf-8');87 try {88 const json = JSON.parse(file);89 if (Array.isArray(json)) {90 return json;91 } else {92 return [json];93 }94 } catch (err) {95 console.log(`${fn} is not JSON file.`);96 return [];97 }98 }).flat();99}100const mdsUtil = new MdsUtil(addonEntries);101102const app = express();103app.use(express.json());104app.use(express.urlencoded({extended: true}));105app.use(helmet());106app.use(helmet.contentSecurityPolicy({107 directives: {108 'script-src': ["'self'", "'unsafe-inline'", "code.jquery.com"],109 }110}));111app.use(cors({112 "origin": "*",113 "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",114 "preflightContinue": false,115 "optionsSuccessStatus": 204116}))117118app.set("view engine", "ejs");119app.set("views", path.resolve('./views'));120121const options = {122 key: process.env.PRIV_KEY ? fs.readFileSync(path.resolve(process.env.PRIV_KEY)) : null, // './ssl/privkey.pem'123 cert: process.env.CERT ? fs.readFileSync(path.resolve(process.env.CERT)) : null, // './ssl/fullchain.pem'124};125126app.get('/hello', function (req, res) {127 // for test128 logger.info('/hello is called.');129 res.status(200).end('Hello, world.');130});131132app.get('/', function (req, res) {133 const data = {134 vendorName: RP_NAME,135 serverURL: RP_ORIGIN.origin,136 };137 res.render("index.ejs", data);138});139140app.post('/attestation/options', async (req, res) => {141 const requestId = randomstring.generate(10);142 logger.info({143 requestId,144 message: '/attestation/options is called.'145 });146 logger.trace({147 requestId,148 message: req.body149 });150151 try {152 RequestValidateUtil.attestationOptions(req);153154 let user = await datastore.findOne({155 type: 'user',156 username: req.body.username,157 });158 if (user == null) {159 const userId = randomstring.generate(10);160 await datastore.insert({161 type: 'user',162 userId,163 username: req.body.username,164 displayName: req.body.displayName,165 });166 user = await datastore.findOne({167 type: 'user',168 userId,169 });170 }171 const credentials = await datastore.find({172 type: 'credential',173 userId: user.userId,174 }).exec();175 const excludes = credentials.map(c => {176 return {177 type: 'public-key',178 id: str2ab.base64url2arraybuffer(c.credentialId),179 transports: c.transports,180 };181 });182183 const challenge = str2ab.buffer2arraybuffer(crypto.randomBytes(64));184 const options = new AttestationCreationOptionsBuilder({185 rp: {186 id: RP_ID,187 name: RP_NAME,188 },189 user: {190 id: str2ab.string2arraybuffer(user.userId),191 name: req.body.username,192 displayName: req.body.displayName,193 },194 challenge,195 pubKeyCredParams: ALGS.map(alg => {196 return {197 type: 'public-key',198 alg,199 };200 }),201 timeout: 60000, // 60 sec202 excludeCredentials: excludes,203 authenticatorSelection: {204 ...req.body.authenticatorSelection,205 residentKey: (req.body.authenticatorSelection != null && req.body.authenticatorSelection.requireResidentKey) ? 'required' : undefined,206 },207 attestation: req.body.attestation,208 }).buildEncode();209 await datastore.insert({210 type: 'challenge',211 challenge: str2ab.arraybuffer2base64url(challenge),212 userId: user.userId,213 path: 'attestation',214 });215 logger.trace({216 requestId,217 message: options218 });219220 res.status(200).json({221 ...options,222 extensions: {223 ...(req.body.extensions || {}),224 },225 status: 'ok',226 errorMessage: '',227 });228 } catch (err) {229 logger.error({230 requestId,231 message: err232 });233 res.status(500).json({234 status: 'failed',235 errorMessage: `${requestId} ${err.message}`,236 });237 }238});239240app.post('/attestation/result', async (req, res) => {241 const requestId = randomstring.generate(10);242 logger.info({243 requestId,244 message: '/attestation/result is called.',245 });246 logger.trace({247 requestId,248 message: req.body249 });250251 try {252 RequestValidateUtil.attestationResult(req);253254 const parsed = AttestationResponseParser.parse({255 id: req.body.id,256 response: {257 attestationObject: str2ab.base64url2arraybuffer(req.body.response.attestationObject),258 clientDataJSON: str2ab.base64url2arraybuffer(req.body.response.clientDataJSON),259 transports: req.body.response.transports,260 },261 type: req.body.type,262 });263 if (parsed.challenge == null) {264 throw new Error('cannot parse challenge');265 }266 const challengeRecord = await datastore.findOne({267 type: 'challenge',268 path: 'attestation',269 challenge: parsed.challenge.base64url,270 });271 let isSuccess = false;272 try {273 const {274 challenge,275 userId,276 } = challengeRecord;277 let useMetadataService = false;278 let mdsEntry = null;279 if (parsed.aaguid != null && parsed.aaguid.uuid != null && parsed.aaguid.uuid !== '00000000-0000-0000-0000-000000000000') {280 mdsEntry = await mdsUtil.findEntry(parsed.aaguid.uuid);281 if (mdsEntry != null) {282 useMetadataService = true;283 }284 }285 const expectation = new AttestationExpectationBuilder({286 challenge: str2ab.base64url2arraybuffer(challenge),287 origin: RP_ORIGIN.origin,288 rpId: RP_ID,289 algs: ALGS,290 useMetadataService,291 metadataEntry: mdsEntry,292 }).build();293294 const verifier = new AttestationResponseVerifier({295 id: req.body.id,296 response: {297 attestationObject: str2ab.base64url2arraybuffer(req.body.response.attestationObject),298 clientDataJSON: str2ab.base64url2arraybuffer(req.body.response.clientDataJSON),299 transports: req.body.response.transports,300 },301 type: req.body.type302 }, expectation);303 const result = await verifier.verify();304 logger.info({305 requestId,306 message: JSON.stringify(result, null, 2),307 });308 if (result.verification) {309 const aaguid = result.aaguid.uuid;310 if (aaguid !== '00000000-0000-0000-0000-000000000000') {311 const entry = await mdsUtil.findEntry(aaguid);312 await mdsUtil.verifyEntry(entry, 'sha256', result.attestationTypes || []);313 }314315 await datastore.insert({316 type: 'credential',317 credentialId: result.credentialId.base64url,318 credential: result.pem,319 signCount: result.signCount,320 aaguid: result.aaguid.uuid,321 transports: req.body.response.transports || [],322 userId,323 });324 await datastore.remove({325 type: 'challenge',326 challenge,327 });328 isSuccess = true;329 } else {330 isSuccess = false;331 }332 } catch (err) {333 isSuccess = false;334 throw err;335 }336337 if (isSuccess) {338 res.status(200).json({339 status: 'ok',340 errorMessage: '',341 });342 } else {343 throw new Error('Register is rejected.');344 }345 } catch (err) {346 logger.error({347 requestId,348 message: err349 });350 res.status(500).json({351 status: 'failed',352 errorMessage: `${requestId} ${err.message}`,353 });354 }355});356357app.post('/assertion/options', async (req, res) => {358 const requestId = randomstring.generate(10);359 logger.info({360 requestId,361 message:'/assertion/options is called.'362 });363 logger.trace({364 requestId,365 message: req.body366 });367368 try {369 RequestValidateUtil.assertionOptions(req);370371 const user = await datastore.findOne({372 type: 'user',373 username: req.body.username,374 });375 if (user == null) {376 throw new Error(`user is not found: ${req.body.username}`);377 }378 const credentials = await datastore.find({379 type: 'credential',380 userId: user.userId,381 }).exec();382383 const options = AssertionRequestOptionsBuilder.easyCreate({384 rpId: RP_ID,385 userVerification: req.body.userVerification,386 }).buildEncode();387388 options.allowCredentials = credentials.map(c => {389 return {390 type: 'public-key',391 id: c.credentialId,392 transports: c.transports || [],393 };394 });395 logger.info({396 requestId,397 message: options398 });399400 const challenge = options.challenge;401 await datastore.insert({402 type: 'challenge',403 challenge,404 path: 'assertion',405 userId: user.userId,406 userVerification: req.body.userVerification,407 });408409 res.status(200).json({410 ...options,411 extensions: {412 ...(req.body.extensions || {}),413 },414 status: 'ok',415 errorMessage: '',416 });417 } catch (err) {418 logger.error({419 requestId,420 message: err421 });422 res.status(500).json({423 status: 'failed',424 errorMessage: `${requestId} ${err.message}`,425 });426 }427});428429app.post('/assertion/result', async (req, res) => {430 const requestId = randomstring.generate(10);431 logger.info({432 requestId,433 message: '/assertion/result is called.'434 });435 logger.trace({436 requestId,437 message: req.body438 });439440 try {441 RequestValidateUtil.assertionResult(req);442443 const parsed = AssertionResponseParser.parse({444 id: req.body.id,445 response: {446 clientDataJSON: str2ab.base64url2arraybuffer(req.body.response.clientDataJSON),447 authenticatorData: str2ab.base64url2arraybuffer(req.body.response.authenticatorData),448 signature: str2ab.base64url2arraybuffer(req.body.response.signature),449 userHandle: req.body.response.userHandle != null ? str2ab.base64url2arraybuffer(req.body.response.userHandle) : undefined,450 },451 type: req.body.type,452 });453454 const challengeRecord = await datastore.findOne({455 type: 'challenge',456 challenge: parsed.challenge.base64url,457 path: 'assertion',458 }).exec();459 const {460 challenge,461 userId,462 userVerification,463 } = challengeRecord;464465 const credential = await datastore.findOne({466 type: 'credential',467 credentialId: parsed.credentialId.base64url,468 userId,469 });470 471 let flags = new Set();472 if (userVerification === 'required') {473 flags.add('UserVerified');474 }475 const expectation = new AssertionExpectationBuilder({476 credentialPublicKey: credential.credential,477 challenge: str2ab.base642arraybuffer(challenge),478 origin: RP_ORIGIN.origin,479 rpId: RP_ID,480 flags,481 storedSignCount: credential.signCount,482 strictSignCount: true,483 }).build();484485 let isSuccess = false;486 try {487488 const verifier = new AssertionResponseVerifier({489 id: req.body.id,490 response: {491 clientDataJSON: str2ab.base64url2arraybuffer(req.body.response.clientDataJSON),492 authenticatorData: str2ab.base64url2arraybuffer(req.body.response.authenticatorData),493 signature: str2ab.base64url2arraybuffer(req.body.response.signature),494 userHandle: req.body.response.userHandle != null ? str2ab.base64url2arraybuffer(req.body.response.userHandle) : undefined,495 },496 type: req.body.type,497 }, expectation);498 const result = await verifier.verify();499 logger.info({500 requestId,501 message: JSON.stringify(result, null, 2),502 });503 if (result.verification) {504 await datastore.update({505 type: 'credential',506 credentialId: credential.credentialId,507 userId,508 }, {509 $set: { signCount: result.signCount },510 }, {});511 await datastore.remove({512 type: 'challenge',513 challenge,514 });515 isSuccess = true;516 } else {517 isSuccess = false;518 }519 } catch (err) {520 isSuccess = false;521 throw err;522 }523524 if (isSuccess) {525 res.status(200).json({526 status: 'ok',527 errorMessage: '',528 }); 529 } else {530 throw new Error('Verification is failed.');531 }532 } catch (err) {533 logger.error({534 requestId,535 message: err536 });537 res.status(500).json({538 status: 'failed',539 errorMessage: `${requestId} ${err.message}`,540 });541 }542});543544let httpServer;545if (options.cert != null && options.key != null) {546 httpServer = https.createServer(options, app);547} else {548 httpServer = http.createServer(app);549}550const server = httpServer.listen(process.env.PORT, process.env.HOSTNAME, function() {551 const host = server.address().address;552 const port = server.address().port;553554 console.log('Server is listening at http://%s:%s', host, port);
...
server.js
Source:server.js
...44 i++;45 }46 return str;47 }48 function str2ab(str) {49 var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char50 var bufView = new Uint16Array(buf);51 for (var i=0, strLen=str.length; i<strLen; i++) {52 bufView[i] = str.charCodeAt(i);53 }54 return buf;55 }56 ws.on('message',function(message){57 var message=ab2str(message);58 if(message=="index"){ 59 index_clients.push(ws);60 reload();61 }62 else if(message==1 && game1==0){63 if(rooms[0]<2){64 rooms[0]++;65 if(rooms[0]==1) {66 ws.send(str2ab("Oczekiwanie na doÅÄ
czenie przeciwnika..."));67 ws.send(str2ab("style"));68 win1=0;69 board1 =70 [0,0,0,71 0,0,0,72 0,0,0];73 }74 if(rooms[0]==2){75 block1=1;76 reload();77 ws.send(str2ab("Twój przeciwnik już jest gotowy."));78 ws.send(str2ab("Oczekiwanie na ruch przeciwnika..."));79 ws.send(str2ab("style"));80 room1_clients.forEach(function e(client){81 if (client!=ws){82 client.send(str2ab("DoÅÄ
czyÅ przeciwnik."));83 client.send(str2ab("Twój ruch."));84 client.send(str2ab("style2"));85 }86 });87 game1=1;88 }89 room1_clients.push(ws);90 reload();91 } 92 }93 else if(message==2 && game2==0){94 if(rooms[1]<2){95 rooms[1]++;96 if(rooms[1]==1){97 ws.send(str2ab("Oczekiwanie na doÅÄ
czenie przeciwnika..."));98 ws.send(str2ab("style"));99 win2=0;100 board2 =101 [0,0,0,102 0,0,0,103 0,0,0];104 }105 if(rooms[1]==2){106 block2=1;107 reload();108 ws.send(str2ab("Twój przeciwnik już jest gotowy."));109 ws.send(str2ab("Oczekiwanie na ruch przeciwnika..."));110 ws.send(str2ab("style"));111 room2_clients.forEach(function e(client){112 if (client!=ws){113 client.send(str2ab("DoÅÄ
czyÅ przeciwnik."));114 client.send(str2ab("Twój ruch."));115 client.send(str2ab("style2"));116 }117 });118 game2=1;119 }120 room2_clients.push(ws);121 reload();122 }123 }124 else if(message==1 && game1==1){125 ws.send(str2ab(board1.toString()));126 rooms[0]++;127 room1_clients.push(ws);128 if (style==0){129 ws.send(str2ab("style2"));130 ws.send(str2ab("Twój ruch."));131 room1_clients.forEach(function e(client){132 if(client!=ws){133 client.send(str2ab("style"));134 client.send(str2ab("Oczekiwanie na ruch przeciwnika..."));135 }136 });137 }138 if (style==1){139 ws.send(str2ab("style"));140 ws.send(str2ab("Oczekiwanie na ruch przeciwnika..."));141 room1_clients.forEach(function e(client){142 if(client!=ws){143 client.send(str2ab("style2"));144 client.send(str2ab("Twój ruch."));145 }146 });147 }148 style=0;149 reload();150 }151 else if(message==2 && game1==1){152 ws.send(str2ab(board2.toString()));153 rooms[1]++;154 room2_clients.push(ws);155 if (style==0){156 ws.send(str2ab("style2"));157 ws.send(str2ab("Twój ruch."));158 room2_clients.forEach(function e(client){159 if (client!=ws){160 client.send(str2ab("style"));161 client.send(str2ab("Oczekiwanie na ruch przeciwnika..."));162 }163 });164 }165 if (style==1){166 ws.send(str2ab("style"));167 ws.send(str2ab("Oczekiwanie na ruch przeciwnika..."));168 room2_clients.forEach(function e(client){169 if(client!=ws){170 client.send(str2ab("style2"));171 client.send(str2ab("Twój ruch."));172 }173 });174 }175 style=0;176 reload();177 }178 else if(message=="escape"){179 closing();180 }181 else if(message=="style1"){182 style=1;183 }184 else if(message=="style0"){185 style=0;186 }187 else{188 for( var i = 0; i < room1_clients.length; i++){ 189 if ( room1_clients[i] === ws) {190 if (i==symbol[0]) board1[message[1]]=1;191 if (i==symbol[1]) board1[message[1]]=2;192 if(win1==0)winner1();193 room1_clients.forEach(function e(client){194 client.send(str2ab(board1.toString()));195 if(client!=ws){ 196 if(win1==0){197 client.send(str2ab("style2"));198 client.send(str2ab("Twój ruch."));199 }200 }201 }); 202 if (win1==0){203 ws.send(str2ab("style"));204 ws.send(str2ab("Oczekiwanie na ruch przeciwnika..."));205 }206 }207 }208 209 for( var i = 0; i < room2_clients.length; i++){ 210 if ( room2_clients[i] === ws) {211 if (i==symbol[2]) board2[message[1]]=1;212 if (i==symbol[3]) board2[message[1]]=2;213 if(win2==0)winner2();214 room2_clients.forEach(function e(client){215 client.send(str2ab(board2.toString())); 216 if(client!=ws && win2==0){ 217 client.send(str2ab("style2"));218 client.send(str2ab("Twój ruch."));219 }220 }); 221 if (win2==0){222 ws.send(str2ab("style"));223 ws.send(str2ab("Oczekiwanie na ruch przeciwnika..."));224 }225 }226 }227 }228 });229 230 ws.on('close',function(){ 231 closing();232 });233 234 function closing(){235 236 for( var i = 0; i < index_clients.length; i++){ 237 if ( index_clients[i] === ws) {238 index_clients.splice(i, 1); 239 }240 }241 for( var i = 0; i < room1_clients.length; i++){ 242 if ( room1_clients[i] === ws) {243 room1_clients.splice(i, 1); 244 if (i==0){245 var x = symbol[0];246 symbol[0]=symbol[1];247 symbol[1]=x;248 }249 rooms[0]--;250 251 room1_clients.forEach(function e(client){252 if(client!=ws)client.send(str2ab("Przeciwnik siÄ rozÅÄ
czyÅ!"));253 client.send(str2ab("style"));254 });255 if(rooms[0]==0){256 block1=0;257 game1=0;258 style=0;259 index_clients.forEach(function e(client){260 client.send(str2ab("unblock1"));261 });262 }263 reload(); 264 }265 }266 267 for( var i = 0; i < room2_clients.length; i++){ 268 if ( room2_clients[i] === ws) { 269 room2_clients.splice(i, 1); 270 if (i==0){271 var x = symbol[2];272 symbol[2]=symbol[3];273 symbol[3]=x;274 }275 rooms[1]--;276 277 room2_clients.forEach(function e(client){278 if(client!=ws)client.send(str2ab("Przeciwnik siÄ rozÅÄ
czyÅ!"));279 client.send(str2ab("style"));280 });281 if(rooms[1]==0){282 block2=0;283 game2=0;284 style=0;285 index_clients.forEach(function e(client){286 client.send(str2ab("unblock2"));287 });288 }289 reload();290 }291 }292 }293 function reload(){294 index_clients.forEach(function e(client){295 client.send(str2ab(rooms.toString()));296 if(block1==1)client.send(str2ab("block1"));297 if(block2==1)client.send(str2ab("block2"));298 });299 }300 function winner1(){301 winning.forEach(function(c){ 302 if(board1[c[0]] == board1[c[1]] && board1[c[1]] == board1[c[2]] && board1[c[1]] != "")303 {304 win1=1;305 game1=0;306 reload();307 room1_clients.forEach(function e(client){308 client.send(str2ab("style"));309 client.send(str2ab("GAME OVER"));310 });311 } 312 });313 }314 function winner2(){315 winning.forEach(function(c){ 316 if(board2[c[0]] == board2[c[1]] && board2[c[1]] == board2[c[2]] && board2[c[1]] != "")317 {318 win2=1;319 game2=0;320 reload();321 room2_clients.forEach(function e(client){322 client.send(str2ab("style"));323 client.send(str2ab("GAME OVER")); 324 });325 }326 });327 }...
crypto.js
Source:crypto.js
...6};7function ab2str(buf) {8 return String.fromCharCode.apply(null, new Uint8Array(buf));9}10function str2ab(str) {11 const buf = new ArrayBuffer(str.length);12 const bufView = new Uint8Array(buf);13 for (let i = 0, strLen = str.length; i < strLen; i++) {14 bufView[i] = str.charCodeAt(i);15 }16 return buf;17}18export async function generateIdentity () {19 return await crypto.subtle.generateKey(20 KEY_PAIR_PARAMS,21 true,22 ['sign', 'verify']23 );24}25export async function importB64Identity (b64keyPair) {26 const privateKey = await crypto.subtle.importKey(27 'pkcs8',28 str2ab(atob(b64keyPair.privateKey)),29 KEY_PAIR_PARAMS,30 false,31 ['sign'],32 );33 const publicKey = await crypto.subtle.importKey(34 'spki',35 str2ab(atob(b64keyPair.publicKey)),36 KEY_PAIR_PARAMS,37 false,38 ['verify'],39 );40 return { privateKey, publicKey };41}42export async function exportB64Identity (keyPair) {43 const privateKey = await crypto.subtle.exportKey('pkcs8', keyPair.privateKey)44 .then(buf => btoa(ab2str(buf)));45 const publicKey = await crypto.subtle.exportKey('spki', keyPair.publicKey)46 .then(buf => btoa(ab2str(buf)));47 return { privateKey, publicKey };48}49export async function exportPEMPublicKey (keyPair) {50 const { publicKey } = await exportB64Identity(keyPair);51 return `-----BEGIN PUBLIC KEY-----\n${publicKey}\n-----END PUBLIC KEY-----`;52}53export async function generateToken (_claim, privateKey) {54 const header = JSON.stringify({ alg: KEY_PAIR_PARAMS.hash, type: 'JWT' });55 const claim = JSON.stringify(_claim);56 let token = `${btoa(header)}.${btoa(claim)}`;57 const _signature = await crypto.subtle.sign(58 KEY_PAIR_PARAMS.name,59 privateKey,60 new TextEncoder().encode(token)61 );62 const signature = btoa(ab2str(_signature));63 token += `.${signature}`;64 return `Bearer ${token}`;65}66export async function generateEncryptionKey () {67 return await window.crypto.subtle.generateKey(68 { name: "AES-GCM", length: 128 },69 true,70 ["encrypt", "decrypt"]71 );72}73export async function exportEncryptionKey (key) {74 return (await window.crypto.subtle.exportKey("jwk", key)).k;75}76export async function importEncryptionKey (k) {77 return await window.crypto.subtle.importKey(78 "jwk",79 {80 k,81 alg: "A128GCM",82 ext: true,83 key_ops: ["encrypt", "decrypt"],84 kty: "oct",85 },86 { name: "AES-GCM", length: 128 },87 false, // extractable88 ["encrypt", "decrypt"]89 );90}91export async function encryptToB64 (plaintext, key) {92 const iv = window.crypto.getRandomValues(new Uint8Array(12));93 const ciphertext = await window.crypto.subtle.encrypt(94 { name: "AES-GCM", iv },95 key,96 str2ab(plaintext)97 );98 return {99 ciphertext: btoa(ab2str(ciphertext)),100 iv: btoa(ab2str(iv)),101 };102}103export async function decryptFromB64 ({ ciphertext, iv }, key) {104 const decrypted = await window.crypto.subtle.decrypt(105 { name: "AES-GCM", iv: str2ab(atob(iv)) },106 key,107 str2ab(atob(ciphertext))108 );109 return ab2str(decrypted);...
Using AI Code Generation
1var str = "Hello World";2var ab = wptools.str2ab(str);3var str2 = wptools.ab2str(ab);4console.log(str2);5var str = "Hello World";6var ab = window.str2ab(str);7var str2 = window.ab2str(ab);8console.log(str2);
Using AI Code Generation
1var str = "hello world";2var ab = new TextEncoder("utf-8").encode(str).buffer;3console.log(ab);4var str = "hello world";5var ab = new TextEncoder("utf-8").encode(str).buffer;6console.log(ab);7var str = "hello world";8var ab = new TextEncoder("utf-8").encode(str).buffer;9console.log(ab);10var str = "hello world";11var ab = new TextEncoder("utf-8").encode(str).buffer;12console.log(ab);13var str = "hello world";14var ab = new TextEncoder("utf-8").encode(str).buffer;15console.log(ab);16var str = "hello world";17var ab = new TextEncoder("utf-8").encode(str).buffer;18console.log(ab);19var str = "hello world";20var ab = new TextEncoder("utf-8").encode(str).buffer;21console.log(ab);22var str = "hello world";23var ab = new TextEncoder("utf-8").encode(str).buffer;24console.log(ab);25var str = "hello world";26var ab = new TextEncoder("utf-8").encode(str).buffer;27console.log(ab);28var str = "hello world";29var ab = new TextEncoder("utf-8").encode(str).buffer;30console.log(ab);31var str = "hello world";32var ab = new TextEncoder("utf-8").encode(str).buffer;33console.log(ab);34var str = "hello world";35var ab = new TextEncoder("utf-8").encode(str).buffer;36console.log(ab);
Using AI Code Generation
1var ab = str2ab('Hello World!');2var str = ab2str(ab);3var str2ab = function(str) {4 var bufView = new Uint16Array(buf);5 for (var i = 0, strLen = str.length; i < strLen; i++) {6 bufView[i] = str.charCodeAt(i);7 }8 return buf;9};10var ab2str = function(buf) {11 return String.fromCharCode.apply(null, new Uint16Array(buf));12};13var ab = str2ab('Hello World!');14var str = ab2str(ab);15var str2ab = function(str) {16 var bufView = new Uint16Array(buf);17 for (var i = 0, strLen = str.length; i < strLen; i++) {18 bufView[i] = str.charCodeAt(i);19 }20 return buf;21};22var ab2str = function(buf) {23 return String.fromCharCode.apply(null, new Uint16Array(buf));24};25var ab = str2ab('Hello World!');26var str = ab2str(ab);27var str2ab = function(str)
Using AI Code Generation
1const wptools = require('wp-tools');2const str = 'some string';3const ab = wptools.str2ab(str);4const dec = wptools.ab2str(ab);5console.log(dec);6 var wptools = require('wp-tools');7 var str = 'some string';8 var ab = wptools.str2ab(str);9 var dec = wptools.ab2str(ab);10 console.log(dec);11 require 'wp-tools.php';12 $str = 'some string';13 $ab = wptools\str2ab($str);14 $dec = wptools\ab2str($ab);15 echo $dec;16 require 'wp-tools.php';17 $str = 'some string';18 $ab = wptools\str2ab($str);19 $dec = wptools\ab2str($ab);20 echo $dec;21 require 'wp-tools.php';22 $str = 'some string';23 $ab = wptools\str2ab($str);24 $dec = wptools\ab2str($ab);25 echo $dec;26 require 'wp-tools.php';27 $str = 'some string';28 $ab = wptools\str2ab($str);29 $dec = wptools\ab2str($ab);30 echo $dec;31 require 'wp-tools.php';32 $str = 'some string';33 $ab = wptools\str2ab($str);34 $dec = wptools\ab2str($ab);35 echo $dec;
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!