node-jose cyrillic support, how to? - javascript

https://github.com/cisco/node-jose
it's my code example:
let keystore1;
let keystore2;
keystore1 = JWK.createKeyStore();
keystore2 = JWK.createKeyStore();
const input = { message: { text: 'Привет!' } };
const priv1 = await keystore1.generate('EC', 'P-256', {
kid: '1gBdaS-G8RLax2qgObTD94w',
key_ops:["sign", "decrypt", "unwrap"]
});
const priv2 = await keystore2.generate('EC', 'P-256', {
kid: '2gBdaS-G8RLax2qgObTD94v',
key_ops:["sign", "decrypt", "unwrap"]
});
const pub1 = await JWK.asKey(priv1.toJSON());
const pub2 = await JWK.asKey(priv2.toJSON());
const encrypted = await JWE.createEncrypt(
{
format: 'compact',
fields: {
alg: 'ECDH-ES',
enc: 'A128CBC-HS256',
cty: 'json', // replace with JWT if you're encrypting a JWT...
},
},
{
key: pub2,
}
)
.update(JSON.stringify(input))
.final();
console.log('encrypted', encrypted);
const decrypted = await JWE.createDecrypt(priv2).decrypt(encrypted);
console.log('decrypted', JSON.parse(decrypted.payload.toString()));
// simulate only having access to the public key, usually this is your starting point as you only have access to the public components if you're encrypting a message for someone else.
With latin - decryption ok!
How to decrypte with cyrillic, please help me.

You can pass the encoding to the update function.
e.g.JWE.createEncrypt(...).update(input, "utf8")
Doc

Related

Discord.js v13 REST API Guide Cat and Urban Issues

So i tried following the https://discordjs.guide/additional-info/rest-api.html guide before making my own. But I can't get either to work.
Firstly with /cat it crashes and the console returns with:
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at getJSONResponse (BOTLOCATION\index.js:77:14)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Client.<anonymous> (BOTLOCATION\index.js:90:20)
And /urban works but no matter what term I enter it returns with NULL.
Here is the code, its nearly identical from the guides apart from the added SlashCommandBuilder and REST.
const { request } = require('undici');
const clientId = 'CLIENTID_HERE';
const guildId = 'GUILDID_HERE';
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const commands = [
new SlashCommandBuilder().setName('cat').setDescription('Cat thing idk'),
new SlashCommandBuilder().setName('urban').setDescription('Urban Dictionary Thing'),
]
.map(command => command.toJSON());
const rest = new REST({ version: '9' }).setToken("TOKEN_HERE");
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
//rest.put(Routes.applicationGuildCommands(clientId), { body: commands })
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
const trim = (str, max) => (str.length > max ? `${str.slice(0, max - 3)}...` : str);
async function getJSONResponse(body) {
let fullBody = '';
for await (const data of body) {
fullBody += data.toString();
}
return JSON.parse(fullBody);
}
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
await interaction.deferReply();
if (commandName === 'cat') {
const catResult = await request('https://aws.random.cat/meow');
const { file } = await getJSONResponse(catResult.body);
interaction.reply({ files: [{ attachment: file, name: 'cat.png' }] });
} else if (commandName === 'urban') {
const term = interaction.options.getString('term');
const query = new URLSearchParams({ term });
const dictResult = await request(`https://api.urbandictionary.com/v0/define?${query}`);
const { list } = await getJSONResponse(dictResult.body);
if (!list.length) {
return interaction.editReply(`No results found for **${term}**.`);
}
const [answer] = list;
const embed = new MessageEmbed()
.setColor('#EFFF00')
.setTitle(answer.word)
.setURL(answer.permalink)
.addFields(
{ name: 'Definition', value: trim(answer.definition, 1024) },
{ name: 'Example', value: trim(answer.example, 1024) },
{
name: 'Rating',
value: `${answer.thumbs_up} thumbs up. ${answer.thumbs_down} thumbs down.`,
},
);
interaction.editReply({ embeds: [embed] });
}
});
So for the cat command since there is a deferReply first we need to use editReply since deferReply counts as the first/initial reply.
await interaction.deferReply();
const catResult = await request('https://aws.random.cat/meow').catch((err) => { console.log(err); });;
const { file } = await getJSONResponse(catResult.body).catch((err) => { console.log(err); });
return await interaction.editReply({ files: [{ attachment: file, name: 'cat.png' }] });
I also added a .catch to the end of each await, this was just for testing however I recommend it.
Now with the urban command, the reason it is using null is since you don't have the string option's text. We can check for it by adding an if statement.
await interaction.deferReply();
const term = interaction.options.getString('term');
if (!term) return await interaction.editReply('Please provide a term.'); // We need to add this check to see if the user provided the term option or not.
const query = new URLSearchParams({ term });
const dictResult = await request(`https://api.urbandictionary.com/v0/define?${query}`);
const { list } = await getJSONResponse(dictResult.body);
if (!list.length) {
return interaction.editReply(`No results found for **${term}**.`);
}
const [answer] = list;
const embed = new MessageEmbed()
.setColor('#EFFF00')
.setTitle(answer.word)
.setURL(answer.permalink)
.addFields(
{ name: 'Definition', value: trim(answer.definition, 1024) },
{ name: 'Example', value: trim(answer.example, 1024) },
{
name: 'Rating',
value: `${answer.thumbs_up} thumbs up. ${answer.thumbs_down} thumbs down.`,
},
);
return await interaction.editReply({ embeds: [embed] });
IMPORTANT: When you are building your slash command you are not setting a string option. In the commands array, when creating the second slash command called urban we will add the support for the string option there. (An example using the string option, discord.js guide all command options)
This is how we can do this:
const commands = [
new SlashCommandBuilder().setName('cat')
.setDescription('Cat thing idk'),
new SlashCommandBuilder()
.setName('urban')
.setDescription('Urban Dictionary Thing')
.addStringOption((option) => option.setName('term').setDescription('term')) // We first add the string option then set the name to 'term' which is what the code calls for and then the description.
].map((command) => command.toJSON());
If you would like to make the term input required, add .setRequired(true) which will not allow the command to be ran without entering the term to search.
Once you do that you should be all good! Tested the code and it's working once that's fixed

