简体   繁体   English

对于相同的输入,SHA1在Java和javascript中有所不同

[英]SHA1 varies in java and javascript for same input

Facing an issue while creating SHA1 from javascript and java. 从javascript和java创建SHA1时遇到问题。 The problem is both are different. 问题是不同的。 It is used for validating the client request to web server. 它用于验证对Web服务器的客户端请求。 That means client send a based64 encoded security key to server and server regenerate the same key and equate both are same. 这意味着客户端向服务器发送一个基于base64编码的安全密钥,并且服务器重新生成相同的密钥并等同于两者相同。 Please find below code for generating secret keys in client and server. 请在下面找到用于在客户端和服务器中生成密钥的代码。 Server 服务器

MessageDigest mDigest = null;
try {
    mDigest = MessageDigest.getInstance("SHA1");
} catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
}

String input = value1 + value1 + server_key;
byte[] result = mDigest.digest(input.getBytes());
String secret = Base64.encodeToString(result, Base64.NO_WRAP);
...
//comparison logic goes here

... ...

Client (java script) 客户端(Java脚本)

var input = value1 + value2 + server_key;
//http://code.google.com/p/crypto-js/
var hash = CryptoJS.SHA1(input);
var encoded  = base64Encode(hash.toString());

//WEB SERVICE INVOCATION FROM JAVASCRIPT GIES HERE.

The values value1, value1, server_key will be available in both client and server. 值value1,value1,server_key在客户端和服务器中均可用。 The issue we are facing is, the SHA1 generated in both client and server is not matching. 我们面临的问题是,客户端和服务器中生成的SHA1不匹配。 I understand the issue is in java its using getBytes() and in javascript using string value for generating SHA1. 我知道问题是在Java中使用getBytes()和在javascript中使用字符串值生成SHA1。 The CryptoJS.SHA1 does not support bytearray as parameter. CryptoJS.SHA1不支持字节数组作为参数。 We cannot change the server code as it is used by many client applications. 我们无法更改服务器代码,因为许多客户端应用程序都在使用它。 Any help will be much appreciated. 任何帮助都感激不尽。

In Java -> 在Java中->

byte[] result = mDigest.digest(input.getBytes()); 

and in JavaScript -> 并在JavaScript中->

var hash = CryptoJS.SHA1(input);. 

I belief this is the problem. 我相信这是问题所在。 In java the parameter is a bytearray and output is also a bytearray. 在Java中,参数是字节数组,输出也是字节数组。 But in javascript the parameter is var (string) and return is also var (string). 但是在javascript中,参数是var(字符串),返回值也是var(字符串)。 I 've also compared the output of CryptoJS.SHA1 with some online SHA1 generating tools. 我还比较了CryptoJS.SHA1和一些在线SHA1生成工具的输出。 The comparison is true. 比较是正确的。 I am not an expert in this area. 我不是这方面的专家。 If you can explain more, it will be more helpful. 如果您能解释得更多,将会更有帮助。

I managed it to do in another way. 我设法用另一种方式来做。 My application is a cordova based application. 我的应用程序是基于cordova的应用程序。 So generated the sha1 and encoded it from java and objC and invoked it using cordova plugins. 因此生成了sha1并从java和objC对其进行了编码,并使用cordova插件对其进行了调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM