Error [0x8015] (ESP_ERR_MBEDTLS_X509_CRT_PARSE_FAILED) esp32 - mqtt

good afternoon colleagues, please see if you can give me a light
example 1
void conect(void) {
esp_mqtt_client_handle_t mqttClient;
const char *certificate;
certificate =
"-----BEGIN CERTIFICATE-----\n"
"MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n"
"MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n"
"d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n"
"QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n"
"MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n"
"b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n"
"9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n"
"CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n"
"nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n"
"43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n"
"T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n"
"gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n"
"BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n"
"TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n"
"DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n"
"hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n"
"06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n"
"PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n"
"YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n"
"CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n"
"-----END CERTIFICATE-----\n"
esp_mqtt_client_config_t mqttConfig = {};
mqttConfig.uri = "mqtts://broker.emqx.io";
mqttConfig.port = 8883;
mqttConfig.cert_pem = certificate;
mqttConfig.username = "";
mqttConfig.password = "";
mqttConfig.keepalive = 60;
mqttConfig.client_id = "test";
mqttClient = esp_mqtt_client_init(&mqttConfig);
esp_mqtt_client_start(mqttClient);
}
the code above works perfectly but when I change the certificate variable to std::string it gives an error
below is the change and the error
example 2
void conect(void) {
esp_mqtt_client_handle_t mqttClient;
std::string certificate;
certificate =
"-----BEGIN CERTIFICATE-----\n"
"MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n"
"MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n"
"d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n"
"QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n"
"MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n"
"b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n"
"9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n"
"CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n"
"nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n"
"43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n"
"T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n"
"gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n"
"BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n"
"TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n"
"DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n"
"hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n"
"06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n"
"PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n"
"YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n"
"CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n"
"-----END CERTIFICATE-----\n"
esp_mqtt_client_config_t mqttConfig = {};
mqttConfig.uri = "mqtts://broker.emqx.io";
mqttConfig.port = 8883;
mqttConfig.cert_pem = certificate.c_str();
mqttConfig.username = "";
mqttConfig.password = "";
mqttConfig.keepalive = 60;
mqttConfig.client_id = "test";
mqttClient = esp_mqtt_client_init(&mqttConfig);
esp_mqtt_client_start(mqttClient);
}
when this certificate variable is set to std::string it gives an error:
E (5021) esp-tls-mbedtls: mbedtls_x509_crt_parse returned -0x2180
E (5021) esp-tls-mbedtls: Failed to set client configurations, returned [0x8015] (ESP_ERR_MBEDTLS_X509_CRT_PARSE_FAILED)
E (5031) esp-tls: create_ssl_handle failed
E (5031) esp-tls: Failed to open new connection
E (5041) TRANSPORT_BASE: Failed to open a new connection
E (5051) MQTT_CLIENT: Error transport connect
mqttConfig.cert_pem accepts const char * but converting a string variable gives the above error and if I create the variable as const char * it works as per example 1
can someone please guide me what could be going on
const char *p = certificate.c_str();
mqttConfig.cert_pem = p;
Thank you very much

Related

TypeError: provider.send is not a function in anchor

