Skip to content

Instantly share code, notes, and snippets.

@kdevray
Forked from ishikawa/gist:88599
Created April 2, 2024 19:03
Show Gist options
  • Save kdevray/7fd66db8ffcce278b64fd0bff4ea58c9 to your computer and use it in GitHub Desktop.
Save kdevray/7fd66db8ffcce278b64fd0bff4ea58c9 to your computer and use it in GitHub Desktop.

Revisions

  1. @ishikawa ishikawa revised this gist Apr 1, 2009. 1 changed file with 13 additions and 0 deletions.
    13 changes: 13 additions & 0 deletions gistfile1.java
    Original file line number Diff line number Diff line change
    @@ -7,6 +7,19 @@
    import javax.crypto.spec.SecretKeySpec;


    /**
    * The <tt>HmacSha1Signature</tt> shows how to calculate
    * a message authentication code using HMAC-SHA1 algorithm.
    *
    * <pre>
    * % java -version
    * java version "1.6.0_11"
    * % javac HmacSha1Signature.java
    * % java -ea HmacSha1Signature
    * 104152c5bfdca07bc633eebd46199f0255c9f49d
    * </pre>
    *
    */
    public class HmacSha1Signature {
    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";

  2. @ishikawa ishikawa created this gist Apr 1, 2009.
    38 changes: 38 additions & 0 deletions gistfile1.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.security.SignatureException;
    import java.util.Formatter;

    import javax.crypto.Mac;
    import javax.crypto.spec.SecretKeySpec;


    public class HmacSha1Signature {
    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";

    private static String toHexString(byte[] bytes) {
    Formatter formatter = new Formatter();

    for (byte b : bytes) {
    formatter.format("%02x", b);
    }

    return formatter.toString();
    }

    public static String calculateRFC2104HMAC(String data, String key)
    throws SignatureException, NoSuchAlgorithmException, InvalidKeyException
    {
    SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
    Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
    mac.init(signingKey);
    return toHexString(mac.doFinal(data.getBytes()));
    }

    public static void main(String[] args) throws Exception {
    String hmac = calculateRFC2104HMAC("data", "key");

    System.out.println(hmac);
    assert hmac.equals("104152c5bfdca07bc633eebd46199f0255c9f49d");
    }
    }