Javascript React Native/JS的SHA256 ComputeHash的等效版本(来自C#)
我正在尝试构建一个等效版本的SHA256 ComputeHash(来自C#,与下面示例中的输出完全相同),以响应Native/JavaScript。 以下是C#: 有谁知道JavaScript有什么问题,或者是否存在与C#one完全相同的版本吗? 解决方案1: 安装人 试试这个,它会给出与c相同的结果# 代码:Javascript React Native/JS的SHA256 ComputeHash的等效版本(来自C#),javascript,c#,react-native,hash,expo,Javascript,C#,React Native,Hash,Expo,我正在尝试构建一个等效版本的SHA256 ComputeHash(来自C#,与下面示例中的输出完全相同),以响应Native/JavaScript。 以下是C#: 有谁知道JavaScript有什么问题,或者是否存在与C#one完全相同的版本吗? 解决方案1: 安装人 试试这个,它会给出与c相同的结果# 代码: import React, { Component } from "react"; import { Text, StyleSheet, View } from "react-n
import React, { Component } from "react";
import { Text, StyleSheet, View } from "react-native";
import * as Crypto from "expo-crypto";
const isNullOrWhitespace = (input) => {
if (typeof input === "undefined" || input == null) return true;
return input.replace(/\s/g, "").length < 1;
};
const hash = async (input) => {
if (isNullOrWhitespace(input)) {
return "";
}
let hash = await Crypto.digestStringAsync(
Crypto.CryptoDigestAlgorithm.SHA256,
input
);
const sBuilder = await hash.toString(16);
return `0x${sBuilder.toLowerCase()}`;
};
export default class App extends Component {
state = {
encodedString: "",
};
async UNSAFE_componentWillMount() {
const result = await hash("StringIWantToHash"); //here you can pass your string
this.setState({ encodedString: result });
}
render() {
const { encodedString } = this.state;
return (
<View style={styles.container}>
<Text>{encodedString}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
});
试试这个,它会给出与c相同的结果#
var CryptoJS=require(“CryptoJS”);
常量isNullOrWhitespace=(输入)=>{
if(typeof input==“undefined”| | input==null)返回true;
返回输入。替换(/\s/g,“”)。长度<1;
};
常量哈希=(输入)=>{
if(isNullOrWhitespace(输入)){
返回“”;
}
让hash=CryptoJS.SHA256(输入);
const sBuilder=hash.toString(CryptoJS.enc.Hex);
返回`0x${sBuilder.toLowerCase()}`;
};
const result=hash(“StringIWantToHash”);
console.log(结果,“结果”);//它将给出与C相同的结果#
解决方案1:使用UTF8而不是Unicode
这是一个编码问题
Encoding.Unicode
是微软对UTF-16(一种双宽编码,由于历史原因在Windows世界中使用,但其他人不使用)的误导性名称。(见答覆)
您应该改为使用Encoding.UTF8.GetBytes
像这样使用库:
const jssha=require('js-sha256')
函数散列(输入)
{
常量hashString=“0x”+jssha.sha256(输入)
返回哈希字符串;
}
const hashResult=hash(“StringIWantToHash”)
//输出:0x29c506d0d69a16e413d63921b7de79525c43715931d8d93127dbeb46eacda2f9
只需使用UTF8编码,我们就可以在C语言中实现类似的效果:
公共静态字符串哈希(字符串输入)
{
if(string.IsNullOrWhiteSpace(input))返回“”;
使用(SHA256 hasher=SHA256.Create())
{
//将输入字符串转换为字节数组并计算哈希。
byte[]data=hasher.ComputeHash(Encoding.UTF8.GetBytes(input));//注意这里的UTF8
//创建新的Stringbuilder以收集字节
//并创建一个字符串。
StringBuilder sBuilder=新StringBuilder();
//循环遍历散列数据的每个字节
//并将每个字符串格式化为十六进制字符串。
for(int i=0;i
另外,我相信其他有助于计算SHA256哈希的JS/React本机库也使用UTF8编码,因此我认为您可以使用任何其他加密库
解决方案2:如果需要使用Unicode怎么办?
在这种情况下,您需要在JS代码中手动表示C#编码。当您使用Unicode编码时,如果字符串中的每个字节都是纯拉丁字符,则每个字节后面都会出现“0”字节。对于其他符号(超过255个数字),Unicode需要2个字节
var input=“StringIWantToHash”;
var encodedInput=Encoding.Unicode.GetBytes(输入);
//输出:[83,0,116,0,114,0,105,0,110,0,…]
因此,我们需要在JS代码中表示:
const jssha=require('js-sha256')
函数散列(输入)
{
var字节=[];
对于(变量i=0;i>0]);
}
常量hashString=“0x”+jssha.sha256(字节)
返回哈希字符串;
}
const hashResult=hash(“StringIWantToHash”)
//输出:0x029dbc4b54b39bed6d684175b2d76cc5622c60fe91f0bde9865b977d0d9a531d
是否尝试此库?还可以通过使用hmacSha256
alsoSo查看您是否说它会为相同的输入生成不同的结果?@Raj yes,确实正确。好的。你有没有试着把它转换成Base64
?@Raj我不明白为什么那会有什么不同,那只会让结果更糟。我刚刚试过:)下面是一个我用一些输入来尝试的例子。输入:test2React Native/Expo返回:0x60303ae22b998861bce3b28f33eec1be758a213c86c93c076dbe9f558c11c752
C返回:0x39A227298DC7E6E5D109AB36EC280F6CD3B4B7440AF5C739ED808D4EC02AAE4
正确的是C,因为我们在数据库中也使用了C。这是什么原因造成的?您能在这里发布输入字符串以便于输入吗我能确定哪一个是真正的问题吗?我使用的输入是“test2”,没有“@Muhammed Numan Sorry to known:”,但我仍然非常感谢您的解决方案!没有像你这样的人,这些问题永远不会得到回答^^我不知道怎么了,但对我来说,“StringiWantoHash”总是“0x029DBC4B54B39BED684175B2D76CC5622C60FE91F0BDE9865B977D0D9A531D
”在我这边,而JS是“0x29C506D0D69A16E413D6921B7DE79525C43715931D8D93127DB46EACDA2F9
”。C#one“0x029DBC4B54B39BED684175B2D76CC5622C60FE91F0BDE9865B977D0D9A531D
”是正确的。我想知道出了什么问题。Hmm@KevinJensenPetersen如果使用Encoding.Unicode.GetBytes
,我也会得到0x029dbc4b54b39bed6d684175b2d76cc5622c60fe91f0bde9865b977d0d9a531d
。如果我使用Encoding.UTF8.GetBytes
我有这个散列:0x29c506d0d69a16e413d63921b7de79525c43715931d8d93127dbeb46eacda2f9
使用Unicode
生成的散列不正确。改为使用UTF8
hash。我不能使用UTF8,因为我们的数据库依赖于Unicode。因为正确的是0x029dbc4b54b39bed6d684175b2d76cc5622c60fe91f0bde9865b977d0d9a531d
(数据库处理该格式)@KevinJensenPete
import * as Crypto from 'expo-crypto';
const hash = await Crypto.digestStringAsync(
Crypto.CryptoDigestAlgorithm.SHA256,
"StringIWantToHash"
);
yarn add sha256
import React, { Component } from "react";
import { Text, StyleSheet, View } from "react-native";
const sha256 = require("sha256");
const isNullOrWhitespace = (input) => {
if (typeof input === "undefined" || input == null) return true;
return input.replace(/\s/g, "").length < 1;
};
const getByteArray = (input) => {
let bytes = [];
for (var i = 0, k = 0; i < input.length; i++, k += 2) {
bytes[k] = input.charCodeAt(i);
bytes[k + 1] = 0;
}
return bytes;
};
const hash = async (input) => {
if (isNullOrWhitespace(input)) {
return "";
}
var bytes = getByteArray(input);
const hashString = "0x" + sha256(bytes, { asBytes: false });
return hashString;
};
export default class App extends Component {
state = {
encodedString: "",
};
async UNSAFE_componentWillMount() {
const encodedString = await hash("test2"); //0x39a2272982dc7e6e5d109ab36ec280f6cd3b4b7440af5c739ed808d4ec02aae4
this.setState({ encodedString: encodedString });
}
render() {
const { encodedString } = this.state;
return (
<View style={styles.container}>
<Text>{encodedString}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
});
await hash.toString(16);
import React, { Component } from "react";
import { Text, StyleSheet, View } from "react-native";
import * as Crypto from "expo-crypto";
const isNullOrWhitespace = (input) => {
if (typeof input === "undefined" || input == null) return true;
return input.replace(/\s/g, "").length < 1;
};
const hash = async (input) => {
if (isNullOrWhitespace(input)) {
return "";
}
let hash = await Crypto.digestStringAsync(
Crypto.CryptoDigestAlgorithm.SHA256,
input
);
const sBuilder = await hash.toString(16);
return `0x${sBuilder.toLowerCase()}`;
};
export default class App extends Component {
state = {
encodedString: "",
};
async UNSAFE_componentWillMount() {
const result = await hash("StringIWantToHash"); //here you can pass your string
this.setState({ encodedString: result });
}
render() {
const { encodedString } = this.state;
return (
<View style={styles.container}>
<Text>{encodedString}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
});
yarn add crypto-js
var CryptoJS = require("crypto-js");
const isNullOrWhitespace = (input) => {
if (typeof input === "undefined" || input == null) return true;
return input.replace(/\s/g, "").length < 1;
};
const hash = (input) => {
if (isNullOrWhitespace(input)) {
return "";
}
let hash = CryptoJS.SHA256(input);
const sBuilder=hash.toString(CryptoJS.enc.Hex);
return `0x${sBuilder.toLowerCase()}`;
};
const result=hash("StringIWantToHash");
console.log(result,"result"); // it will give the same result as C#