I'm looking at this https://book.solmeet.dev/notes/intro-to-anchor written according to the code in the textbook:
TypeError: provider.send is not a function when await provider.send()
import * as anchor from '#project-serum/anchor';
import { Program } from '#project-serum/anchor';
import { AnchorEscrow } from '../target/types/anchor_escrow';
import { PublicKey, SystemProgram, Transaction } from '#solana/web3.js';
import { TOKEN_PROGRAM_ID, Token } from "#solana/spl-token";
import { assert } from "chai";
describe('anchor-escrow', () => {
// Configure the client to use the local cluster.
const provider = new anchor.getProvider();
anchor.setProvider(provider);
const program = anchor.workspace.AnchorEscrow as Program<AnchorEscrow>;
let mintA = null;
let mintB = null;
let initializerTokenAccountA = null;
let initializerTokenAccountB = null;
let takerTokenAccountA = null;
let takerTokenAccountB = null;
let vault_account_pda = null;
let vault_account_bump = null;
let vault_authority_pda = null;
const takerAmount = 1000;
const initializerAmount = 500;
const escrowAccount = anchor.web3.Keypair.generate();
const payer = anchor.web3.Keypair.generate();
const mintAuthority = anchor.web3.Keypair.generate();
const initializerMainAccount = anchor.web3.Keypair.generate();
const takerMainAccount = anchor.web3.Keypair.generate();
it("Initialize program state", async () => {
// Airdropping tokens to a payer.
await provider.connection.confirmTransaction(
await provider.connection.requestAirdrop(payer.publicKey, 10000000000),
"confirmed"
);
// ⚠️ An error has occurred here
await provider.send(
(() => {
const tx = new Transaction();
tx.add(
SystemProgram.transfer({
fromPubkey: payer.publicKey,
toPubkey: initializerMainAccount.publicKey,
lamports: 100000000,
}),
SystemProgram.transfer({
fromPubkey: payer.publicKey,
toPubkey: takerMainAccount.publicKey,
lamports: 100000000,
})
);
return tx;
})(),
[payer]
);
});
then run anchor test
Warning: cargo-build-bpf is deprecated. Please, use cargo-build-sbf
cargo-build-bpf child: /Users/yjy/.local/share/solana/install/active_release/bin/cargo-build-sbf --arch bpf
Error: Function _ZN13anchor_escrow9__private8__global8exchange17hb34dfff05db149f5E Stack offset of 4096 exceeded max offset of 4096 by 0 bytes, please minimize large stack variables
Finished release [optimized] target(s) in 0.34s
Found a 'test' script in the Anchor.toml. Running it as a test suite!
Running test suite: "/Users/yjy/Documents/Code/solana/anchor-projects/anchor-escrow/Anchor.toml"
yarn run v1.22.18
warning package.json: No license field
$ /Users/yjy/Documents/Code/solana/anchor-projects/anchor-escrow/node_modules/.bin/ts-mocha -p ./tsconfig.json -t 1000000 'tests/**/*.ts'
anchor-escrow
1) Initialize program state
✔ Initialize escrow
✔ Exchange escrow state
✔ Initialize escrow and cancel escrow
3 passing (598ms)
1 failing
1) anchor-escrow
Initialize program state:
TypeError: provider.send is not a function
at /Users/yjy/Documents/Code/solana/anchor-projects/anchor-escrow/tests/anchor-escrow.ts:45:20
at Generator.next (<anonymous>)
at fulfilled (tests/anchor-escrow.ts:28:58)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
How can I solve this problem?
It looks like send doesn't exist, but you can use sendAndConfirm if you want to confirm the transction too, or sendAll if you just want to send. That takes an array of Transactions, so you can do:
const tx = new Transaction();
tx.add(
SystemProgram.transfer({
fromPubkey: payer.publicKey,
toPubkey: initializerMainAccount.publicKey,
lamports: 100000000,
}),
SystemProgram.transfer({
fromPubkey: payer.publicKey,
toPubkey: takerMainAccount.publicKey,
lamports: 100000000,
})
);
await provider.sendAll([{tx, signers: [payer]}]);

Create signature in nodejs algorithm rsa-sha1 private_key.pem

Can I create signature like code below in Nodejs?
# Load PRIVATE key
private_key = OpenSSL::PKey::RSA.new(File.read(Rails.root + ENV['EPAY_PRIVATE_KEY']))
# Sign your data
signMessage = private_key.sign(OpenSSL::Digest::SHA1.new, message)
# Base64 message
baseMessage = Base64.encode64(signMessage.to_s)
You should be able to do the same thing in Node.js, creating a signature is quite easy, for example:
const crypto = require('crypto');
const fs = require('fs');
const privateKey = fs.readFileSync('./private-key.pem', 'utf8');
const message = "some message data";
const sign = crypto.createSign('SHA1');
sign.update(message);
sign.end();
const signature = sign.sign(privateKey);
console.log("Signature: ", signature.toString('base64'));
This creates a base64 encoded SHA1 signature of the message.

Compatible AES encryption and decryption for Flutter and javascript

