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');
Related
I am implementing Stripe in my project and getting this error on the browser: Failed prop type: The prop `stripeKey` is marked as required in `ReactStripeCheckout`, but its value is `undefined`.
I'm storing my publishable key in a .env file in the client folder:
REACT_APP_STRIPE = pk_mykeykey
And in my component, I've assigned the key to KEY:
const KEY = process.env.REACT_APP_STRIPE
And here's my Stripe component:
name="Lama Shop"
image="https://avatars.githubusercontent.com/u/1486366?v=4"
billingAddress
shippingAddress
description={`Your total is $${cart.total}`}
amount={cart.total * 100}
token={onToken}
stripeKey={KEY}
>
<Button>CHECKOUT NOW</Button>
</StripeCheckout>
I've console.logged the key, it returns undefined and the token also returns null.
Try:
re-starting the node-server again. Environment variables are only handled once in a react-app's lifecycle, which is on startup of the react app server.
Make sure your .env file is located in the same root directory as your package.json file, and if you aren't using create-react-app, make sure its included in your build script.
If the above steps didn't resolve your issue, you shouldn't need dotenv when building a react app, but you can import as such:
import * as dotenv from "dotenv"
//insert your config file path here
const configPath = "./path/to/.env"
const configVariables = dotenv.config(configPath)
const key = configVariables.REACT_APP_STRIPE
console.log(key)
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
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 used npm to install the Binance API node. I reach to the following step:
import Binance from 'binance-api-node'
const client = Binance()
// Authenticated client, can make signed calls
const client2 = Binance({
apiKey: 'xxx',
apiSecret: 'xxx',
getTime: xxx, // time generator function, optional, defaults to () => Date.now()
})
client.time().then(time => console.log(time))
Could you please guide me on how to run this part. The node module could be found on https://github.com/Ashlar/binance-api-node
You'll need to create your API key following this doc
2. Once you have your API key and secret key, you store in apiKey and apiSecret respectively.
3. 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 instead of ES6 import
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')