java - 调试 AES-CMAC,生成错误答案

标签 java debugging encryption cryptography aes

我正在使用以下代码和类从 AES_CMAC 生成多样化 key 。 doFinal 方法每次返回不同的 key ,因为输入和 masterKey 是常量。

 public byte[] calculateDiverseKey(byte [] input) throws InvalidKeyException, NoSuchAlgorithmException {
    AesCmac mac = null;
    mac = new AesCmac();
    SecretKey key = new SecretKeySpec(masterKey, "AES");
    mac.init(key);  //set master key
    mac.updateBlock(input); //given input
    for (byte b: input) System.out.print(" "+b);
    return mac.doFinal();
    }

AesCmac.java类

//package fi.aalto.spothip.crypto;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;






import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;

public class AesCmac {
    private static final byte CONSTANT = (byte) 0x87;
    private static final int BLOCK_SIZE = 16;

    private int macLength;
    private Cipher aesCipher;

    private byte[] buffer;
    private int bufferCount;

    private byte[] k1;
    private byte[] k2;

    public AesCmac() throws NoSuchAlgorithmException {
        this(BLOCK_SIZE);
    }

    public AesCmac(int length) throws NoSuchAlgorithmException {
        if (length > BLOCK_SIZE) {
            throw new NoSuchAlgorithmException("AES CMAC maximum length is " + BLOCK_SIZE);
        }

        try {
            macLength = length;
            aesCipher = Cipher.getInstance("AES/CBC/NOPADDING");
            buffer = new byte[BLOCK_SIZE];
        } catch (NoSuchPaddingException nspe) {
            nspe.printStackTrace();
        }
    }

    private byte[] doubleSubKey(byte[] k) {
        byte[] ret = new byte[k.length];

        boolean firstBitSet = ((k[0]&0x80) != 0);
        for (int i=0; i<k.length; i++) {
            ret[i] = (byte) (k[i] << 1);
            if (i+1 < k.length && ((k[i+1]&0x80) != 0)) {
                ret[i] |= 0x01;
            }
        }
        if (firstBitSet) {
            ret[ret.length-1] ^= CONSTANT;
        }
        return ret;
    }

    public final void init(Key key) throws InvalidKeyException {
        if (!(key instanceof SecretKeySpec)) {
            throw new InvalidKeyException("Key is not of required type SecretKey.");
        }
        if (!((SecretKeySpec)key).getAlgorithm().equals("AES")) {
            throw new InvalidKeyException("Key is not an AES key.");
        }
        aesCipher.init(Cipher.ENCRYPT_MODE, key);

        // First calculate k0 from zero bytes
        byte[] k0 = new byte[BLOCK_SIZE];
        try {
            aesCipher.update(k0, 0, k0.length, k0, 0);
        } catch (ShortBufferException sbe) {}

        // Calculate values for k1 and k2
        k1 = doubleSubKey(k0);
        k2 = doubleSubKey(k1);

        aesCipher.init(Cipher.ENCRYPT_MODE, key);
        bufferCount = 0;
    }

    public final void updateByte(byte b) {
        updateBlock(new byte[] { b });
    }

    public final void updateBlock(byte[] data) {
        int currentOffset = 0;

        if (data.length < BLOCK_SIZE-bufferCount) {
            System.arraycopy(data, 0, buffer, bufferCount, data.length);
            bufferCount += data.length;
            return;
        } else if (bufferCount > 0) {
            System.arraycopy(data, 0, buffer, bufferCount, BLOCK_SIZE-bufferCount);
            try {
                aesCipher.update(buffer, 0, BLOCK_SIZE, buffer, 0);
            } catch (ShortBufferException sbe) {}
            currentOffset += BLOCK_SIZE-bufferCount;
            bufferCount = 0;
        }

        // Transform all the full blocks in data
        while (currentOffset+BLOCK_SIZE < data.length) {
            try {
                aesCipher.update(data, currentOffset, BLOCK_SIZE, buffer, 0);
            } catch (ShortBufferException sbe) {}
            currentOffset += BLOCK_SIZE;
        }

        // Save the leftover bytes to buffer
        if (currentOffset != data.length) {
            System.arraycopy(data, currentOffset, buffer, 0, data.length-currentOffset);
            bufferCount = data.length-currentOffset;
        }
    }

    public final byte[] doFinal() {
        byte[] subKey = k1;
        if (bufferCount < BLOCK_SIZE) {
            // Add padding and XOR with k2 instead
            buffer[bufferCount] = (byte) 0x80;
            for (int i=bufferCount+1; i<BLOCK_SIZE; i++)
                buffer[i] = (byte) 0x00;
            subKey = k2;
        }
        for (int i=0; i<BLOCK_SIZE; i++) {
            buffer[i] ^= subKey[i];
        }

        // Calculate the final CMAC calue
        try {
            aesCipher.doFinal(buffer, 0, BLOCK_SIZE, buffer, 0);
        }
        // These should never happen because we pad manually
        catch (ShortBufferException sbe) {}
        catch (IllegalBlockSizeException ibse) {}
        catch (BadPaddingException ibse) {}
        bufferCount = 0;

        byte[] mac = new byte[macLength];
        System.arraycopy(buffer, 0, mac, 0, macLength);
        return  mac;
    }

    public final byte[] calculateHash(byte[] data) {
        updateBlock(data);
        return doFinal();
    }
}

最佳答案

尝试指定一个明确的零 IV:

private static final IvParameterSpec ZERO_IV = new IvParameterSpec(new byte[16]); 

并像这样在您的两 (2) 个初始化方法中使用它:

aesCipher.init(Cipher.ENCRYPT_MODE, key, ZERO_IV);

注意这是一个特定于 AES-CMAC 实现的答案。不要将此答案用作您应该使用全零 IV 进行加密的指示,否则您的数据可能不会保持完全 secret 。

关于java - 调试 AES-CMAC,生成错误答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24874176/

相关文章:

azure - 不在 Azure Blob 存储上启用加密的原因?

python - 用 pandas 读取加密的 excel

mysql - postgresql中插入语句中的加密密码抛出错误(需要添加显式类型转换)

java - pitest 无法定位 junit 测试

java - 使用 com.jfrog.artifactory 插件时找不到方法

debugging - 为什么 !locks 对我不起作用?

visual-studio-2010 - 用于 x64 调试的 SOS 扩展

不拉伸(stretch)宽度的Java Swing JPanel

java - 线程 "main"java.io.FileNotFoundException : (The system cannot find the file specified) 中的异常

angularjs - 在 ionic 下调试 Angular ui-router