I am trying to write two functions in flutter and Javascript which I can use throughout my project to encrypt or decrypt data using AES when data is exchanged.
For Flutter, I am using the pointycastle package based on instructions
https://gist.github.com/proteye/e54eef1713e1fe9123d1eb04c0a5cf9b?signup=true
import 'dart:convert';
import 'dart:typed_data';
import "package:pointycastle/export.dart";
import "./convert_helper.dart";
// AES key size
const KEY_SIZE = 32; // 32 byte key for AES-256
const ITERATION_COUNT = 1000;
class AesHelper {
static const CBC_MODE = 'CBC';
static const CFB_MODE = 'CFB';
static Uint8List deriveKey(dynamic password,
{String salt = '',
int iterationCount = ITERATION_COUNT,
int derivedKeyLength = KEY_SIZE}) {
if (password == null || password.isEmpty) {
throw new ArgumentError('password must not be empty');
}
if (password is String) {
password = createUint8ListFromString(password);
}
Uint8List saltBytes = createUint8ListFromString(salt);
Pbkdf2Parameters params =
new Pbkdf2Parameters(saltBytes, iterationCount, derivedKeyLength);
KeyDerivator keyDerivator =
new PBKDF2KeyDerivator(new HMac(new SHA256Digest(), 64));
keyDerivator.init(params);
return keyDerivator.process(password);
}
static Uint8List pad(Uint8List src, int blockSize) {
var pad = new PKCS7Padding();
pad.init(null);
int padLength = blockSize - (src.length % blockSize);
var out = new Uint8List(src.length + padLength)..setAll(0, src);
pad.addPadding(out, src.length);
return out;
}
static Uint8List unpad(Uint8List src) {
var pad = new PKCS7Padding();
pad.init(null);
int padLength = pad.padCount(src);
int len = src.length - padLength;
return new Uint8List(len)..setRange(0, len, src);
}
static String encrypt(String password, String plaintext,
{String mode = CBC_MODE}) {
Uint8List derivedKey = deriveKey(password);
KeyParameter keyParam = new KeyParameter(derivedKey);
BlockCipher aes = new AESFastEngine();
var rnd = FortunaRandom();
rnd.seed(keyParam);
Uint8List iv = rnd.nextBytes(aes.blockSize);
BlockCipher cipher;
ParametersWithIV params = new ParametersWithIV(keyParam, iv);
switch (mode) {
case CBC_MODE:
cipher = new CBCBlockCipher(aes);
break;
case CFB_MODE:
cipher = new CFBBlockCipher(aes, aes.blockSize);
break;
default:
throw new ArgumentError('incorrect value of the "mode" parameter');
break;
}
cipher.init(true, params);
Uint8List textBytes = createUint8ListFromString(plaintext);
Uint8List paddedText = pad(textBytes, aes.blockSize);
Uint8List cipherBytes = _processBlocks(cipher, paddedText);
Uint8List cipherIvBytes = new Uint8List(cipherBytes.length + iv.length)
..setAll(0, iv)
..setAll(iv.length, cipherBytes);
return base64.encode(cipherIvBytes);
}
static String decrypt(String password, String ciphertext,
{String mode = CBC_MODE}) {
Uint8List derivedKey = deriveKey(password);
KeyParameter keyParam = new KeyParameter(derivedKey);
BlockCipher aes = new AESFastEngine();
Uint8List cipherIvBytes = base64.decode(ciphertext);
Uint8List iv = new Uint8List(aes.blockSize)
..setRange(0, aes.blockSize, cipherIvBytes);
BlockCipher cipher;
ParametersWithIV params = new ParametersWithIV(keyParam, iv);
switch (mode) {
case CBC_MODE:
cipher = new CBCBlockCipher(aes);
break;
case CFB_MODE:
cipher = new CFBBlockCipher(aes, aes.blockSize);
break;
default:
throw new ArgumentError('incorrect value of the "mode" parameter');
break;
}
cipher.init(false, params);
int cipherLen = cipherIvBytes.length - aes.blockSize;
Uint8List cipherBytes = new Uint8List(cipherLen)
..setRange(0, cipherLen, cipherIvBytes, aes.blockSize);
Uint8List paddedText = _processBlocks(cipher, cipherBytes);
Uint8List textBytes = unpad(paddedText);
return new String.fromCharCodes(textBytes);
}
static Uint8List _processBlocks(BlockCipher cipher, Uint8List inp) {
var out = new Uint8List(inp.lengthInBytes);
for (var offset = 0; offset < inp.lengthInBytes;) {
var len = cipher.processBlock(inp, offset, out, offset);
offset += len;
}
return out;
}
}
and class flutter convert_helper.dart
import "dart:typed_data";
import 'dart:convert';
import 'package:convert/convert.dart' as convert;
Uint8List createUint8ListFromString(String s) {
var ret = new Uint8List(s.length);
for (var i = 0; i < s.length; i++) {
ret[i] = s.codeUnitAt(i);
}
return ret;
}
Uint8List createUint8ListFromHexString(String hex) {
var result = new Uint8List(hex.length ~/ 2);
for (var i = 0; i < hex.length; i += 2) {
var num = hex.substring(i, i + 2);
var byte = int.parse(num, radix: 16);
result[i ~/ 2] = byte;
}
return result;
}
Uint8List createUint8ListFromSequentialNumbers(int len) {
var ret = new Uint8List(len);
for (var i = 0; i < len; i++) {
ret[i] = i;
}
return ret;
}
String formatBytesAsHexString(Uint8List bytes) {
var result = new StringBuffer();
for (var i = 0; i < bytes.lengthInBytes; i++) {
var part = bytes[i];
result.write('${part < 16 ? '0' : ''}${part.toRadixString(16)}');
}
return result.toString();
}
List<int> decodePEM(String pem) {
var startsWith = [
"-----BEGIN PUBLIC KEY-----",
"-----BEGIN PRIVATE KEY-----",
"-----BEGIN ENCRYPTED MESSAGE-----",
"-----BEGIN PGP PUBLIC KEY BLOCK-----\r\nVersion: React-Native-OpenPGP.js 0.1\r\nComment: http://openpgpjs.org\r\n\r\n",
"-----BEGIN PGP PRIVATE KEY BLOCK-----\r\nVersion: React-Native-OpenPGP.js 0.1\r\nComment: http://openpgpjs.org\r\n\r\n",
];
var endsWith = [
"-----END PUBLIC KEY-----",
"-----END PRIVATE KEY-----",
"-----END ENCRYPTED MESSAGE-----",
"-----END PGP PUBLIC KEY BLOCK-----",
"-----END PGP PRIVATE KEY BLOCK-----",
];
bool isOpenPgp = pem.indexOf('BEGIN PGP') != -1;
for (var s in startsWith) {
if (pem.startsWith(s)) {
pem = pem.substring(s.length);
}
}
for (var s in endsWith) {
if (pem.endsWith(s)) {
pem = pem.substring(0, pem.length - s.length);
}
}
if (isOpenPgp) {
var index = pem.indexOf('\r\n');
pem = pem.substring(0, index);
}
pem = pem.replaceAll('\n', '');
pem = pem.replaceAll('\r', '');
return base64.decode(pem);
}
List<int> decodeHex(String hex) {
hex = hex
.replaceAll(':', '')
.replaceAll('\n', '')
.replaceAll('\r', '')
.replaceAll('\t', '');
return convert.hex.decode(hex);
}
For the Javascript solution, I am using CryptoJS
var AESKey = "20190225165436_15230006321670000"
cc = CryptoJS.AES.encrypt( ("abcdef ha ha "), AESKey, { mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 } ).toString()
CryptoJS.AES.decrypt(cc, AESKey).toString(CryptoJS.enc.Utf8); //return abcdef ha ha
Both solutions work well within their own environment, however, the flutter or Javascript hashes can't be exchanged, they will not decrypt. My guess is that the character encoding has something to do with it, hence why the base64 sizes differ so much. Does anyone have an idea to get this working together? Thanks!
Does anyone have an idea to get this working together?
import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';
import 'package:crypto/crypto.dart';
import 'package:tuple/tuple.dart';
import 'package:encrypt/encrypt.dart' as encrypt;
String encryptAESCryptoJS(String plainText, String passphrase) {
try {
final salt = genRandomWithNonZero(8);
var keyndIV = deriveKeyAndIV(passphrase, salt);
final key = encrypt.Key(keyndIV.item1);
final iv = encrypt.IV(keyndIV.item2);
final encrypter = encrypt.Encrypter(
encrypt.AES(key, mode: encrypt.AESMode.cbc, padding: "PKCS7"));
final encrypted = encrypter.encrypt(plainText, iv: iv);
Uint8List encryptedBytesWithSalt = Uint8List.fromList(
createUint8ListFromString("Salted__") + salt + encrypted.bytes);
return base64.encode(encryptedBytesWithSalt);
} catch (error) {
throw error;
}
}
String decryptAESCryptoJS(String encrypted, String passphrase) {
try {
Uint8List encryptedBytesWithSalt = base64.decode(encrypted);
Uint8List encryptedBytes =
encryptedBytesWithSalt.sublist(16, encryptedBytesWithSalt.length);
final salt = encryptedBytesWithSalt.sublist(8, 16);
var keyndIV = deriveKeyAndIV(passphrase, salt);
final key = encrypt.Key(keyndIV.item1);
final iv = encrypt.IV(keyndIV.item2);
final encrypter = encrypt.Encrypter(
encrypt.AES(key, mode: encrypt.AESMode.cbc, padding: "PKCS7"));
final decrypted =
encrypter.decrypt64(base64.encode(encryptedBytes), iv: iv);
return decrypted;
} catch (error) {
throw error;
}
}
Tuple2<Uint8List, Uint8List> deriveKeyAndIV(String passphrase, Uint8List salt) {
var password = createUint8ListFromString(passphrase);
Uint8List concatenatedHashes = Uint8List(0);
Uint8List currentHash = Uint8List(0);
bool enoughBytesForKey = false;
Uint8List preHash = Uint8List(0);
while (!enoughBytesForKey) {
int preHashLength = currentHash.length + password.length + salt.length;
if (currentHash.length > 0)
preHash = Uint8List.fromList(
currentHash + password + salt);
else
preHash = Uint8List.fromList(
password + salt);
currentHash = md5.convert(preHash).bytes;
concatenatedHashes = Uint8List.fromList(concatenatedHashes + currentHash);
if (concatenatedHashes.length >= 48) enoughBytesForKey = true;
}
var keyBtyes = concatenatedHashes.sublist(0, 32);
var ivBtyes = concatenatedHashes.sublist(32, 48);
return new Tuple2(keyBtyes, ivBtyes);
}
Uint8List createUint8ListFromString(String s) {
var ret = new Uint8List(s.length);
for (var i = 0; i < s.length; i++) {
ret[i] = s.codeUnitAt(i);
}
return ret;
}
Uint8List genRandomWithNonZero(int seedLength) {
final random = Random.secure();
const int randomMax = 245;
final Uint8List uint8list = Uint8List(seedLength);
for (int i=0; i < seedLength; i++) {
uint8list[i] = random.nextInt(randomMax)+1;
}
return uint8list;
}
Please refer below link for solution.
https://medium.com/#chingsuehok/cryptojs-aes-encryption-decryption-for-flutter-dart-7ca123bd7464
For those people who are looking for a solution for C# (RijndaelManaged & Rfc2898DeriveBytes) and Flutter link
The main problem is that the two key derivation algorithms are different.
In your Dart/PC code you are using PBKDF2, but the KDF used by CryptoJS.AES.encrypt is OpenSSL's EVP_BytesToKey
You could implement the equivalent of EVP_BytesToKey in Dart using PC. However it would probably be easier to change the JavaScript code to derive its key using PBKDF2, which is already supported by CryptoJS. That will give you a key and IV to be used like this:
var encrypted = CryptoJS.AES.encrypt("Message", key, { iv: iv });