How can I solve msg: 'Signature for this request is not valid.' from binance API?

I am trying to create a test order using Binance API but I have this error message msg: 'Signature for this request is not valid.' I tried to get the signature using the secret key and timestamp = Date.now() but didn't work.
My code is:
const credentials = require('./credentials');
const crypto = require('crypto');
function testNewOrder(symbol,side,type,timeInForce,quantity,price) {
const url = credentials.urlTest;
let timeStamp = Date.now();
let signature = crypto.createHmac('sha256', credentials.secretKeyTest).update(`timestamp=${timeStamp}`).digest('hex')
console.log(signature,timeStamp,timeStamp2);
fetch(`${url}/api/v3/order/test?symbol=${symbol}&side=${side}&type=${type}&timeInForce=${timeInForce}&quantity=${quantity}&price=${price}&timestamp=${timeStamp}&signature=${signature}`, {
method: 'POST',
headers: {
"Content-Type": "application/json",
"X-MBX-APIKEY": credentials.apiKeyTest
},
}).then(response => {
return response.json();
}).then( data=> {
console.log(data);
}).catch(err => {
console.log(err)
})
}
testNewOrder('BTCUSDT','SELL','LIMIT','GTC','0.02','42000');
I was also facing same issue, Hope this will help
import { createHmac } from "crypto";
const SECRET = "";
export const addSignature = (params) => {
// Object to query string
const queryString = Object.keys(params)
.map((key) => `${key}=${params[key]}`)
.join("&");
const signature = createHmac("sha256", SECRET)
.update(queryString)
.digest("hex");
return {
...params,
signature,
};
};
addSignature({
symbol: "BTC",
// ...
});

How to call balanceOf() method for non published ABI

