Skip to content

Instantly share code, notes, and snippets.

@mmoayyed
Created March 31, 2023 17:36
Show Gist options
  • Save mmoayyed/2867d73ba13705623aa784a2d8a4ba49 to your computer and use it in GitHub Desktop.
Save mmoayyed/2867d73ba13705623aa784a2d8a4ba49 to your computer and use it in GitHub Desktop.
import org.apache.commons.codec.binary.Hex
import org.apache.commons.codec.digest.HmacUtils
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import java.nio.charset.StandardCharsets
def key =
"0x9B7A8A71592A41F4C935A159768E7771AF4F814CA7DDAC80491A355B072090CF7A3D26DCBD7123C26A1134D291FD5044355B1F124D7127902693F85921545F20109D52472A1E0F0D3E0069357FA7000C2CDA1EEAAADF5B81046687472DC8CA730DC3AD0C0359B7ED2F04398FAD8FE3C47881D5AA82BA065D969C931CBE2B92A4"
try {
// first approach
def result = new HmacUtils(org.apache.commons.codec.digest.HmacAlgorithms.HMAC_SHA_512, key).hmacHex("P@ssword_1234")
println result
// second approach
Mac sha512Hmac = Mac.getInstance("HmacSHA512");
final byte[] byteKey = key.getBytes(StandardCharsets.UTF_8);
SecretKeySpec keySpec = new SecretKeySpec(byteKey, "HmacSHA512");
sha512Hmac.init(keySpec);
byte[] macData = sha512Hmac.doFinal("P@ssword_1234".getBytes(StandardCharsets.UTF_8));
result = Hex.encodeHexString(macData)
println result
} catch (final Exception e) {
e.printStackTrace();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment