6

我正在将一个图像文件从 React Native 上传到 AWS Lambda(节点 10.x),并且想要验证我发送的文件的哈希值是否与收到的文件匹配。为此,我在 React Native 和 Lambda 中使用散列,但散列从不匹配。这是我尝试过的相关代码。

反应原生

import RNFS from "react-native-fs";
const contentChecksum = await RNFS.hash(post.contentUrl, "md5");

Lambda(节点)

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");

这些校验和从不匹配。我试过base64在 Node ( data.Body.toString("base64")) 和sha256. 计算校验和以使其在 React Native 和 Node 中匹配的技巧是什么?

编辑:这是最近一次测试的结果。

post.contentUrlfile:///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

(该文件在 iPhone 上是本地的)

contentChecksum来自 React Native:48aa5cdb30f01719a2b12d481dc22f04

contentChecksum从节点(Lambda):7b30b61a55d2c39707082293c625fc10

data.Body是一个Buffer

我还注意到 S3 对象上的 eTag 属性与我在 Node.js 中计算的 md5 校验和相匹配。由于 eTag通常是文件的 md5 哈希,这告诉我我可能在 React Native 中错误地计算了哈希,但我不确定如何计算。我正在使用 react-native-fs 包中的哈希函数。

4

2 回答 2

1

您可以在ReactAWS Lambda上使用相同的代码,即Node.js。

因此,在您的React.js应用程序中,您可以使用以下代码:

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>
        )
    }

}

并且该变量hash必须包含您在 AWS 上获得的相同值。

为了运行,您必须安装加密库:

npm i --save react-native-crypto

更改变量 YOUR_KEY,然后运行应用程序:

npm start

在浏览器中你应该得到:

4b751fef5e9660e3943173fd3e6c4224
于 2019-09-16T12:30:43.540 回答
1

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');
于 2019-09-17T13:28:38.810 回答