I'm trying to call balanceOf() method on a specific Tron contract (TYukBQZ2XXCcRCReAUguyXncCWNY9CEiDQ), but what I get is Failed to execute . If I do not provide the parameters I get Invalid argument count provided - meaning at some level it works for this contract.
What is interesting it works well on contracts other than the ones created with JustSwap Factory contract eg. https://tronscan.io/#/contract/TYukBQZ2XXCcRCReAUguyXncCWNY9CEiDQ/code .
The code includes the standard TRC20 methods - including balanceOf() - I'm stuck and tried all that's possible form my side, but let's just say I'm not fluent in tronweb api.
My code:
export const getDataToken = async (contractAddress, account, account2) => {
try {
const instance = await window.tronWeb.contract(
[
{
constant: true,
inputs: [{ name: "owner", type: "address" }],
name: "balanceOf",
outputs: [{ name: "", type: "uint256" }],
payable: false,
stateMutability: "view",
type: "function"
}
],
contractAddress
);
console.log(instance);
if (instance.balanceOf) {
console.log("dadadad if");
const tokenBalance = await instance.balanceOf(account).call();
const tokenBalance2 = await instance.balanceOf(account2).call();
return {
tokenBalance: (tokenBalance / Math.pow(10, 18)).toString(),
tokenContract: instance,
tokenBalance2: (tokenBalance2 / Math.pow(10, 18)).toString()
};
}
} catch (message) {
console.log("error getData :" + message);
}
};
const { tokenBalance, tokenContract, tokenBalance2 } = getDataToken(
"TYukBQZ2XXCcRCReAUguyXncCWNY9CEiDQ",
"TL4HzzxGMc1LMfs3XCi4yTJikaBVubz5y4",
"TTFp171XD4JdUB33sDq2ydXJyUEEZjNhLD"
);
This function can help (example for getting JustSwap pair price):
async function takePrice(contractAddress, token){
var functionSelector = 'getTokenToTrxInputPrice(uint256)';
var parameter = [
{
type: 'uint256',
value: token
}
]
var options = {};
transaction = await window.tronWeb.transactionBuilder.triggerConstantContract(contractAddress, functionSelector, options, parameter);
return window.tronWeb.BigNumber("0x"+transaction['constant_result'][0]);
}
priceUSDTTRX = window.tronWeb.fromSun(await takePrice(USDTTRX_ADDRESS, "1000000"));
priceSomeTone18TRX = window.tronWeb.fromSun(await takePrice(SomeTone18TRX_ADDRESS, "1"+"0".repeat(18)));
I have good result:
const TronWeb = require("tronweb");
const ethers = require('ethers')
const MAINNET_RPC = "https://api.trongrid.io";
const PLACEHOLDER_PRIVATE_KEY = "YOUR_PRIVATE_KEY";
const HttpProvider = TronWeb.providers.HttpProvider;
const fullNode = new HttpProvider(MAINNET_RPC);
const solidityNode = new HttpProvider(MAINNET_RPC);
const eventServer = new HttpProvider(MAINNET_RPC);
const tronWeb = new TronWeb(fullNode,solidityNode,eventServer,PLACEHOLDER_PRIVATE_KEY);
const startJustSwap = async () => {
try {
const contractTokenExchangeUSDT = 'TQn9Y2khEsLJW1ChVWFMSMeRDow5KcbLSE'; //S-USDT-TRX Token
const parameter = [{type:`uint256`,value: 10000000}];
const tx = await tronWebLocal.transactionBuilder.triggerConstantContract(contractToken, `trxToTokenSwapInput(uint256,uint256)`, {}, parameter);
console.log(tx);
} catch (e) {
console.log(e);
}
};
startJustSwap();
try const tokenBalance = await instance.balanceOf(account).call({ _isConstant: true });
It works for me.
transactionBuilder.triggerConstantContract works too, but mine is simpler

How to pass headers in axios as secret-key

