Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Iso9797Alg3 - Retail MAC Calculation in Java
package cz.monetplus.mac;
import static org.assertj.core.api.Assertions.assertThat;
import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.Mac;
import org.bouncycastle.crypto.engines.DESEngine;
import org.bouncycastle.crypto.macs.ISO9797Alg3Mac;
import org.bouncycastle.crypto.params.KeyParameter;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Iso9797Alg3MacTest {
private static final Logger log = LoggerFactory.getLogger(Iso9797Alg3MacTest.class);
private static final String baseMsg = "30323030723c54c128e88001164761739001010010000000000000000350050911511500219811511505091012456702030011000811012345678901344761739001010010d10122011143878089303030303031303032313938574552543031333241424344454631323334353637383943415244204143434550544f52204e414d45202020202020205a4c494e202020202020202020435a7642313233343536373839303132333434355e504144494c4c412f4c2e202020202020202020202020202020205e39393031313230303030303030303030303030302a2a5858582a2a2a2a2a2a0203";
private static final String macKey = "7CA110454A1A6E57E1ED3BF85377FE55";
@Test
public void iso9797Alg3MacTest() throws Exception {
final BlockCipher cipher = new DESEngine();
final KeyParameter key = createKey(Hex.decodeHex(macKey.toCharArray()));
final byte[] dataToMac = Hex.decodeHex(baseMsg.toCharArray());
final byte[] genMac = generateIso9797Alg3Mac(key, cipher, dataToMac);
assertThat(genMac).isEqualTo(Hex.decodeHex("0015da835ffd7293".toCharArray()));
}
private byte[] generateIso9797Alg3Mac(KeyParameter key, BlockCipher cipher, byte[] data) {
final Mac mac = new ISO9797Alg3Mac(cipher);
mac.init(key);
mac.update(data, 0, data.length);
final byte[] out = new byte[8];
mac.doFinal(out, 0);
log.trace("Generated MAC : {}",Hex.encodeHexString(out));
return out;
}
private static KeyParameter createKey(byte[] key) {
if (key.length != 16) {
throw new RuntimeException("Unsupported key len " + key.length + " B for ISO9797Alg3Mac");
}
return new KeyParameter(key);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment