HMAC MD5 Example
public byte[] hmacMd5(byte[] key, byte[] text) {
HMac mac = new HMac(new MD5Digest());
mac.init(new KeyParameter(key));
int macSize = mac.getMacSize();
byte[] output = new byte[macSize];
mac.update(text, 0, text.length);
mac.doFinal(output, 0);
return output;
}
public void hmac_md5_rfc_2202_test_001_01() {
//test_case = 1
//key = 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
//key_len = 16
//data = "Hi There"
//data_len = 8
//digest = 0x9294727a3638bb1c13f48ef8158bfc9d
byte[] key = {
(byte)0x0b, (byte)0x0b, (byte)0x0b, (byte)0x0b, (byte)0x0b, (byte)0x0b, (byte)0x0b, (byte)0x0b,
(byte)0x0b, (byte)0x0b, (byte)0x0b, (byte)0x0b, (byte)0x0b, (byte)0x0b, (byte)0x0b, (byte)0x0b
};
byte[] msg = "Hi There".getBytes(StandardCharsets.UTF_8);
Mac mac = new Mac();
byte[] ret = mac.hmacMd5(key, msg);
assertEquals("9294727A3638BB1C13F48EF8158BFC9D", toHex(ret));
}
HMAC SHA1 Example
public byte[] hmacSha1(byte[] key, byte[] text) {
HMac mac = new HMac(new SHA1Digest());
mac.init(new KeyParameter(key));
int macSize = mac.getMacSize();
byte[] output = new byte[macSize];
mac.update(text, 0, text.length);
mac.doFinal(output, 0);
return output;
}
@Test
public void hmac_sha1_rfc_2202_test_008() {
//test_case = 2
//key = "Jefe"
//key_len = 4
//data = "what do ya want for nothing?"
//data_len = 28
//digest = 0xeffcdf6ae5eb2fa2d27416d5f184df9c259a7c79
byte[] key = "Jefe".getBytes(StandardCharsets.UTF_8);
byte[] msg = "what do ya want for nothing?".getBytes(StandardCharsets.UTF_8);
Mac mac = new Mac();
byte[] ret = mac.hmacSha1(key, msg);
assertEquals("EFFCDF6AE5EB2FA2D27416D5F184DF9C259A7C79", toHex(ret));
}
RFC 2202에 HMAC-MD5, HMAC-SHA1에 대한 Testcase들을 제공하고 있다.
참고자료 및 소스 코드
https://www.ietf.org/rfc/rfc2202.txt
'bouncy castle' 카테고리의 다른 글
[bouncy castle] File Hash(SHA256) 값 구하기 (0) | 2023.08.05 |
---|---|
[bouncy castle] SEED ECB Example (0) | 2023.08.05 |
[bouncy castle] AES CMAC 128 example (0) | 2023.08.04 |
[bouncy castle] Random generator (0) | 2023.08.01 |
[bouncy castle] hash SHA1, SHA256, SHA512 (0) | 2023.07.31 |