使用 JavaScript 计算 HMAC-SHA1 签名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25472966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculate HMAC-SHA1 Signature using JavaScript
提问by anchor
I am writing a JavaScript Client Application that needs to communicate with Server. I tried to implement the API, but i stuck on one method and I need help.
我正在编写一个需要与服务器通信的 JavaScript 客户端应用程序。我试图实现 API,但我坚持使用一种方法,我需要帮助。
Infect i don't know how to translate this from Java to JavaScript (I don't know where to find analog libraries written in javascript that are used in this method):
感染我不知道如何将其从 Java 转换为 JavaScript(我不知道在哪里可以找到在此方法中使用的用 javascript 编写的模拟库):
import java.security.SignatureException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* This class defines common routines for generating
* authentication signatures for AWS requests.
*/
public class Signature {
private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
/**
* Computes RFC 2104-compliant HMAC signature.
* * @param data
* The data to be signed.
* @param key
* The signing key.
* @return
* The Base64-encoded RFC 2104-compliant HMAC signature.
* @throws
* java.security.SignatureException when signature generation fails
*/
public static String calculateRFC2104HMAC(String data, String key)
throws java.security.SignatureException
{
String result;
try {
// get an hmac_sha1 key from the raw key bytes
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
// get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
mac.init(signingKey);
// compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(data.getBytes());
// base64-encode the hmac
result = Encoding.EncodeBase64(rawHmac);
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
return result;
}
}
This method is from AWS Documentations: Java Sample Code for Calculating HMAC-SHA1 Signatures
此方法来自 AWS 文档: 用于计算 HMAC-SHA1 签名的 Java 示例代码
I am asking if someone can give me some references (websites) where I can find solution or analog libraries, written in javascript.
我在问是否有人可以给我一些参考资料(网站),在那里我可以找到用 javascript 编写的解决方案或模拟库。
I searched AWS Documentation and SDK for JavaScript and I couldn't find translation in JS.
我搜索了适用于 JavaScript 的 AWS 文档和开发工具包,但在 JS 中找不到翻译。
Thanks very much in advance.
首先十分感谢。
回答by Mr37037
Hi i think this might be helpful for you.
您好,我认为这可能对您有所帮助。
Here you can find out the link to calculate hmac sha1:
在这里您可以找到计算 hmac sha1 的链接:
http://caligatio.github.io/jsSHA/
http://caligatio.github.io/jsSHA/
Here you can find the source code in javascript.
在这里你可以找到 JavaScript 的源代码。