Java/Clojure BouncyCastle 报告错误的密钥大小,但密钥大小是正确的

Java/Clojure BouncyCastle reports wrong key size, but key size is right

我正在尝试使用 ISO9797 Alghrythm 3 生成 MAC。 我在 Clojure 中这样做,但我想我在这里遇到了更多 Java 问题。我运行这个代码:

(defn mac2 [key message]
  (let [engine (org.bouncycastle.crypto.engines.DESedeEngine.)
        mac (org.bouncycastle.crypto.macs.ISO9797Alg3Mac. engine)
        bytes (byte-array (.getMacSize mac))
        key (->bytes key)
        msg (->bytes E-IFD)]
    (prn key (count key))
    (.init mac (org.bouncycastle.crypto.params.DESedeParameters. key))
    (.update mac msg 0 (count msg))
    (.doFinal mac bytes 0)
    (->hex-string bytes)))

并得到这个输出(异常抛出在 (.init mac ...):

#<byte[] [B@65e47e28> 16
IllegalArgumentException key size must be 16 or 24 bytes.  org.bouncycastle.crypto.engines.DESedeEngine.init (:-1)

现在你看到了,prn ist 打印了密钥长度,它是 16。 但是 BouncyCastle 抱怨,它不是 16 或 24(将密钥更改为长度为 24 的密钥也无济于事)

另外当我运行这段代码时,没有问题:

(defn mac1 [key message]
  (let [engine (org.bouncycastle.crypto.engines.DESedeEngine.)
        mac (org.bouncycastle.crypto.macs.CMac. engine)
        bytes (byte-array (.getMacSize mac))
        msg (->bytes E-IFD)]
    (.init mac (org.bouncycastle.crypto.params.DESedeParameters. (->bytes key)))
    (.update mac msg 0 (count msg))
    (.doFinal mac bytes 0)
    (->hex-string bytes)))

好的,我post这里是工作代码。问题是我传递的是 org.bouncycastle.crypto.engines.DESedeEngine 而不是 org.bouncycastle.crypto.engines.DESEngine.

org.bouncycastle.crypto.macs.ISO9797Alg3Mac 将密钥分成 3 个部分,然后将第一个部分传递给它的引擎。因此 DESedeEngine 报告错误的密钥大小,尽管原始密钥的大小正确。

(defn mac2 [key message]
  (let [engine (org.bouncycastle.crypto.engines.DESEngine.)
        mac (org.bouncycastle.crypto.macs.ISO9797Alg3Mac. engine)
        bytes (byte-array (.getMacSize mac))
        key (->bytes key)
        msg (->bytes E-IFD)]
    (prn key (count key))
    (.init mac (org.bouncycastle.crypto.params.DESedeParameters. key))
    (.update mac msg 0 (count msg))
    (.doFinal mac bytes 0)
    (->hex-string bytes)))