본문 바로가기

bouncy castle

[bouncy castle] AES CMAC 128 example

AES CMAC Example

 

AES CMAC 128에서 128의 의미는 CMAC Block Size를 bit로 표기한 것으로 16 byte key 길이를 의미한다.

 

public byte[] aesCmac128(byte[] key, byte[] text) {
    //Create CMAC / AES / 128 bit 
    CMac mac = new CMac(new AESEngine(), 128);
    
    mac.init(new KeyParameter(key));
    byte[] output = new byte[mac.getMacSize()];
    mac.update(text, 0, text.length);
    mac.doFinal(output, 0);
    return output;
}

public void aes_cmac_test_001() {
    byte[] key = { // "ABCDEFGHIJKLMNOP"
        (byte)0x41, (byte)0x42, (byte)0x43, (byte)0x44, (byte)0x45, (byte)0x46, (byte)0x47, (byte)0x48,
        (byte)0x49, (byte)0x4a, (byte)0x4b, (byte)0x4c, (byte)0x4d, (byte)0x4e, (byte)0x4f, (byte)0x50
    };
    byte[] txt = { // "Hello world"
        (byte)0x48, (byte)0x65, (byte)0x6c, (byte)0x6c, (byte)0x6f, (byte)0x20, (byte)0x77, (byte)0x6f, 
        (byte)0x72, (byte)0x6c, (byte)0x64
    };
    Mac mac = new Mac();
    byte[] ret = mac.aesCmac128(key, txt);
    assertEquals("7E6F0950FB03F381BA82D350F88B7638", toHex(ret));
}

 

결과: Hello world input 값의 AES CMAC 결과물

7E:6F:09:50:FB:03:F3:81:BA:82:D3:50:F8:8B:76:38

 

AES CMAC 128에 Initialize Vector을 이용한 예제

public byte[] aesCmac128(byte[] key, byte[] text, byte[] iv) {
    //Create CMAC With IV / AES / 128 bit
    CMac mac = new CMacWithIV(new AESEngine(), 128);
    // create Key Parameter with IV
    mac.init(new ParametersWithIV(new KeyParameter(key), iv));
    byte[] output = new byte[mac.getMacSize()];
    mac.update(text, 0, text.length);
    mac.doFinal(output, 0);
    return output;
}

public void aes_cmac_test_001() {
    byte[] key = { // "ABCDEFGHIJKLMNOP"
        (byte)0x41, (byte)0x42, (byte)0x43, (byte)0x44, (byte)0x45, (byte)0x46, (byte)0x47, (byte)0x48,
        (byte)0x49, (byte)0x4a, (byte)0x4b, (byte)0x4c, (byte)0x4d, (byte)0x4e, (byte)0x4f, (byte)0x50
    };
    byte[] txt = { // "Hello world"
        (byte)0x48, (byte)0x65, (byte)0x6c, (byte)0x6c, (byte)0x6f, (byte)0x20, (byte)0x77, (byte)0x6f, 
        (byte)0x72, (byte)0x6c, (byte)0x64
    };
    byte[] iv = new byte[16];
    iv[15] = 0x01;
    Mac mac = new Mac();
    byte[] ret = mac.aesCmac128(key, txt);
    assertEquals("7E6F0950FB03F381BA82D350F88B7638", toHex(ret));
}

 

결과: Hello world input 값의 AES CMAC 결과물

3E:3B:A4:15:A2:37:74:9D:9F:E4:3D:32:D0:4D:BE:48

 

코드 위치 

https://github.com/coolbong/BouncyCastleExample/blob/master/src/main/java/io/github/coolbong/Mac.java

 

'bouncy castle' 카테고리의 다른 글

[bouncy castle] SEED ECB Example  (0) 2023.08.05
[bouncy castle] HMAC-MD5, HMAC-SHA1 example  (0) 2023.08.05
[bouncy castle] Random generator  (0) 2023.08.01
[bouncy castle] hash SHA1, SHA256, SHA512  (0) 2023.07.31
[bouncy castle] hash md5  (0) 2023.07.31