sharplispers / ironclad

A cryptographic toolkit written in Common Lisp
BSD 3-Clause "New" or "Revised" License
166 stars 28 forks source link

Chacha with a 96-bit nonce? #54

Closed ykonai closed 1 year ago

ykonai commented 1 year ago

Currently, only chacha with a 64-bit nonce is available through the API. Would there be interest in adding the 96-bit nonce variant which is popular in some RFCs? I believe it could be achieved either by just modifying the shared-initialize method of chacha (this would be a minor breaking change) or by defining a new cipher like chacha/rfc. Example:

src/ciphers/chacha.lisp
(defmethod shared-initialize :after ((cipher chacha/rfc) slot-names
                                     &rest initargs
                                     &key (key nil key-p)
                                       (initialization-vector nil iv-p)
                                     &allow-other-keys)
  (declare (ignore initargs key key-p iv-p))
  (setf (chacha-keystream-buffer-remaining cipher) 0)
  (when initialization-vector
    (when (< (length initialization-vector) 8)
      (error 'invalid-initialization-vector
             :cipher (class-name (class-of cipher))
             :block-length 8))
    (let ((state (chacha-state cipher)))
      (declare (type chacha-state state))
      (case (length initialization-vector)
        (12 (setf (aref state 12) 0 ;; inelegant but mostly backwards compatible
                  (aref state 13) (ub32ref/le initialization-vector 0)
                  (aref state 14) (ub32ref/le initialization-vector 4)
                  (aref state 15) (ub32ref/le initialization-vector 8)))
        (t (setf (aref state 12) 0
                 (aref state 13) 0
                 (aref state 14) (ub32ref/le initialization-vector 0)
                 (aref state 15) (ub32ref/le initialization-vector 4))))))
  cipher)
glv2 commented 1 year ago

I added support for the 96-bit nonce variant in commit 9da18690adf479b1a5ca0237f4a3d31ffd2ac44b. Could you check if it works for you?

ykonai commented 1 year ago

That looks perfect. Thank you!