【问题标题】:How to Hash String using SHA-1 with key?如何使用带有密钥的 SHA-1 散列字符串?
【发布时间】:2011-05-30 21:08:15
【问题描述】:

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

  • 数据
  • 钥匙

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

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


[我目前使用的代码]
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);
}

【问题讨论】:

  • 您使用什么代码进行转换?
  • SHA-1 with key .. 是 HMAC 吗?这样做的目的是什么?
  • @thejh 我正在更新答案。

标签: java android security hash sha1


【解决方案1】:

试试这样的:

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

}

SecretKeySpec 文档。

【讨论】:

  • 非常感谢回复,但是Base64.encodeBase64是从android.util.Base64还是org.kobjects.base64导入的?提前致谢。
  • 只是为了让你知道 API android.util.Base64 没有你提到的我使用的方法:android.util.Base64.encode(bytes, 0)
  • 在我的示例中,这是从 org.apache.commons.codec.binary 导入的,您可以从 commons.apache.org/codec/download_codec.cgi 下载它
【解决方案2】:

另一种解决方案是使用 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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-24
    • 2012-08-16
    • 2014-03-28
    • 2021-12-21
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多