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

时间:2015-06-13 16:00:53

标签: java clojure bouncycastle des

我试图使用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)))

1 个答案:

答案 0 :(得分:2)

好的,我在这里发布了工作代码。问题是我传递了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)))