How to encode a string into windows-1251 charset? - dart

How can I encode a string into windows-1251 charset?
I'm going to post a form data into a backend, which internaly uses windows-1251, so I need to encode a string properly so that the message will be readable in the backend.
Here's how I send it
final codec = const Windows1251Codec(allowInvalid: false);
final encoded = codec.encode(message);
print('${codec.name}: encode "$message" to "$encoded"');
Response r = await Requests.post('http://abackend.com/page.php?action=send',
body: {'body': encoded},
bodyEncoding: RequestBodyEncoding.FormURLEncoded
);
console:
I/flutter ( 7423): windows-1251: encode "привет" to "[239, 240, 232,
226, 229, 242]"

There is a package that can do this called enough_convert.
Usage example:
import 'package:enough_convert/enough_convert.dart';
void main() {
final codec = const Windows1251Codec(allowInvalid: false);
final input = 'To encode input';
final encoded = codec.encode(input);
}

Related

rsocket net readerIndex exceeds writerIndex

On websocket connection between .net and spring boot rsocket I am trying to encode the routing header to the quotes endpoint like this:
int routeSize = 6;
string hexValue = routeSize.ToString("X");
metaData = hexValue + "quotes";
I don't think this is correct. The entire net client code is
var client = new RSocketClient(new WebSocketTransport("ws://127.0.0.1:7000/"));
await client.ConnectAsync(new RSocketOptions()
{
InitialRequestSize = 3,
DataMimeType = "application/json",
MetadataMimeType = "message/x.rsocket.routing.v0"
});
String json = {\"myQuote\":\"1234\"}
int routeSize = 6;
string hexValue = routeSize.ToString("X");
metaData = hexValue + "quotes";
var stringclient = new RSocketClient.ForStrings(client);
await stringclient.RequestStream(json, metaData)
.ForEachAsync((result) =>
{
Console.WriteLine($"Result ===> {result}");
});
and this produces the error
0001 Error {000}: [00000201] readerIndex(1) + length(54) exceeds writerIndex(7): UnpooledSlicedByteBuf(ridx: 1, widx: 7, cap: 7/7, unwrapped: PooledUnsafeDirectByteBuf(ridx: 0, widx: 281, cap: 281))
As related to RSocket Net client request stream routing metadata to spring boot #MessageMapping routes what's required is the C# equivalent of JavaScript String.fromCharCode(route.length) + route;
The answer was to use a default encoding to get a byte[] of the route name size as integer 6 and then add the length of the route name in bytes followed by the route, passing the string as metaData according to https://github.com/rsocket/rsocket/blob/master/Extensions/Routing.md
byte[] intBytes = BitConverter.GetBytes(6);
string stringBytes = Encoding.Default.GetString(intBytes, 0, 1);
metaData = stringBytes + "quotes";

How can I get a file checksum in Deno?

Just starting with Deno, I am trying to figure out how to calculate a binary file checksum. It seems to me that the problem is not with the methods provided by the hash module of the standard library, but with the file streaming method and/or the type of the chunks feeding the hash.update method.
I have been trying a few alternatives, related to file opening and chunk types,with no success. A simple example is in the following:
import {createHash} from "https://deno.land/std#0.80.0/hash/mod.ts";
const file= new File(["my_big_folder.tar.gz"], "./my_big_folder.tar.gz");
const iterator = file.stream() .getIterator();
const hash = createHash("md5");
for await( let chunk of iterator){
hash.update(chunk);
}
console.log(hash.toString()); //b35edd0be7acc21cae8490a17c545928
This code compiles and runs with no errors, pity that the result is different from what I get running the functions of the crypto module provided by node and the md5sum provided by linux coreutils. Any suggestion ?
nodejs code:
const crypto = require('crypto');
const fs = require('fs');
const hash = crypto.createHash('md5');
const file = './my_big_folder.tar.gz';
const stream = fs.ReadStream(file);
stream.on('data', data=> { hash.update(data); });
stream.on('end', ()=> {
console.log(hash.digest('hex')); //c18f5eac67656328f7c4ec5d0ef5b96f
});
The same result in bash:
$ md5sum ./my_big_folder.tar.gz
$ c18f5eac67656328f7c4ec5d0ef5b96f ./my_big_folder.tar.gz
on Windows 10 this can be used:
CertUtil -hashfile ./my_big_folder.tar.gz md5
The File API isn't used to read a File in Deno, to do that you need to use the Deno.open API and then turn it into an iterable like this
import {createHash} from "https://deno.land/std#0.80.0/hash/mod.ts";
const hash = createHash("md5");
const file = await Deno.open(new URL(
"./BigFile.tar.gz",
import.meta.url, //This is needed cause JavaScript paths are relative to main script not current file
));
for await (const chunk of Deno.iter(file)) {
hash.update(chunk);
}
console.log(hash.toString());
Deno.close(file.rid);
import { crypto, toHashString } from 'https://deno.land/std#0.176.0/crypto/mod.ts';
const getFileBuffer = (filePath: string) => {
const file = Deno.openSync(filePath);
const buf = new Uint8Array(file.statSync().size);
file.readSync(buf);
file.close();
return buf;
};
const getMd5OfBuffer = (data: BufferSource) => toHashString(crypto.subtle.digestSync('MD5', data));
export const getFileMd5 = (filePath: string) => getMd5OfBuffer(getFileBuffer(filePath));

Convert Datagram Data To String HEX

I'm Listening To UDP 6000 port and I want to convert incoming packages to Hex String
I searched but nothing found
Here is my code
import 'dart:io';
import 'package:udp/udp.dart';
main() async {
var sender = await UDP.bind(Endpoint.loopback(port: Port(42)));
var dataLength = await sender.send(
"Hello World!".codeUnits, Endpoint.broadcast(port: Port(21)));
stdout.write("${dataLength} bytes sent.");
var receiver =
await UDP.bind(Endpoint.unicast(InternetAddress.anyIPv4, Port(6000)));
await receiver.listen((datagram) {
print(datagram.data);
}, Duration(seconds: 200));
sender.close();
receiver.close();
}
#
my incoming package is like this:
[104, 101, 108, 108, 111]
I want to Convert to this
68656c6c6f
thanks
You can use the toRadixString to convert to values to hex, and the map the list.
var hex = datagram.data.map((e) => e.toRadixString(16));
print(hex);

Make picture from base64 on client-side

How to make a picture from a base64-string to send it to server by using HttpRequest.request?
For example, I have the following base64-string:
'data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
Instead of sending it I would like to post a jpeg to server? Is it possible?
Convert Base64 to bytes
How to native convert string -> base64 and base64 -> string
Upload binary as image
Dart how to upload image
EDIT
(this is the server part, I have to look for the client part)
Client code:
var request = new HttpRequest()
..open("POST", 'http://yourdomain.com/yourservice')
..overrideMimeType("image/your-imagetype") // might be that this doesn't work than use the next line
..setRequestHeader("Content-Type", "image/your-imagetype")
..onProgress.listen((e) => ...);
request
..onReadyStateChange.listen((e) => ...)
..onLoad.listen((e) => ...)
..send(yourBinaryDataAsUint8List);
Convert to image:
I think you need to create a dataURL like show here How to upload a file in Dart?
and then use the created dataUrl as src in code like shown here How to load an image in Dart
see also Base64 png data to html5 canvas as #DanFromGermany mentioned in his comment on the question.
It may be necessary to convert List to Uint8List in between.
Please add a comment if you need more information.
I like decoding on server-side, but anyways.
Basically you just split a text you got from canvas.toDataUrl(), convert the Base64 text to binary data, then send it to server. Use "CryptoUtils" in "crypto" library to treat Base64. I haven't tested with any proper http server, but this code should work.
// Draw an on-memory image.
final CanvasElement canvas = document.createElement('canvas');
canvas.width = 256;
canvas.height = 256;
final CanvasRenderingContext2D context = canvas.getContext('2d');
final CanvasGradient gradient = context.createLinearGradient(0, 0, 0, canvas.height);
gradient.addColorStop(0, "#1e4877");
gradient.addColorStop(0.5, "#4584b4");
context.fillStyle = gradient;
context.fillRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(10, 10);
context.lineTo(240, 240);
context.lineWidth = 10;
context.strokeStyle = '#ff0000';
context.stroke();
// Convert the image to data url
final String dataUrl = canvas.toDataUrl('image/jpeg');
final String base64Text = dataUrl.split(',')[1];
final Uint8ClampedList base64Data = new Uint8ClampedList.fromList(
CryptoUtils.base64StringToBytes(base64Text));
// Now send the base64 encoded data to the server.
final HttpRequest request = new HttpRequest();
request
..open("POST", 'http://yourdomain.com/postservice')
..onReadyStateChange.listen((_) {
if (request.readyState == HttpRequest.DONE &&
(request.status == 200 || request.status == 0)) {
// data saved OK.
print("onReadyStateChange: " + request.responseText); // output the response from the server
}
})
..onError.listen((_) {
print("onError: " + _.toString());
})
..send(base64Data);
I posted a complete snippet here. https://gist.github.com/hyamamoto/9391477
I found the Blob conversion part not to be working (anymore?).
The code from here does work:
Blob createImageBlob(String dataUri) {
String byteString = window.atob(dataUri.split(',')[1]);
String mimeString = dataUri.split(',')[0].split(':')[1].split(';')[0];
Uint8List arrayBuffer = new Uint8List(byteString.length);
Uint8List dataArray = new Uint8List.view(arrayBuffer.buffer);
for (var i = 0; i < byteString.length; i++) {
dataArray[i] = byteString.codeUnitAt(i);
}
Blob blob = new Blob([arrayBuffer], mimeString);
return blob;
}

Blackberry MD5 authentication with HTTP Post

I need to send to a server in POST an email (String) and a password (MD5 hash in byte[]).
Below how I get my MD5 hash where "password" is a String (what the user enter):
byte[] passMD5 = Crypto.encodeStringMD5(password);
And the function:
public static byte[] encodeStringMD5(String s) throws Exception {
byte[] bytes = s.getBytes();
MD5Digest digest = new MD5Digest();
digest.update(bytes, 0, bytes.length);
int length = digest.getDigestLength();
byte[] md5 = new byte[length];
digest.getDigest(md5, 0, true);
return md5;
}
So "passMD5" should be an MD5 hash in bytes of my string value "password", right?
Then I need to send the information through HTTP POST to an URL and read the result (XML). See below the rest of the code:
readURL(urlTemplate, email, passMD5);
Where urlTemplate is a String like "http://www.domain.com/myfile.aspx?action=login&enc=1", email a String and password the MD5 hash in bytes.
The readURL below:
private void readURL(String url, String email, byte[] pass) throws IOException {
HttpConnection conn = null;
InputStream in = null;
OutputStream os = null;
byte dataBytes[];
try {
URLEncodedPostData data = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, false);
data.append("email", email);
data.append("pass", pass.toString());
dataBytes = data.getBytes();
conn = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Type", data.getContentType());
conn.setRequestProperty("Content-Length", Integer.toString(dataBytes.length));
os = conn.openOutputStream();
os.write(dataBytes);
os.flush();
os.close();
in = conn.openInputStream();
verifyLogin(getLoginContent(in));
} catch (IOException e) {
} catch (IllegalArgumentException e) {
} finally {
ConnectionUtil.close(conn, in);
ConnectionUtil.close(conn, os);
}
}
So right now the MD hash of the password in transformed to a String in order to be added to the data.append() function that only takes String parameters...
I think because of this, I don't send the good MD5 hash and it makes a problem.
On the server side in ASP.NET C#, I have this:
byte[] PasswordHash;
if (enc == 0) {
MD5 MD5Hasher = MD5.Create();
PasswordHash = MD5Hasher.ComputeHash(Encoding.Unicode.GetBytes(Password));
} else {
PasswordHash = Encoding.Unicode.GetBytes(Password);
}
So when I ask this URL "http://www.domain.com/myfile.aspx?action=login&enc=0" and give the password AS IS (so a String, not a byte[] and not MD5 hash) and do
data.append("pass", password);
then it works.
I just have either a problem with creating my MD5 hash or with the HTTP POST or both...
Please help me!
You can't just call "toString()" on a byte[] and expect to get a meaningful result. If you want to convert it to a hex representation of the bytes, you need a method to do that. I suggest going back to your previous question at Blackberry encode MD5 different from MD5 in C# since you had a function there that did the converstion from byte[] to String.

Resources