Issue in IOS Push Notification - Authentication failed because the remote party has closed the transport stream

I am using the below code for push notification.
public void PushNotificationIOS(string message, string registrationKey)
{
string deviceID = registrationKey;
int port = 2195;
String hostname = System.Configuration.ConfigurationManager.AppSettings["HostName"];//"gateway.sandbox.push.apple.com";
string certPath = string.Empty;
certPath = System.Configuration.ConfigurationManager.AppSettings["CertificatePath"] + System.Configuration.ConfigurationManager.AppSettings["Cer
String certificatePath = System.Web.HttpContext.Current.Server.MapPath(certPath);
string certPassword = System.Configuration.ConfigurationManager.AppSettings["CertificatePassword"];
TcpClient client = new TcpClient(hostname, port);
try
{
X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath), certPassword);
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);
MemoryStream memoryStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memoryStream);
writer.Write((byte)0);
writer.Write((byte)0);
writer.Write((byte)32);
writer.Write(StringToByteArray(deviceID.ToUpper()));
String payload = "{\"aps\":{\"alert\":\"" + message + "\",\"badge\":0,\"sound\":\"default\"}}";
writer.Write((byte)0);
writer.Write((byte)payload.Length);
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
writer.Write(b1);
writer.Flush();
byte[] array = memoryStream.ToArray();
sslStream.Write(array);
sslStream.Flush();
client.Close();
}
catch (System.Security.Authentication.AuthenticationException ex)
{
client.Close();
}
}
I am getting the following error
Authentication failed because the remote party has closed the transport stream.
On Trace, I am getting the below
System.Net.Security.SslState.CheckThrow(Boolean authSucessCheck)
at System.Net.Security.SslState.get_SecureStream()
at System.Net.Security.SslStream.Write(Byte[] buffer)
I tried all the things mentioned in various post but am not able to solve the issue.
Make sure certificate is valid & is not corrupted. You can regenerate certificate to be dead sure.
Try providing all the options for SecurityProtocolType like :
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls, false);
SecurityProtocolType.Tls12 can negotiate Transport layer security 1.1 or downwards too but try all options to be sure.
For more details on SecurityProtocolType refer :
https://msdn.microsoft.com/en-us/library/system.net.securityprotocoltype(v=vs.110).aspx

