Why I get a error encrpyting a message with Openpgpjs? - javascript

I am trying to implement openpgpjs on my application because I need to encrypt a string using a public key (PGP). I tested this jsfiddle (https://jsfiddle.net/gu72bzm8/) which encrypts a string using a public key, it works very well. I even tested it with different keys and strings.
var message = "secret message";
const encryptMessage = async() => {
if(window.crypto.getRandomValues){
if(message != ""){
const publicKeyString = document.getElementById("pubkey").innerHTML;
var options = {
message: openpgp.message.fromText(message),
publicKeys: (await openpgp.key.readArmored(publicKeyString)).keys
};
openpgp.encrypt(options).then(ciphertext => {
alert(ciphertext.data);
})
}
} else{
window.alert("This browser does not support basic cryptography!");
}
}
encryptMessage();
However, if I copy exactly that code and try to run it locally (using the same cdn of that fiddle) I get the following error:
Uncaught (in promise) Error: Error encrypting message: No keys, passwords, or session key provided.
How can I fix it?

Related

How to change the Bot/Skype channel incoming message text format

Bot emulator works fine with the clear text responses but when I try to do the same via Skype the bot response with;
I don't understand, please try again
I found out that Skype auto-formats the email by wrapping it in <a /> tags - XMM format and I am a bit stuck what's supposed to do. I think changing the incoming text format to plain-text would fix this.
I found this like for a similar issue on Github but this is on C# and I am using Node.JS.
How do I change the default text format of the bot/skype channel to plain text instead of markdown so Skype auto-formatting would not happen?
Updated according to #ezequiel-jadib but still no luck. Maybe I am doing it wrong?
// bot.js
bot.use(...[logger]);
// logger.js
module.exports = exports = {
receive: (e, next) => {
e.textFormat('plain');
logConversation(e);
next();
},
send: (e, next) => {
logConversation(e);
next();
}
};
To get around this situation, you need to validate if you have an HTML wrapped email address, then extract the email portion from the string before saving it to session.dialogData.
For example replace line 40:
const usernameOrEmail = session.dialogData.usernameOrEmail = results.response;
with:
// where results.response is in the format 'hello#world.com'
var exampleEmailWrappedInHtml = results.response;
// validate if we have email wrapped in HTML from Skype
if(exampleEmailWrappedInHtml.match(/<a href="mailto:/i)) {
console.log('HTML wrapped email detected!');
const usernameOrEmail = session.dialogData.usernameOrEmail = exampleEmailWrappedInHtml.split('>')[1].split('<')[0];
} else {
console.log('no match.');
}
You can just call to the textFormat method of the Message like in C#
The accepted values are:
export var TextFormat = {
plain: 'plain',
markdown: 'markdown',
xml: 'xml'
};

Passing more than the message to the Web Socket #onmessage event

I am working on a Single Page Chat Application that uses Web Socket. My question is :Is there a way to pass more than the message to the function on event #OnMessage? like passing also the user's nickname and photo.
I have tried the following code (added the parameters _nickname and _photo),but after I run it I get the problem :
Server Tomcat v7.0 Server at localhost failed to start.
JavaScript in HTML :
function sendMessage() {
console.log("0000000");
if (websocket != null) {
websocket.send(msg,_nicknname,_photo);
}
msg = "";
}
Web Socket ChatEndPoint.java:
#OnMessage
public void deliverChatMessege(Session session, String msg ,String _nickname,String _photo) throws IOException{
try {
if (session.isOpen()) {
//deliver message
ChatUser user = chatUsers.get(session);
doNotify(user.username, msg, _nickname,_photo, null);
}
} catch (IOException e) {
session.close();
}
}
I was thinking about a way to pass the message, nickname and photo Json-like from JavaScript but I don't know how to get it in the side of the web socket server.
Am I missing something ?
Please help me.
Thanks
With a send method you can only send strings (see docs). However, you can send a JSON object if you use JSON.stringify. Then in the server you can decode the string and you will have your data.
Example
function sendMessage() {
console.log("0000000");
if (websocket != null) {
var data = {
msg: msg,
nickname: _nickname,
photo: _photo
};
websocket.send(JSON.stringify(data));
}
msg = "";
}

Valid JSON (for real) is throwing error in JSON.Parse

I am at a dead end. I am baffled. I am passing a stringified dictionary from Python (using json.dumps()) through UDP to an Ionic 2 (Typescript) application.
The python code generating the messages:
message = { 'time' : str(round(float(op('indexFraction')[0]),3)) }
messageJSON = json.dumps(message)
#messageJSON = json.JSONEncoder().encode(message)
print(messageJSON)
op('udpout').send(messageJSON) #sending out of TouchDesigner
My callback function on the Ionic side looks like this:
socket.on('message', function (message, remoteAddress) {
if (message.length > 0) {
console.log(message, typeof(message));
// alert(message);
// process response message
var data = JSON.parse(message);
console.log(data);
if (data.time) {
alert(data.time);
}
}
});
A sample message looks like this (typeof string):
{"time": "0.934"}
// this is a string, as evidenced by the Console.log
JSON.parse() throws the following:
index.html:1 Uncaught SyntaxError: Unexpected token in JSON at position 17
I've tried all kinds of variants on the object. It passes as valid on JSONlint. It's so simple, no wacky characters. Any ideas?
Thanks,
Marc

Robotjs error: Invalid key code specified

I have the following code in index.js
var settingsFile = "config.json";
var settings = JSON.parse(require("fs").readFileSync(settingsFile));
const net = require('net');
const robot = require("robotjs");
const fs = require("fs");
var client;
var customKeys = {
"scroll_up":'robot.scrollMouse(50, "up");',
"scroll_down":"robot.scrollMouse(50,'down');"
}
function startCommunication(address,port) {
client = net.connect({port: port,host:address}, () => {
// 'connect' listener
console.log('connected to server!');
//client.write('world!\r\n');
});
client.on('data', (data) => {
console.log(data.toString());
var string = data.toString();
console.log(settings.keys[string.substr(1)]);
if(string.substr(0,1) == "d") {
robot.keyToggle(settings.keys[string.substr(1)],"down");
} else {
robot.keyToggle(settings.keys[string.substr(1)],"up");
}
//client.end();
});
client.on('end', () => {
console.log('disconnected from server');
});
}
startCommunication(settings.address,settings.port);
i also have this code in config.json, aka what is parsed into the settings variable.
{
"port":5555,
"address":"192.168.1.118",
"keys":{
"KEY_A":"a",
"KEY_B":"b",
"KEY_X":"x",
"KEY_Y":"y",
"KEY_L":"y",
"KEY_R":"t",
"KEY_DUP":"up",
"KEY_DDOWN":"down",
"KEY_DLEFT":"left",
"KEY_DRIGHT":"right",
"KEY_START":"z",
"KEY_SELECT":"q"
}
}
What The Problem is is that when i get down to either robotjs.togglekeys statement i get the error
Error: Invalid key code specified.
This means that, as there error clearly states, it is getting an invalid keycode. I am guessing that is is some stupid mistake that I made. data in my testing is equal to "dKEY_DRIGHT". the variable string is equal to that but i need to get rid of the d in order for it to work. when i do the live console i am able to get the data that I need by using the same code but somethig goes wrong when it is being ran in the file. anything helps :)
you may try using node-key-sender to send keys presses to your operational system.
Install it with npm install --save-dev node-key-sender.
And send a key to the keyboard using:
var ks = require('node-key-sender');
ks.sendKey('up');
All the values of you config ('a', 'b', ...) are accepted by the lib. You can send them directly.
Check the documentation page for more information: https://www.npmjs.com/package/node-key-sender.

Request for api not working properly

I'm making a request but it doesn't seem to work. If I copy code into my browser it works good, but in my console it shows up this :
{
"status" : "success",
"data" : {
"error_message" : "API access enabled, but unable to verify two-factor authentication code. If you need help with this, please contact support#bitskins.com."
}
}
What am I doing wrong? It's based on two-factor authentication that as I said works good while printing the url itself and when i'm copying it into my browser.
var url = 'https://bitskins.com/api/v1/get_item_price/?api_key='+bitskins.apikey+'&code='+bitskins.code+'&names='+encodeURIComponent(items[i].market_hash_name)+'&delimiter=!END!';
console.log(url);
request(url, function (error, response, body) {
if (!error) {
console.log(body)
}
});
In case you want, here is my api key module to generating it (api key deleted for security)
var TOTP = require('onceler').TOTP;
//Create a TOTP object with your secret
var totp = new TOTP('deleted');
// print out a code that's valid right now
// console.log(totp.now());
var code = totp.now();
module.exports = {
code: code,
apikey: 'deleted'
}
Founder of BitSkins, Inc. here. You need to have the following:
1) Your API Key
2) Your Secure Access Secret
You see the Secret when you enable Secure Access. If you do not have this, just disable/re-enable Secure Access and note the Secret down. The TOTP code you generate is with that Secret. Generate the TOTP code right before every API call and you'll be fine.
I think it should work. For me it works fine.
var API_KEY = ''; //It is very important
var SECRET_KEY = ''; //It is very important
var totp = new TOTP(SECRET_KEY);
var code = totp.now();
var options = {
url: 'https://bitskins.com/api/v1/get_item_price',
form: {
'api_key': API_KEY,
'names': 'Tec-9%20%7C%20Sandstorm%20(Minimal%20Wear)',
'delimiter': '!END!',
'code': code
}
};
function callback(error, response, body) {
if (!error) {
var info = JSON.parse(body);
console.log(info);
}
}
request.post(options, callback);
What npm package do you use to create 2FA code? I'm using "onceler" from example but I think it creates wrond codes. Here is my code:
var API_KEY = ''; //correct key from settings page
var SECRET_KEY = ''; // correct key which I copied from form with QR code.
var totp = new TOTP("SECRET_KEY");
var code = totp.now();
This code doesn't equal code which I can see in my mobile device and with this code I get error message like in author's question. But if I put code from my mobile in programm code - it works fine. So what package should I use to get correct codes?

Categories