java 如何使用带密钥的 SHA-1 散列字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4534370/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:48:37  来源:igfitidea点击:

How to Hash String using SHA-1 with key?

javaandroidsecurityhashsha1

提问by Ahmad Kayyali

The time I used to develop applications on iPhone I was converting String to SHA1 with two combination:

我曾经在 iPhone 上开发应用程序时,我使用两种组合将 String 转换为 SHA1:

  • Data
  • Key
  • 数据
  • 钥匙

Now I am developing an Android application and I did not any example for how to calculate SHA1 With key.

现在我正在开发一个 Android 应用程序,我没有任何关于如何使用密钥计算 SHA1 的示例。

I am greatly appreciative of any guidance or help.

我非常感谢任何指导或帮助。



[The code that I currently use][我目前使用的代码]

private void convertStringToSHA1()
{
        String sTimeStamp  = new SimpleDateFormat("MM/dd/yyyy HH:MM:SS").format(new java.util.Date());
        String sStringToHash = String.format("%1$s\n%2$s", "Username",sTimeStamp);

        MessageDigest cript = MessageDigest.getInstance("SHA-1");
        cript.reset();

        cript.update(sStringToHash.getBytes("utf-8"));
        sStringToHash = new BigInteger(1, cript.digest()).toString(16);
}

采纳答案by evilone

Try something like that:

尝试这样的事情:

private String sha1(String s, String keyString) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {

SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(key);

byte[] bytes = mac.doFinal(s.getBytes("UTF-8"));

return new String( Base64.encodeBase64(bytes));

}

SecretKeySpecdocs.

SecretKeySpec文档。

回答by Fran García

Another solution would be using apache commons codec library:

另一种解决方案是使用 apache commons 编解码器库:

@Grapes(
    @Grab(group='commons-codec', module='commons-codec', version='1.10')
)

import org.apache.commons.codec.digest.HmacUtils

HmacUtils.hmacSha1Hex(key.bytes, message.bytes)