I am using jsonbin.io and hosted a json data as private bin.
I am calling a axios get request to fetch that data. I have to pass my secret-key in headers as
headers{
secret-key: mysecretkey
}
but axios does not allow key in header as secret-key
const secretKey = process.env.REACT_APP_SECRET_KEY;
const localUrl = process.env.REACT_APP_LOCAL_URL;
const fetchPhotosFlocal = async () => {
const response = await axios.get(localUrl, {
headers: {
secret-key: secretKey,
},
});
console.log(response); };
secret-key gives error at compile time and "secret-key" can not fetch data what should i do now ?
secret-key is not a valid identifier in JavaScript, as they cannot contain hyphens (see the specification for more details.
In your case, you can simply put the name of your header in quotes, like this:
const secretKey = process.env.REACT_APP_SECRET_KEY;
const localUrl = process.env.REACT_APP_LOCAL_URL;
const fetchPhotosFlocal = async () => {
const response = await axios.get(localUrl, {
headers: {
"secret-key": secretKey,
},
});
console.log(response);
};
it should be
const fetchPhotosFlocal = async () => axios.get(localUrl, {
headers: {
'secret-key': secretKey,
},
});
const resp = await fetchPhotosFlocal();
console.log(resp);
Problem solved i checked their documentation they are passing secret_key in string code.
req.setRequestHeader("secret-key", "<SECRET_KEY>");
This runs fine
const secretKey = process.env.REACT_APP_SECRET_KEY;
const localUrl = process.env.REACT_APP_LOCAL_URL;
const fetchPhotosFlocal = async () => {
const response = await axios.get(localUrl, {
headers: {
"secret-key": secretKey,
},
});
console.log(response); };

Using node-jose, how do I decrypt the data I just encrypted?

I am trying to implement simple JOSE encrypt and decrypt functions using node-jose.
My code is as follows (written using Node 8.2.1)
const { JWE } = require('node-jose');
const jose = (publicKey, privateKey) => {
async function encrypt(raw) {
if (!raw) throw new Error('Missing raw data.')
const buffer = new Buffer(JSON.stringify(raw));
return JWE.createEncrypt(publicKey).update(buffer).final();
}
async function decrypt(encrypted) {
if (!encrypted) throw new Error('Missing encrypted data.')
const buffer = new Buffer(JSON.stringify(encrypted));
return JWE.createDecrypt(privateKey).decrypt(buffer);
}
return { encrypt, decrypt }
}
module.exports = jose;
I generate an RSA keypair using generate-rsa-keypair.
So testing via this code the encryption side of things works fine
const { JWK } = require('node-jose');
const keygen = require('generate-rsa-keypair');
const jose = require('./src/utils/jose');
const rawKeys = keygen();
const makeKey = pem => JWK.asKey(pem, 'pem');
async function start() {
const publicKey = await makeKey(rawKeys.public)
const privateKey = await makeKey(rawKeys.private)
const raw = {
iss: 'test',
exp: new Date().getTime() + 3600,
sub: {
test: 'This is a test',
},
};
const { encrypt, decrypt } = jose(publicKey, privateKey);
return encrypt(raw).then(encrypted => decrypt(encrypted));
}
return start().then((result) => {
console.log('decrypted', result)
}, (err) => {
console.error(err);
});
the encrypted result is
{
recipients: [ { encrypted_key: 'ciNiK6Unq30zCAXxIl2Dx9b8bZAi79qbpL1yUCwTFnSghFLrIZ11_D2ozt5on3r3ThUu96oDLZPcNShbqWPMV49NvQAsSNGdemhgzmTt3Lf3rJn1YiqvJvqf5NIXdmzjdoEZi-d9224mGpZGVKtIIFeT6-0hYgm5zNqq_aF_X2jy5IiF-mAGspNdXIk_KXPrTVbnU-XL9J5aAoG2Lp51Te1WzGA4Fjg4Ve5ZTzH6TLlQ5R5Ob_14liK-INrSi3armwXrtMgJcTmI_4oBtORtZp8AjaXzecFO_GzifvRVCSKx2vmpy9KaECpskMhZBHVx9RX9cvGKh7hq3Y7vsUucZw' } ],
protected: 'eyJhbGciOiJSU0EtT0FFUCIsImtpZCI6IldLWS1ONDRXM2RnanA4U2ZxSlp3TldqV3AzUG1XZ29UczhjRDh3eWNSUWciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0',
iv: 'wvqir2ewtQPfDHQtzl6IUg',
ciphertext: 'ZwIrL_3739LI17rh3gWDUA6lXIL7ewkSh54FO_RwumC0qh9B0DcAr8RyXsfPbW19cV4u7SbZNSRP6B8qNOTy-2iENlqBISfE_kolDt8g5sg',
tag: 'z8nwrJfRgOi1hYMBI9lGeQ'
}
but when I try to decrypt that I get
Error: no key found
at processKey (node_modules/node-jose/lib/jwe/decrypt.js:157:22)
There are very few examples of using node-jose so I am unsure of the following
I am assuming I ought to be decrypting with the private key. But that's just an assumption. None of the examples show use of public/private key pairs, just a single key.
I'm assuming that the results of the encryption can just be strringified and turned into a buffer and passed into decrypt but perhaps that's not the case.
How does this really work?
When using public/private key pairs, the private key is used to decrypt and the public key is used to encrypt.
The input to JWEDecrypter.decrypt() is the promised output from JWEEncrypter.final().
Change your decrypt function to:
async function decrypt(encrypted) {
if (!encrypted) throw new Error('Missing encrypted data.')
return JWE.createDecrypt(privateKey).decrypt(encrypted);
}

Categories