javaencryptionmessage-digest

Should I do any transformation to AES CMAC provided key?


I've been provided with a java.util.String 32 characters length. The String contains 16 pairs of hexadecimal characters which represent the key that I should use on an AES and CMAC message signature creation.

I've a problem getting the correct message signed with the provided key, I'm using 'bouncycastle' library. I show you my code:

        KeyParameter parameter = new KeyParameter(KEY.getBytes(StandardCharsets.UTF_8));

        AESEngine aes = new AESEngine();
        CMac mac = new CMac(aes);
        mac.init(parameter);
        mac.update(message.getBytes(StandardCharsets.UTF_8), 0, message.getBytes(StandardCharsets.UTF_8).length);
        byte[] out = new byte[mac.getMacSize()];
        mac.doFinal(out, 0);

A partner is implementing this very code in C# with the same library. We found that byte in java has signed number representation although C# don't. Trying to make parallel implementation of this get's me a bit disoriented.

I'm able to get the proper int[] from 0 to 255 values that my partner gets when processing the key.


Solution

  • I had a poor specification of the problem. My inputs happened to be hex encoded (each 2 characters from the string should be treated as an hex number representation, each pair had to be converted to the byte representation of the number).

    This kind of encoding is also the usual way to represent the CMAC output so as a result I define 2 functions:

    
    public static byte[] stringToByteHexpairs(String input){
        
        byte[] output= new byte[input.length()/2];
        int k = 0;
        for (int i = 0; i <= input.length() - 2 ; i += 2) {
             String par = input.substring(i, i+2);
             output[k] = (byte) Integer.parseInt(par,16);
             k++;
        }
        return output;
    }
    
    public static String bytesToHexString(byte[] array) {
    
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < array.length; i++) {
            sb.append(String.format("%02X",array[i]));
        }
        return sb.toString();
    }
    
    

    And I use it before in place of the wrong byte transformation on the code I provided. BONUS I also add the output transformation that is expected:

    KeyParameter parameter = new KeyParameter(stringToByteHexpairs(KEY));
    byte[] messageBytes = stringToByteHexpairs(message);
    
    ...
    
    mac.update(messageBytes, 0, messageBytes.length);
    
    ...
    
    mac.doFinal(out, 0);
    return bytesToHexString(out);