VB equivalent of Node-Red Buffer.from? - javascript

I'll try to summarize the issue the best way I can. I recently purchased a dual interface board that has TCP communication capabilities. In order to get information from the board an array of bytes needs sent to the board in which it will respond with the desired information. In node red I have been able to send the array of bytes using a function and receive a response from the TCP module.
However I would like to use this in an application I am developing that is more user-friendly than node red. Unfortunately, no matter what I have tried I have not been able to receive a response from the device using Visual Basic.
In node red, the array looks something like this:
Msg.payload = Buffer.from([8,121,50,3,100)];
Without buffer.from the device would not respond. I have tried encoding the string in VB into a byte variable and sending via socket, but am having no luck. Any suggestions? Here is the VB code.
Imports System.Net
Public Class Form1
Dim TCPClientz As Sockets.TcpClient
Dim TCPClientStream As Sockets.NetworkStream
Private Sub SendBytesButton_Click(sender As Object, e As EventArgs) Handles SendBytesButton.Click
'Dim intcount As Integer
Dim sendbytes() As Byte = System.Text.Encoding.UTF8.GetBytes(bytestextbox.Text)
TCPClientz = New Sockets.TcpClient(ServerTextBox.Text, PortTextBox.Text) 'Device IP and Port are working. Changing port throws error.
TCPClientStream = TCPClientz.GetStream()
'intcount = TCPClientz.Client.Send(sendbytes)
TCPClientStream.Write(sendbytes, 0, sendbytes.Length)
If TCPClientStream.DataAvailable = True Then 'At this point, I NEVER have gotten the stream to indicate there is available data.
Dim rcvbytes(TCPClientz.ReceiveBufferSize) As Byte
TCPClientStream.Read(rcvbytes, 0, CInt(TCPClientz.ReceiveBufferSize))
replytextbox.Text = System.Text.Encoding.UTF8.GetString(rcvbytes)
End If
End Sub
Does anyone know of any way to capture the bytes being sent by NODE-RED? I can view the payload, but I don't believe this is a representation of the actual bytes being sent. I could try to pair this up with the BYTE array in VB to see if they match.

Related

How can i validate a field that is for a Certificate Signing Request is in the correct format and has a keylength of 2048

I have written an input form (in ServiceNow) for admins to request a new certificate via a Cert Authority integration. However prior to submission i want to validate the Certificate Signing request has the correct headers and a keylength of 2048.
Example of CSR:
-----BEGIN CERTIFICATE REQUEST-----
MIICpTCCAY0CAQAwYDEqMCgGCSqGSIb3DQEJARYbamFtZXN0b21saW5zb25AbmJu
Y28uY29tLmF1MSUwIwYDVQQDDBxTZXJ2aWNlTm93LlRlc3QuSnVseTIxLkxvY2Fs
MQswCQYDVQQGEwJBVTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKpd
VbZG3Ph+UdiOYh+zFqH6pIavANGytWcvEnloG/DboW+JxpWQBqmZqvOZgWnPyC06
wS4f/YpElLFX83/+jLc6Gt3B/QDgfxhGaVnurDx56RvTM1LQVfBZJ3l+OYUmAof+
YB25aRhKQ4krWvXGMUujoi5QSl9yNZlAIzgpjgJ7cRHcbUhlOdcQVz/WnC2dcWB3
H/vLPIzciODOrzwIq1lSJ3OkdOJJ23Ifu19e9ySJsWYoC28THm6Ub8Z9gHHlPTfO
im5UxZFBZjLkx/YphQNNqcMxFMCO/CDo1bZlggws61O2liPzC8LpGwkroYIxngoQ
5rbvm/uyG/HelAFZYT0CAwEAAaAAMA0GCSqGSIb3DQEBCwUAA4IBAQCouy3b62xV
Bu4Scd38HMgtaTCHOndutsuwNnYF6SpxdSTYYMVQIa+gHy3N4vpQ+lNboPlOhsQd
58Jt9iwnmYCR32d36FVmsIpu5xAwweQUBK5v/GIPx5yjY0k8bTFC3vJUsIxbClwC
UtUE5p7p+Ulm+4olk/+VYeKtvE+l+e89NQ4sBlOE5JVSulRsxLjRfQscvj/0Ln/7
7iZQxfgL/Vv1UUBiLfTEmfSyu5i7IomoAUBSJ9xipbh5OWolqHzIBmpQY504Es3X
Ojs9d6KwyCSu5S2yUoj98C+OidqkHXDSfwWQSCfWn1vCuTFQlFS5viYK2pzIjozE
71owCWT8RpGd
-----END CERTIFICATE REQUEST-----
I plan to write a quick client side script to validate the input, but i'm a little stumped on the syntax. Any help appreciated.
This will be very difficult to do up...
Checking the CSR headers is relatively straight forward... you can do something like the following in an onSubmit script
var totalString = g_form.getValue('fieldName').trim();
var headerString = totalString.slice(0, 35);
var encodedCertString = totalString.substring(35, totalString.length - 33);
var footerString = totalString.slice(totalString.length - 33);
var validCert = true;
validCert &= (headerString == '-----BEGIN CERTIFICATE REQUEST-----');
validCert &= (footerString == '-----END CERTIFICATE REQUEST-----');
if(!validCert){
g_form.addErrorMessage('CSR in field missing correct headers');
return false;
}
Where things get "interesting" is that what is between the headers and footer of the CSR is a Base64 encoded PKCS10 binary block of data. Writing a function to deal with binary data is generally beyond what you will want to do in a client side function... the public key itself is merely a portion of that PCKS10 binary package.. not the whole.. so there is no easy way to "decode" it to iterate through the raw binary bites to find the actual key and measure its bit length. Have a look at the PCKS10 binary package format here: https://en.wikipedia.org/wiki/Certificate_signing_request
Most folks that have online CSR decoders actually pass the input to OpenSSL and have it parse the request and report on all of the data that makes it up... For instance: https://redkestrel.co.uk/products/decoder/. You could do something similar but doing so would require a hackish/creative use of a custom MID Server script that you could call using a custom probe... Again.. not something that you would want to mess with within the bounds of a ServiceNow client script.

