How do I convert this PHP code to Javascript?

Asked

Viewed 365 times

-1

I made this code in PHP and I need to use it in Javascript but I don’t even know how to start converting it:

$codigo_verificador = strtr(rtrim(base64_encode(bin2hex(openssl_random_pseudo_bytes(32))), '='), '+/', '-_');

$codigo_desafio = strtr(rtrim(base64_encode(hash('sha256', $codigo_verificador, true)), '='), '+/', '-_');

echo "Código verificador: {$codigo_verificador}";  
echo "Código desafio: {$codigo_desafio}";
  • 1

    You need to study both languages to understand the differences. anyway, a lot of php has not ready in javascript, will need to look for various solutions to convert this code

  • have you searched the site? should have answers to all this, check it out: https://answall.com/q/295491/57220

  • generate a token must be made from the "server side", so you need to do this in php, otherwise your code will not be safe, can be easily manipulated

2 answers

1


I managed to do, these two codes worked for me

TESTE4

const uuidv4 = require('uuid/v4');

let code = uuidv4()
console.log("Code: " + code);

let hexadecimal = CryptoJS.enc.Hex.parse(code)
console.log("Hexadecimal: " + hexadecimal);

let base64 = CryptoJS.enc.Base64.stringify(hexadecimal).replace(/[\/]/g, '_').replace(/[+]g, '-').replace(/[=]/g, '')
console.log("HexToBase64: " + base64);

let sha256 = CryptoJS.SHA256(base64)
console.log("Base64ToSHA256: " + sha256);

let sha256_base64 = CryptoJS.enc.Base64.stringify(sha256).replace(/[\/]/g, '_').replace(/[+]/g, '-').replace(/[=]/g, '')
console.log("Sha256toBase64: " + sha256_base64);

TESTE5

const randomize = require('randomatic');

let code1 = randomize(32)
console.log('Code: ' + code1);

let hexadecimal1 = CryptoJS.enc.Hex.parse(code1)
console.log('CodeToHex: ' + hexadecimal1);

let base641 = CryptoJS.enc.Base64.stringify(hexadecimal1).replace(/[\/]/g, '_').replace(/[+]/g, '-').replace(/[=]/g, '')
console.log('HexToBase64: ' + base641);

let sha2561 = CryptoJS.SHA256(base641)
console.log('Base64ToSHA256: ' + sha2561);

let sha256_base641 = CryptoJS.enc.Base64.stringify(sha2561).replace(/[\/]/g, '_').replace(/[+]/g, '-').replace(/[=]/g, '')
console.log('Sha256ToBase64: ' + sha256_base641);

0

Do you want to use the values of $codigo_checker and $codigo_desafio in a javascript code? Just throw the values in a Hidden input and capture them normally.

In html:

<input type='hidden' id='codigo_verificador' value='<?=$codigo_verificador;?>'/>
<input type='hidden' id='codigo_desafio' value='<?=$codigo_desafio;?>'/>

In javascript:

var codigo_verificador = document.querySelector('#codigo_verificador');
var codigo_desafio = document.querySelector('#codigo_desafio');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.