web3.utils.hexToAscii return junk data - javascript

this.web3.utils.hexToAscii('') return junk data like return oÚ©J$ìGðK[!Ä¿ÎßyVoÙ,©ù³Ì1ØõDcS{¸³)¼ àToken transfer101 insted of actual data "**0.0007 Token transfer 101 **".
Example:
this.web3.utils.hexToAscii('0x0000000000000000000000006fdaa94a8a24ec47f04b8b5b21c4bfcedf8c79560000000000000000000000006fd92ca99c1df9b3cc318bd8f54463537bb8b32900000000000000000000000000000000000000000000000000000000000002bc00000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000000e546f6b656e207472616e7366657200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000033130310000000000000000000000000000000000000000000000000000000000');
Actual behavior
return oÚ©J$ìGðK[!Ä¿ÎßyVoÙ,©ù³Ì1ØõDcS{¸³)¼ àToken transfer101
Expected behavior
0.0007 Token transfer 101

The input data is not hex representation of the expected string, that's why the hexToAscii() function returns unexpected output.
It works correctly for the actual hex-encoded string:
const decoded = web3.utils.hexToAscii("0x302E3030303720546F6B656E207472616E7366657220313031");
console.log(decoded);

Related

Convert Float32Array to base64 in javascript

There are many Q&A's about converting blobs or Uint8Array to base64. But I have been unable to find how to convert from 32-bit arrays to base64. Here is an attempt.
function p(msg) { console.log(msg) }
let wav1 = [0.1,0.2,0.3]
let wav = new Float32Array(wav1)
p(`Len array to encrypt=${wav.length}`)
let omsg = JSON.stringify({onset: { id: 'abc', cntr: 1234}, wav: atob(wav) })
p(omsg)
The atob gives:
Uncaught InvalidCharacterError: Failed to execute 'atob' on 'Window':
The string to be decoded is not correctly encoded."
What intermediate step is needed to allow proper encoding of the floats to base64 ? Note that I have also tried TweetNacl-util instead of atob this way:
nacl.util.encodeBase64(wav)
This results in the same error.
Update Using JSON.stringify directly converts each float element into its ascii equivalent - which bloats the datasize . For the above that is:
"0.10000000149011612,"1":0.20000000298023224,"2":0.30000001192092896
We are transferring large arrays so this is a suboptimal solution.
Update The crucial element of the solution in the accepted answer is using Float32Array(floats).buffer . I was unaware of the buffer attribute.
The problem with your current code is that nacl.util.encodeBase64() takes in either a string, Array, or Uint8Array. Since your input isn't an Array or Uint8Array, it assumes you want to pass it in as a string.
The solution, of course, is to encode it into a Uint8Array first, then encode the Uint8Array into base64. When you decode, first decode the base64 into a Uint8Array, then convert the Uint8Array back into your Float32Array. This can be done using JavaScript ArrayBuffer.
const floatSize = 4;
function floatArrayToBytes(floats) {
var output = floats.buffer; // Get the ArrayBuffer from the float array
return new Uint8Array(output); // Convert the ArrayBuffer to Uint8s.
}
function bytesToFloatArray(bytes) {
var output = bytes.buffer; // Get the ArrayBuffer from the Uint8Array.
return new Float32Array(output); // Convert the ArrayBuffer to floats.
}
var encoded = nacl.util.encodeBase64(floatArrayToBytes(wav)) // Encode
var decoded = bytesToFloatArray(nacl.util.decodeBase64(encoded)) // Decode
If you don't like functions, here's some one-liners!
var encoded = nacl.util.encodeBase64(new Uint8Array(wav.buffer)) // Encode
var decoded = new Float32Array(nacl.util.decodeBase64(encoded).buffer) // Decode

PHP Convert Simple 3 Line JavaScript to PHP Equivalent

I've been provided with a few lines of JavaScript that I need to convert to the PHP equivalent. Not being a JavaScript developer I'm struggling with this. Here's the JavaScript sample I've been provided:
const crypto = require('crypto')
const secret_in_hex = Buffer.from(secret, 'hex');
const hash = crypto.createHmac('sha512', secret_in_hex)
.update(body)
.digest('hex')
// Compare hash with the received X-Onfleet-Signature in raw bytes
The docs for the API I'm working with to setup a Webhook receiver in PHP mention:
Each webhook request contains a signature from Onfleet in X-Onfleet-Signature header. To authenticate the webhook request received on your webhook server, you will need to validate against this header. To validate against X-Onfleet-Signature, you will need to compare its value with an HMAC you have generated using the hexadecimal format of your webhook secrets and the full body of the webhook POST request in raw bytes.
I'm assuming I'll be using the hash_hmac function and possibly the bin2hex function but completely stumped at this point and appreciate if someone can show me the PHP equivalent of the above JavaScript (assuming there is one).
The simplest equivalent should be:
$secretInHex = hex2bin($secret);
$hash = hash_hmac('sha512', $body, $secretInHex);
You should note that hex2bin function does NOT convert a hexadecimal number to a binary number but it decodes a hexadecimally encoded binary string.
So the secret provided should already be a hexadecimal else hex2bin will throw an exception

Convert Bson to Json object

Crome developer tool show this
console.log('DATA*** ', data[0]._id);
error : DATA*** Object {_bsontype: "ObjectID", id: "YIä↵P¨H0"}
How I can convert it into normal JSON object?
What you are looking for is
JSON.stringify()
JSON.stringify(objectToSerialize)
You need to use JSON.stringify() and then JSON.parse() to convert bson to valid json.
const dataString = JSON.stringify(data[0]);
const parsed = JSON.parse(dataString);
console.log(parsed._id);
Other bson types may give you its associated representation in Canonical format. For example, if you used the decimal bsonType in your mongodb it will present it like so:
...(continuing from code block above)
console.log(parsed.aDecimalNumber); // { $numberDecimal: 1.00 }
you want to call the .tostring() function on the id field.
The objectId is held as a special type stored in hex to reduce size. You'll need to use the toString function to convert it to the 24 ascii char string
https://github.com/mongodb/js-bson/blob/1.0-branch/lib/bson/objectid.js#L171-L179
console.log('DATA*** ', data[0]._id.toString());

Parsing a JSON string in javascript

I encountered a weird behaviour of JSON.parse method in javscript.
If you pass it a string in quotes like - "\"I am a random string\""
Instead of throwing an error it will parse the string and return the same
var a = '"I am a random string"';
var b = JSON.parse(a); // no error, parsing is successful
console.log(b); // output "I am a random string"
I am wondering what could be the cause of this? Is a string in quotes considered a valid JSON object?
According to the JSON Specification, a JSON text is any serialized value. Any of the following value types is valid JSON:
Objects ({ })
Arrays ([ ])
Strings ("a")
Numbers (1)
true, false and null
Quoting directly from the grammar in the spec:
value = false / null / true / object / array / number / string
JSON.parse() can deserialize any kind of value listed above, not just Objects.

JavaScript. WebSocket server. Error during WebSocket handshake: Incorrect 'Sec-WebSocket-Accept' header value [duplicate]

I'm following rfc6455:
Concretely, if as in the example above, the |Sec-WebSocket-Key|
header field had the value "dGhlIHNhbXBsZSBub25jZQ==", the server
would concatenate the string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
to form the string "dGhlIHNhbXBsZSBub25jZQ==258EAFA5-E914-47DA-95CA-
C5AB0DC85B11". The server would then take the SHA-1 hash of this,
giving the value 0xb3 0x7a 0x4f 0x2c 0xc0 0x62 0x4f 0x16 0x90 0xf6
0x46 0x06 0xcf 0x38 0x59 0x45 0xb2 0xbe 0xc4 0xea. This value is
then base64-encoded (see Section 4 of [RFC4648]), to give the value
"s3pPLMBiTxaQ9kYGzzhZRbK+xOo=". This value would then be echoed in
the |Sec-WebSocket-Accept| header field.
and fail to generate the correct "Sec-WebSocket-Accept".
In order to understand the process I'm using online SHA1 hash and Base64 Encode.
The online SHA1 hash for "dGhlIHNhbXBsZSBub25jZQ==258EAFA5-E914-47DA-95CA-C5AB0DC85B11" give the correct result: "b37a4f2cc0624f1690f64606cf385945b2bec4ea" as described in rfc6455.
But The online Base64 Encode give me the wrong results "YjM3YTRmMmNjMDYyNGYxNjkwZjY0NjA2Y2YzODU5NDViMmJlYzRlYQ==" for input "b37a4f2cc0624f1690f64606cf385945b2bec4ea".
The result should be "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="
What am I doing wrong?
You need to base64-encode the raw sha1 digest.
You are encoding the hexadecimal string representation of the digest which is double the length.
Online tools work with text and don't work with raw binary data, that's why you are getting wrong results.
Python 2 example:
import hashlib, base64
h = hashlib.sha1("dGhlIHNhbXBsZSBub25jZQ==258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
print "hexdigest:", h.hexdigest() # hexadecimal string representation of the digest
print "digest:", h.digest() # raw binary digest
print
print "wrong result:", base64.b64encode(h.hexdigest())
print "right result:", base64.b64encode(h.digest())
This prints:
hexdigest: b37a4f2cc0624f1690f64606cf385945b2bec4ea
digest: ᄈzO,ÀbOミöFÏ8YEᄇᄒÄê
wrong result: YjM3YTRmMmNjMDYyNGYxNjkwZjY0NjA2Y2YzODU5NDViMmJlYzRlYQ==
right result: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Python 3 example:
import hashlib, base64
h = hashlib.sha1(b"dGhlIHNhbXBsZSBub25jZQ==258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
print("hexdigest:", h.hexdigest()) # hexadecimal string representation of the digest
print("digest:", h.digest()) # raw binary digest
print()
print("wrong result:", base64.b64encode(h.hexdigest().encode()).decode())
print("right result:", base64.b64encode(h.digest()).decode())
This prints:
hexdigest: b37a4f2cc0624f1690f64606cf385945b2bec4ea
digest: b'\xb3zO,\xc0bO\x16\x90\xf6F\x06\xcf8YE\xb2\xbe\xc4\xea'
wrong result: YjM3YTRmMmNjMDYyNGYxNjkwZjY0NjA2Y2YzODU5NDViMmJlYzRlYQ==
right result: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

Categories

Resources