Java row websocket data transfer

So basically i have java ServerSocket connected with browser which has js websocket on it. After correct handshaking i'm reciving data in this cycle
while((d = in.read()) != -1) {
System.out.println(Integer.toString(d));
}
Client sends data with
socket.send(send_data.value);
Where send_data is an input element;
And when i send data repeatedly i always get different bytes, and what is most important - number of bytes is not divisible by 4.
Why is this happening? Should i use some ByteBuffer stuff or flush()?

How to build flatbuffers message with existing struct buffer in javascript

I'm sending an ack to a received message in Node.js server and I want to echo the messageId back to the client. Currently I'm parsing the messageId from a buffer to string and building the ack from the string. Parsing the id to string and back is unnecessary but I'm unable to build the ack directly with the stuct buffer.
This is how it works when messageid is passed in as a string.
function createAck(messageId) {
let builder = new flatbuffers.Builder;
const request = MyServer.MessageAck;
request.startMessageAck(builder);
request.addMessgeId(builder, createUUID(builder, messageId));
const requestMessage = request.endMessageAck(builder);
return builder.finish(requestMessage);
}
function createUUID(builder, messageId) {
let uuidBytes = new Uint8Array(uuidParse.parse(messageId));
let dataview = new DataView(uuidBytes.buffer);
return MyServer.UUID.createUUID(builder,
flatbuffers.Long.create(dataview.getInt32(0, true), dataview.getInt32(4, true)),
flatbuffers.Long.create(dataview.getInt32(8, true), dataview.getInt32(12, true)));
}
I would like to pass in the messageId as a buffer directly taken from the message with
request.addMessgeId(builder, messageId);
But I'm getting an error: 'FlatBuffers: struct must be serialized inline.'
Here is the struct:
struct UUID {
low_bytes: ulong;
high_bytes: ulong;
}
The error refers to the fact that structs must be stored in-line, i.e. their bytes must be written to the buffer in between startMessageAck and endMessageAck. You can't refer to a struct stored elsewhere.
You should be able to copy the existing struct without using the intermediate Uint8Array and DataView however, something along the lines of (not tested):
request.addMessgeId(builder, MyServer.UUID.createUUID(builder,
messageId.low_bytes(), messageId.high_bytes());
Assuming messageId is a reference to an incoming UUID struct, can't tell from your code.
Even better would be if you could copy the struct using the JS equivalent of C memcpy, but that would require some hackery directly on the ByteBuffer in the builder that the current API doesn't directly support, so is probably not worth it for just 2 fields.

Uploading/Downloading Byte Arrays with AngularJS and ASP.NET Web API

I have spent several days researching and working on a solution for uploading/downloading byte[]’s. I am close, but have one remaining issue that appears to be in my AngularJS code block.
There is a similar question on SO, but it has no responses. See https://stackoverflow.com/questions/23849665/web-api-accept-and-post-byte-array
Here is some background information to set the context before I state my problem.
I am attempting to create a general purpose client/server interface to upload and download byte[]’s, which are used as part of a proprietary server database.
I am using TypeScript, AngularJS, JavaScript, and Bootstrap CSS on the client to create a single page app (SPA).
I am using ASP.NET Web API/C# on the server.
The SPA is being developed to replace an existing product that was developed in Silverlight so it is constrained to existing system requirements. The SPA also needs to target a broad range of devices (mobile to desktop) and major OSs.
With the help of several online resources (listed below), I have gotten most of my code working. I am using an asynchronous multimedia formatter for byte[]’s from the Byte Rot link below.
http://byterot.blogspot.com/2012/04/aspnet-web-api-series-part-5.html
Returning binary file from controller in ASP.NET Web API
I am using a jpeg converted to a Uint8Array as my test case on the client.
The actual system byte arrays will contain mixed content compacted into predefined data packets. However, I need to be able to handle any valid byte array so an image is a valid test case.
The data is transmitted to the server correctly using the client and server code shown below AND the Byte Rot Formatter (NOT shown but available on their website).
I have verified that the jpeg is received properly on the server as a byte[] along with the string parameter metadata.
I have used Fiddler to verify that the correct response is sent back to the client.
The size is correct
The image is viewable in Fiddler.
My problem is that the server response in the Angular client code shown below is not correct.
By incorrect, I mean the wrong size (~10K versus ~27.5K) and it is not recognized as a valid value for the UintArray constructor. Visual Studio shows JFIF when I place the cursor over the returned “response” shown in the client code below, but there is no other visible indicator of the content.
/********************** Server Code ************************/
Added missing item to code after [FromBody]byte[]
public class ItemUploadController : ApiController{
[AcceptVerbs("Post")]
public HttpResponseMessage Upload(string var1, string var2, [FromBody]byte[] item){
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new MemoryStream(item);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
}
}
/***************** Example Client Code ********************/
The only thing that I have omitted from the code are the actual variable parameters.
$http({
url: 'api/ItemUpload/Upload',
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },// Added per Byte Rot blog...
params: {
// Other params here, including string metadata about uploads
var1: var1,
var2: var2
},
data: new Uint8Array(item),
// arrybuffer must be lowecase. Once changed, it fixed my problem.
responseType: 'arraybuffer',// Added per http://www.html5rocks.com/en/tutorials/file/xhr2/
transformRequest: [],
})
.success((response, status) => {
if (status === 200) {
// The response variable length is about 10K, whereas the correct Fiddler size is ~27.5K.
// The error that I receive here is that the constructor argument in invalid.
// My guess is that I am doing something incorrectly with the AngularJS code, but I
// have implemented everything that I have read about. Any thoughts???
var unsigned8Int = new Uint8Array(response);
// For the test case, I want to convert the byte array back to a base64 encoded string
// before verifying with the original source that was used to generate the byte[] upload.
var b64Encoded = btoa(String.fromCharCode.apply(null, unsigned8Int));
callback(b64Encoded);
}
})
.error((data, status) => {
console.log('[ERROR] Status Code:' + status);
});
/****************************************************************/
Any help or suggestions would be greatly appreciated.
Thanks...
Edited to include more diagnostic data
First, I used the angular.isArray function to determine that the response value is NOT an array, which I think it should be.
Second, I used the following code to interrogate the response, which appears to be an invisible string. The leading characters do not seem to correspond to any valid sequence in the image byte array code.
var buffer = new ArrayBuffer(response.length);
var data = new Uint8Array(buffer);
var len = data.length, i;
for (i = 0; i < len; i++) {
data[i] = response[i].charCodeAt(0);
}
Experiment Results
I ran an experiment by creating byte array values from 0 - 255 on the server, which I downloaded. The AngularJS client received the first 128 bytes correctly (i.e., 0,1,...,126,127), but the remaining values were 65535 in Internet Explorer 11, and 65533 in Chrome and Firefox. Fiddler shows that 256 values were sent over the network, but there are only 217 characters received in the AngularJS client code. If I only use 0-127 as the server values, everything seems to work. I have no idea what can cause this, but the client response seems more in line with signed bytes, which I do not think is possible.
Fiddler Hex data from the server shows 256 bytes with the values ranging from 00,01,...,EF,FF, which is correct. As I mentioned earlier, I can return an image and view it properly in Fiddler, so the Web API server interface works for both POST and GET.
I am trying vanilla XMLHttpRequest to see I can get that working outside of the AngularJS environment.
XMLHttpRequest Testing Update
I have been able to confirm that vanilla XMLHttpRequest works with the server for the GET and is able to return the correct byte codes and the test image.
The good news is that I can hack around AngularJS to get my system working, but the bad news is that I do not like doing this. I would prefer to stay with Angular for all my client-side server communication.
I am going to open up a separate issue on Stack Overflow that only deals with the GET byte[] issues that I am have with AngularJS. If I can get a resolution, I will update this issue with the solution for historical purposes to help others.
Update
Eric Eslinger on Google Groups sent me a small code segment highlighting that responseType should be "arraybuffer", all lower case. I updated the code block above to show the lowercase value and added a note.
Thanks...
I finally received a response from Eric Eslinger on Google Group. He pointed out that he uses
$http.get('http://example.com/bindata.jpg', {responseType: 'arraybuffer'}).
He mentioned that the camelcase was probably significant, which it is. Changed one character and the entire flow is working now.
All credit goes to Eric Eslinger.

