开发者

How to Hash String using SHA-1 with key?

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

  • Data
  • Key

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

I am greatly appreciative of any guidance or help.


[The code that I currently use]

private void convertStringToSH开发者_如何学JAVAA1()
{
        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);
}


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

}

SecretKeySpec docs.


Another solution would be using apache commons codec library:

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

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