我需要计算字符串的SHA-256散列用密钥。 我发现这个代码:
public String computeHash(String input)
throws NoSuchAlgorithmException, UnsupportedEncodingException
{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.reset();
byte[] byteData = digest.digest(input.getBytes("UTF-8"));
StringBuffer sb = new StringBuffer();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
计算哈希没有密钥。 我怎样才能用密钥计算? 我搜查,但我没有发现任何的Android解决方案。 任何的想法 ?
看下面这个例子。
/**
* Encryption of a given text using the provided secretKey
*
* @param text
* @param secretKey
* @return the encoded string
* @throws SignatureException
*/
public static String hashMac(String text, String secretKey)
throws SignatureException {
try {
Key sk = new SecretKeySpec(secretKey.getBytes(), HASH_ALGORITHM);
Mac mac = Mac.getInstance(sk.getAlgorithm());
mac.init(sk);
final byte[] hmac = mac.doFinal(text.getBytes());
return toHexString(hmac);
} catch (NoSuchAlgorithmException e1) {
// throw an exception or pick a different encryption method
throw new SignatureException(
"error building signature, no such algorithm in device "
+ HASH_ALGORITHM);
} catch (InvalidKeyException e) {
throw new SignatureException(
"error building signature, invalid key " + HASH_ALGORITHM);
}
}
凡HASH_ALGORITHM被定义为:
private static final String HASH_ALGORITHM = "HmacSHA256";
public static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
Formatter formatter = new Formatter(sb);
for (byte b : bytes) {
formatter.format("%02x", b);
}
return sb.toString();
}
使用下面的代码,
/**
* Returns a hexadecimal encoded SHA-256 hash for the input String.
* @param data
* @return
*/
private static String getSHA256Hash(String data) {
String result = null;
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(data.getBytes("UTF-8"));
return bytesToHex(hash); // make it printable
}catch(Exception ex) {
ex.printStackTrace();
}
return result;
}
/**
* Use javax.xml.bind.DatatypeConverter class in JDK
* to convert byte array to a hexadecimal string. Note that this generates hexadecimal in upper case.
* @param hash
* @return
*/
private static String bytesToHex(byte[] hash) {
return DatatypeConverter.printHexBinary(hash);
}
要使用DatatypeConverter,从下面的链接下载jar文件。
http://www.java2s.com/Code/Jar/j/Downloadjavaxxmlbindjar.htm
文章来源: How can I calculate the SHA-256 hash of a string with a secret key in Android?