When I use crypto-js to encrypt text, it throws an error Cannot read property 'encrypt' of undefined. What's wrong with my code?
...
const Cookies = require('js-cookie');
const request = require('browser-request');
const CryptoJS = require('crypto');
class OssHelper extends Helper {
addFetchEvent (urlFunction) {
const createTime = new Date().getTime();
const encryptUuid = CryptoJS.AES.encrypt(Cookies.get('CLIPUUID'), createTime);
};
}
...
The error tells you that "AES" is undefined.
Please check how you should use CryptoJS. It seems you did not instanciate an AES object. Shouldn't you require(crypto/aes) and assign it to an AES constant?
const AES = require('crypto-js/aes');
...
const encryptUuid = AES.encrypt
See https://www.npmjs.com/package/crypto-js
you are installing crypto-js with command (if you are using npm of course) npm install crypto-js, not crypto, (crypto is other built in module of nodeJS), so you got to require crypto-js not crypto with code: var CryptoJS = require('crypto-js')
Related
The full code is here:
https://github.com/dmerejkowsky/chuck-norris-webassembly-plugins
Here's what's wrong
There's a get_fact method written in Rust and exported with wasm_bindgen:
#[wasm_bindgen]
pub fn get_fact() -> String {
"Chuck Norris can slam a revolving door".to_string()
}
When I build the wasm file with wasm-pack --target nodejs I can call the get_fact just fine from Javascript:
const assert = require('node:assert/strict');
const ck = require('../pkg/chuck_norris.js');
const actual = ck.get_fact();
assert.ok(actual.includes("Chuck Norris"));
But when trying to write the same test in Python:
from wasmer import engine, Store, Module, Instance
from wasmer_compiler_cranelift import Compiler
rust_wasm = Path / "to" / "chucknorris_bg.wasm"
store = Store(engine.Universal(Compiler))
module = Module(store, rust_wasm.read_bytes())
instance = Instance(module)
get_fact = instance.exports.get_fact
actual = get_fact()
assert "Chuck Norris" in actual
I get :
RuntimeError: Parameters of type [] did not match signature [I32] -> []
Any clues as to why NodeJs and Python disagree on the signature of the get_fact() function ?
Answering myself: you cannot use webassembly with strings this way. More info on this blog post: https://medium.com/wasm/strings-in-webassembly-wasm-57a05c1ea333
I would like to translate this code into actual TypeScript. Could you help me there?
import mongoose, { Promise } from 'mongoose';
Promise = global.Promise;
const db = {};
db.mongoose = mongoose;
db.user = require("./user.model");
db.role = require("./role.model");
db.ROLES = ["user", "admin", "moderator"];
export default db;
It would be great if you'd provide us with what you have tried and achieved so that it is easier to modify your code.
A way to do this would be to type this in a TypeScript file in an editor that provides linting for TypeScript like Visual Studio Code. Then check all the errors and fix them.
newbie here! I'm trying to make a basic ping to the Binance crypto exchange using its exposed REST API and node.js. Instead of coding everything from 0, I'm planning to use a wrapper package in https://github.com/binance-exchange/binance-api-node that facilities interaction. I've downloaded the binance-api-node code from github into my node.js project.
After installing the package, when trying to run the included basic getting-started code to get the time from the server:
import Binance from 'binance-api-node';
const client = Binance();
client.time().then(time => console.log(time));
I’m getting this error:
Uncaught TypeError: Binance is not a function
I also tried:
const client = new Binance();
but I get another error saying Binance is not a constructor.
This is the function declaration in the index.d.ts of binance-api-node
declare module 'binance-api-node' {
export default function(options?: {
apiKey?: string
apiSecret?: string
getTime?: () => number | Promise<number>
httpBase?: string
httpFutures?: string
wsBase?: string
wsFutures?: string
proxy?: string
}): Binance
...
Any help will be appreciated.
Thanks!
As stated in documentation:
If you do not have an appropriate babel config, you will need to use the basic commonjs requires:
const Binance = require('binance-api-node').default
const client = Binance();
Or like this, it worked for me:
import Binance from 'binance-api-node';
const client = Binance.default();
I'm learning typescript and every time i compile my project typescript adds this to my .js file
exports.__esModule = true;
This is apparently essential to the program if i am importing anything. But my browser says
Uncaught ReferenceError: exports is not defined
Why is this happening, I have tried defining it by creating a dummy var exports variable but then it tells me __esmodule cant edit property of undefined.
At this point typescript has made my project take much longer then its advertised rating of making projects quicker. I am about to give up and use regular javascript.
app.ts
import {privateRoom} from './room';
let socket : any = io();
function createRoomWithYoutubeID() {
const youtubeVideo : string = (<HTMLInputElement>document.getElementById('link_input')).value;
socket.emit('create_room', youtubeVideo);
}
console.log(privateRoom());
app.js
"use strict";
exports.__esModule = true;
var room_1 = require("./room");
var socket = io();
function createRoomWithYoutubeID() {
var youtubeVideo = document.getElementById('link_input').value;
socket.emit('create_room', youtubeVideo);
}
console.log(room_1.privateRoom());
I'm uploading an image file from React Native to AWS Lambda (Node 10.x) and want to verify the hash of the file I've sent matches the file received. To do this I'm using hashing in React Native and again in Lambda, but the hashes never match. Here are the relevant bits of code I've tried.
React Native
import RNFS from "react-native-fs";
const contentChecksum = await RNFS.hash(post.contentUrl, "md5");
Lambda (Node)
import AWS from "aws-sdk";
const crypto = require("crypto");
const s3 = new AWS.S3();
const data = await s3
.getObject({
Bucket: file.bucket,
Key: file.key
})
.promise();
const contentChecksum = crypto
.createHash("md5")
.update(data.Body)
.digest("hex");
These checksums never match. I've tried using base64 encoding in Node (data.Body.toString("base64")) and also sha256. What is the trick to calculating the checksum so they match in React Native and Node?
Edit: Here are the results from a recent test.
post.contentUrl: file:///Users/xxxxxxx/Library/Developer/CoreSimulator/Devices/2F2F4FD3-574E-40D7-BE6B-7080E926E70A/data/Containers/Data/Application/65A3FF67-98B2-444D-B75D-3717C1274FBC/Library/Caches/Camera/FDCD8F90-D24F-4E64-851A-96AB388C4B59.jpg
(the file is local on an iPhone)
contentChecksum from React Native: 48aa5cdb30f01719a2b12d481dc22f04
contentChecksum from Node (Lambda): 7b30b61a55d2c39707082293c625fc10
data.Body is a Buffer.
I also note that the eTag attribute on the S3 object matches the md5 checksum I'm calculating in Node. Since eTag is usually the md5 hash of the file, this tells me that I'm likely calculating the hash incorrectly in React Native, but I'm not sure how. I'm using the hash function from the react-native-fs package.
You can use the same code on React and AWS Lambda, that is Node.js.
So in your React.js application you could use the following code:
import * as React from 'react';
import crypto from 'crypto';
var key = 'YOUR_KEY';
export default class Test extends React.Component {
render() {
var hash = crypto.createHash('md5').update(key).digest('hex');
return (
<div>
{hash}
</div>
)
}
}
And the variable hash have to contains the same value you get on AWS.
In order to run you have to install the crypto library:
npm i --save react-native-crypto
Change the variable YOUR_KEY, then run the application:
npm start
And in the browser you should get:
4b751fef5e9660e3943173fd3e6c4224
You can use the crypto module.
To get a list of all available hash algorithms, you can use crypto.getHashes().
Here is a Nodejs example:
var crypto = require('crypto')
crypto.getHashes() // [ 'dsa', 'dsa-sha', ..., 'md5', ... ]
Here is a helper method for generating checksum value from string input:
var crypto = require('crypto')
function checksum(str, algorithm, encoding) {
return crypto
.createHash(algorithm || 'md5')
.update(str, 'utf8')
.digest(encoding || 'hex')
}
checksum('This is my test text');
checksum('This is my test text', 'sha1');