Encode in Python and decrypt in Javascript

I've searched for this, there are lots of hits, but I can't find one that is neither complete (pulls all the bits together) nor says its a bad idea, use HTTP. I've tried lots of things based on the hits I've found, but I can't get it to work.
The target problem is to AES encrypt textual data at one place, send it to a web API where it is stored in a database, then retrieve from the database via another API and decode it in the browser. This is not for security in transmission, it is so that, if the originator and the receiver know the key and IV, then it can be stored without the server knowing what the real content is.
The originator code is python, and the web API is python, so to make life easier initially, I'm storing the content unencrypted in the database. I've done AES encrypt/decrypt in python before, so that's not an issue. What I'm trying to do is encrypt in python as the content comes out of the database, transmit it, then decrypt in javascript. I've been using the python 'from Crypto.Cipher import AES' code, and javascript CryptoJS implementation from code.google.com
I'm happy at this stage to write the key and the IV into the code, distribution isn't really a problem as the originator and the client browser are effectively the same system.
I've not added any code because I think it would be more trouble than its worth at this stage.
Thanks in advance!
OK, some code. On the server python(3) side:
text = 'This is a message'
key = 'This is a key123'
iv = 'This is an IV456'
text += (16 - len(text) % 16) * ' ' # Pad to 16 chars, spaces are OK here
aes = AES.new(key, AES.MODE_CBC, iv)
enc = base64.b64encode(aes.encrypt(text)).decode()
print(enc)
enc is passed along with other data, JSON encoded, as the response to an AJAX request. On the client javascript side:
enc = /* from JSON */ ;
console.log(enc) ;
key = 'This is a key123';
iv = 'This is an IV456';
text = CryptoJS.AES.decrypt(Base64.decode(enc), key,
{ iv: iv, mode: CryptoJS.mode.CBC })) ;
console.log(text)
The python print(enc) and the javascript console.log(env) are the same, so I know the b64'd encoded data is coming over OK. The console.log(text) (in Chrome) shows as
l.WordArray.t.extend.init { ... }'
and not 'This is a message'. So why not!
Solved, but another mystery
I used the code from this gist:
https://gist.github.com/andres-erbsen/1307675
But: this uses code from http://crypto-js.googlecode.com/files/... which is not what you get from the download at https://code.google.com/p/crypto-js/downloads/list. The gist code uses Crypto.xxxx names; the download code uses CryptoJS.xxxx names. The gist is 2 years old, has CryptoJS replaced Crypto maybe?

Categories