IMAP OAuth2 with Chilkat

I was looking for a way to Authenticate an IMAP session with google's Service account
But Since we already use Chilkat how do we do it, I found the following:
http://www.cknotes.com/imap-authentication-using-oauth/
allowing me to send a raw command:
imap.SendRawCommand("AUTHENTICATE XOAUTH <base64_data>");
This shows how to strucure the command:
https://developers.google.com/gmail/xoauth2_protocol
But having trouble putting it all together.
limilabs puts things together nicely in this example:
http://www.limilabs.com/blog/oauth2-gmail-imap-service-account
They have a neat imap.LoginOAUTH2(userEmail, credential.Token.AccessToken); that wraps things up into a command. How do I do this as a raw command for Chilkat?
const string serviceAccountEmail = "service-account-xxxxxx#developer.gserviceaccount.com";
const string serviceAccountCertPath = #"service-xxxxxx.p12";
const string serviceAccountCertPassword = "notasecret";
const string userEmail = "user#domain.com";
X509Certificate2 certificate = new X509Certificate2(
serviceAccountCertPath,
serviceAccountCertPassword,
X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { "https://mail.google.com/" },
User = userEmail
}.FromCertificate(certificate));
bool success = credential.RequestAccessTokenAsync(CancellationToken.None).Result;
using (Chilkat.Imap imap = new Chilkat.Imap())
{
imap.UnlockComponent("unlock-code");
imap.Ssl = true;
imap.Port = 993;
imap.Connect("imap.gmail.com");
var authString = String.Format("user={0}" + "\x001" + "auth=Bearer {1}" + "\x001" + "\x001",userEmail, credential.Token.AccessToken);
var encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(authString));
string response = imap.SendRawCommand("AUTHENTICATE XOAUTH2 " + encoded);
imap.SelectMailbox("Inbox");
bool bUid;
bUid = false;
string mimeStr;
int i;
int n;
n = imap.NumMessages;
for (i = 1; i <= n; i++)
{
// Download the email by sequence number.
mimeStr = imap.FetchSingleAsMime(i, bUid);
Chilkat.Email chilkatEmail = new Chilkat.Email();
chilkatEmail.SetFromMimeText(mimeStr);
Console.WriteLine(chilkatEmail.Subject);
}
imap.CloseMailbox("Inbox");
Console.ReadLine();
}
}

Resources