我正在尝试使用HMAC-SHA256算法创建签名,这是我的代码。 我正在使用US ASCII编码。
final Charset asciiCs = Charset.forName("US-ASCII");
final Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
final SecretKeySpec secret_key = new javax.crypto.spec.SecretKeySpec(asciiCs.encode("key").array(), "HmacSHA256");
final byte[] mac_data = sha256_HMAC.doFinal(asciiCs.encode("The quick brown fox jumps over the lazy dog").array());
String result = "";
for (final byte element : mac_data)
{
result += Integer.toString((element & 0xff) + 0x100, 16).substring(1);
}
System.out.println("Result:[" + result + "]");
我从上面的代码得到的结果是:
f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8
这与wiki中显示的相同
HMAC_SHA256("key", "The quick brown fox jumps over the lazy dog") = 0x f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8
除了0x
的。
如果我做的一切正常,或者我可以改进我的代码,我正在寻找想法/评论。
答案 0 :(得分:56)
这是我的解决方案:
public static String encode(String key, String data) throws Exception {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
sha256_HMAC.init(secret_key);
return Hex.encodeHexString(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
}
public static void main(String [] args) throws Exception {
System.out.println(encode("key", "The quick brown fox jumps over the lazy dog"));
}
或者您可以返回Base64中编码的哈希:
Base64.encodeBase64String(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
十六进制的输出符合预期:
f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8
答案 1 :(得分:35)
0x表示后面的字符表示十六进制字符串。
0x1A == 1Ah == 26 == 1A
所以0x只是为了澄清输出的格式,不用担心。
答案 2 :(得分:13)
你得到的答案是正确的。在上面的代码中有一个小问题,你需要在调用doFinal()
之前使用init(key) final Charset charSet = Charset.forName("US-ASCII");
final Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
final SecretKeySpec secret_key = new javax.crypto.spec.SecretKeySpec(charSet.encode("key").array(), "HmacSHA256");
try {
sha256_HMAC.init(secret_key);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
...
答案 3 :(得分:8)
如果你正在使用Guava,它的最新版本现在允许你使用
Hashing.hmacSha256()
答案 4 :(得分:7)
这对我来说很好
我添加了依赖
compile 'commons-codec:commons-codec:1.9'
参考:http://mvnrepository.com/artifact/commons-codec/commons-codec/1.9
我的功能
public String encode(String key, String data) {
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
sha256_HMAC.init(secret_key);
return new String(Hex.encodeHex(sha256_HMAC.doFinal(data.getBytes("UTF-8"))));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
答案 5 :(得分:1)
用于生成编码(HMAC-x)签名的Java简单代码。 (使用Java-8和Eclipse进行尝试)
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import com.sun.org.apache.xml.internal.security.utils.Base64;
/**
* Encryption class to show how to generate encoded(HMAC-x) signatures.
*
*/
public class Encryption {
public static void main(String args[]) {
String message = "This is my message.";
String key = "your_key";
String algorithm = "HmacMD5"; // OPTIONS= HmacSHA512, HmacSHA256, HmacSHA1, HmacMD5
try {
// 1. Get an algorithm instance.
Mac sha256_hmac = Mac.getInstance(algorithm);
// 2. Create secret key.
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), algorithm);
// 3. Assign secret key algorithm.
sha256_hmac.init(secret_key);
// 4. Generate Base64 encoded cipher string.
String hash = Base64.encode(sha256_hmac.doFinal(message.getBytes("UTF-8")));
// You can use any other encoding format to get hash text in that encoding.
System.out.println(hash);
/**
* Here are the outputs for given algorithms:-
*
* HmacMD5 = hpytHW6XebJ/hNyJeX/A2w==
* HmacSHA1 = CZbtauhnzKs+UkBmdC1ssoEqdOw=
* HmacSHA256 =gCZJBUrp45o+Z5REzMwyJrdbRj8Rvfoy33ULZ1bySXM=
* HmacSHA512 = OAqi5yEbt2lkwDuFlO6/4UU6XmU2JEDuZn6+1pY4xLAq/JJGSNfSy1if499coG1K2Nqz/yyAMKPIx9C91uLj+w==
*/
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
}
}
注意:您可以使用任何其他算法,并可以尝试生成
HmacMD5
,HmacSHA1
,HmacSHA256
,HmacSHA512
个签名。
答案 6 :(得分:1)
很抱歉迟到了,我已经尝试了以上所有答案,但没有一个能给我正确的价值。在做了大量的R& D后,我找到了一个简单的方法,给了我确切的价值。
在您的班级中声明此方法
private String hmacSha(String KEY, String VALUE, String SHA_TYPE) {
try {
SecretKeySpec signingKey = new SecretKeySpec(KEY.getBytes("UTF-8"), SHA_TYPE);
Mac mac = Mac.getInstance(SHA_TYPE);
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(VALUE.getBytes("UTF-8"));
byte[] hexArray = {(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f'};
byte[] hexChars = new byte[rawHmac.length * 2];
for ( int j = 0; j < rawHmac.length; j++ ) {
int v = rawHmac[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
使用此
Log.e("TAG", "onCreate: "+hmacSha("key","text","HmacSHA256"));
<强>验证强>
1.Android工作室输出
2.在线HMAC生成器输出(访问在线Genrator的here)
答案 7 :(得分:0)
这是我的解决方案:
public String HMAC_SHA256(String secret, String message)
{
String hash="";
try{
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
hash = Base64.encodeToString(sha256_HMAC.doFinal(message.getBytes()), Base64.DEFAULT);
}catch (Exception e)
{
}
return hash.trim();
}
答案 8 :(得分:0)
如果您有机会找到解决方法如何在这里计算HMAC-SHA256,但是你得到了这样的例外:
java.lang.NoSuchMethodError:没有静态方法 encodeHexString([B)Ljava /郎/字符串;在班上 Lorg /阿帕奇/公地/编解码器/二进制/己烷;或者它的超级课程 (声明&#39; org.apache.commons.codec.binary.Hex&#39;出现在 /system/framework/org.apache.http.legacy.boot.jar)
然后使用:
public static String encode(String key, String data) {
try {
Mac hmac = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
hmac.init(secret_key);
return new String(Hex.encodeHex(hmac.doFinal(data.getBytes("UTF-8"))));
} catch (Exception e) {
throw new RuntimeException(e);
}
}