Krishna
Krishna

Reputation: 263

MAC ISO 9797-1 MAC algorithm 3 and padding method 1 in Java?

Need to generate 35 bytes (70 characters) Alphanumerical data using ISO 9797-1 MAC algorithm 3 and padding method 1 in java.

I have tried using below code but its not generating 35 bytes (70 characters) Alphanumerical data and using key as 64 byte key.

public byte[] getRetailMAC(byte[] key, byte[] data) {
    int macSizeBits = 64;

    BlockCipher cipher = new DESEngine();

    Mac mac = new ISO9797Alg3Mac(cipher, macSizeBits);

    KeyParameter keyP = new KeyParameter(key);
    mac.init(keyP);
    mac.update(data, 0, data.length);

    // perform padding manually
    int n = cipher.getBlockSize();
    int zeroPaddingRequired = n - (data.length + n - 1) % n - 1; 
    for (int i = 0; i < zeroPaddingRequired; i++) {
        mac.update((byte) 0x00);
    }

    byte[] out = new byte[macSizeBits / Byte.SIZE];
    mac.doFinal(out, 0);

    return out;
}

and I expect the output is 35 bytes (70 characters) Alphanumerical data but actual output getting above code is :[B@2ee0d183.

Can anyone please help me on this.

Upvotes: 1

Views: 1410

Answers (1)

Topaco
Topaco

Reputation: 49390

  • The :[B@2ee0d183 is the object id (see Java: Syntax and meaning behind "[B@1ef9157"? Binary/Address?) of your byte-array, it's not the content! The method org.bouncycastle.util.encoders.Hex.toHexString(...) can be used to display the content as a hexadecimal string, i.e. if the byte-array consists of e.g. 3 bytes with the contents 0x42, 0x42 and 0x43, then this method returns the string 414243.
  • The maximum length of the MAC generated by ISO9797Alg3Mac is equal to the block length of the used cipher, i.e. of DES, which is 8 bytes. I.e. the parameter macSizeBits (length in bit) must be (a multiple of 8 and) less than or equal to 64. For larger sizes an exception is thrown in the doFinal-method. For this reason, a MAC with a length of 35 bytes cannot be generated (but of course several MACs can be concatenated until the desired length is reached).
  • Moreover, if no padding is defined in the constructor (as it's currently the case), zero-byte-padding (in this context also called padding method 1) is used by default. This means that the manual implementation of the zero-byte-padding is not necessary (but does not cause an error of course).

The last two points can be tested explicitly, or verified in the source code (https://www.bouncycastle.org/latest_releases.html, section Sources and JavaDoc, bcprov-jdk15on-161.zip).

Upvotes: 1

Related Questions