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

499 views Asked by At

i'm trying to generate a MAC using the ISO9797 Alghrythm 3. I do this in Clojure, but I guess I'm having more of a Java Problem here. I run this code:

(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)))

And get this output (the exception is thrown at (.init mac ...):

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

Now you see, the prn ist printing put the key-length, which is 16. But BouncyCastle complains, that it is not 16 or 24 (changing the key to a key with the length of 24 does not help either)

Also when i run this code, there is no Problem:

(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

There are 1 answers

1
zabeltech On BEST ANSWER

Alright, I post the working code here. The problem was that I was passing org.bouncycastle.crypto.engines.DESedeEngine instead of org.bouncycastle.crypto.engines.DESEngine.

org.bouncycastle.crypto.macs.ISO9797Alg3Mac splits the key into 3 pieces and passes then the first one to its Engine. Hence DESedeEngine reports a wrong key size, although the original key had the right size.

(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)))