Skip to content

Instantly share code, notes, and snippets.

@masatomix
Created August 18, 2017 00:44
Show Gist options
  • Save masatomix/e5f76d30b917c46be8343346c520d217 to your computer and use it in GitHub Desktop.
Save masatomix/e5f76d30b917c46be8343346c520d217 to your computer and use it in GitHub Desktop.
HmacSHA256 によるハッシュのサンプル
package nu.mine.kino;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.HmacUtils;
public class HmacSha256Main {
public static void main(String[] args)
throws InvalidKeyException, NoSuchAlgorithmException {
String data = "Hello, world!";
String key = "aaaaaaaaaabbbbbbaaaaaaaaaabbbbbb"; // <-256bitの共通鍵
String result01 = Base64
.encodeBase64URLSafeString(hmacSha256(key, data));
String result02 = Base64
.encodeBase64URLSafeString(HmacUtils.hmacSha256(key, data));
System.out.println(result01);
System.out.println(result02);
}
public static byte[] hmacSha256(String secretKey, String data)
throws NoSuchAlgorithmException, InvalidKeyException {
String algorithm = "HmacSHA256";
SecretKey key = new SecretKeySpec(secretKey.getBytes(), algorithm);
Mac mac = Mac.getInstance(algorithm);
mac.init(key);
mac.update(data.getBytes());
return mac.doFinal();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment