如何使用Bouncycastle JCE提供程序的AES CCM - CCMParameters

6

能否使用JCE执行CCM操作?

我在互联网上看到很多使用非JCE bouncycastle类的例子,特别是它们调用init并传递一个CCMParameters对象。

问题在于,这个CCMParameters对象不从AlgorthmParameters或AlgorithmParameterSpec派生,因此似乎没有办法将其传递给Cipher.init()(在使用Cipher.getInstance("AES/CCM/NoPadding")获取Cipher对象之后)。

怎么才能做到这一点呢?


1
已经有人回复了:关于BC _provider_,请参考https://crypto.stackexchange.com/questions/51834/can-java-decrypt-a-4-byte-mic(尽管它在那里被投票为离题)。 - dave_thompson_085
2个回答

2

你好,这里是AES-CCM算法的示例代码,其中所有通常名称都是输入参数。请注意十六进制数据字节和其他所有内容。

import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.modes.CCMBlockCipher;
import org.bouncycastle.crypto.params.CCMParameters;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.util.encoders.Hex;

public class AesCcm {
    public static void main(String[] args) throws IllegalStateException, InvalidCipherTextException {
    int macSize = 125;
    byte[] key = new byte[32];
    byte[] keybyte = "test123".getBytes();
    byte[] inputNouc = "abcdefghijklm".getBytes();
    for (int I = 0; I < keybyte.length; I++) {
        key[I] = keybyte[I];
    }

//      Input data in HEX format
    String input = "ed88fe7b95fa0ffa190b7ab33933fa";

    byte[] inputData= Hex.decode(input);

    BlockCipher engine = new AESEngine();
    CCMParameters params = new CCMParameters(new KeyParameter(key),
            macSize, inputNouc, null);

    CCMBlockCipher cipher = new CCMBlockCipher(engine);
    cipher.init(true, params);
    byte[] outputText = new byte[cipher.getOutputSize(inputData.length)];
    int outputLen = cipher.processBytes(inputData, 0, inputData.length,
            outputText , 0);
    cipher.doFinal(outputText, outputLen);

//      outputText and mac are in bytes 
    System.out.println(outputText);
    System.out.println(cipher.getMac());
    }
}

1
那很好,但问题是关于使用JCE,而不是bouncycastle专有API。 - nsayer

0

不,JCE目前(截至JDK 10)不支持CCM模式。

有关支持的AES模式列表,请查看Oracle的官方文档此处。请参阅表4-13 “SunJCE提供程序密码转换”


也许这值得一个新问题,但上面问题的评论表明使用 BC 和普通的 JCE API 现在可能是可行的。如下所述,我知道 BC 的专有 API 可以做到这一点,但如果 JCE API 有一种方式即使需要另一种 Cipher 提供程序,那将是很好的。 - nsayer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接