为何Ironclad库的decrypt-in-place针对ARC4流加密未按预期工作
问题根因
- 密码实例状态未重置
Ironclad中的流密码实例是有状态的,调用encrypt-in-place完成加密后,实例内部的密钥流生成器已经偏移到和明文长度匹配的位置。此时直接复用该实例调用decrypt-in-place,不会从头生成初始密钥流,而是使用偏移后的后续密钥流做异或运算,自然无法还原出原始明文。 - ARC4算法本身不需要初始化向量,你调用
make-cipher时传入的initialization-vector参数属于无效参数,虽不是本次问题的核心诱因,但属于冗余错误写法。 - crypto-shortcuts库的
encrypt/decrypt接口每次调用时都会重新创建全新的密码实例,天然使用初始状态的密钥流处理数据,因此运行逻辑符合预期。
修正方案
解密前不要复用加密使用过的密码实例,可选两种处理方式:
- 重新创建一个密钥、算法参数完全相同的新密码实例用于解密
- 调用
reinitialize-instance方法重置原有密码实例的状态到初始值
修正后可正常运行的代码
(ql:quickload :ironclad) (ql:quickload :crypto-shortcuts) (use-package :ironclad) (defparameter str "Hello World!") (defparameter message (ascii-string-to-byte-array str)) (defparameter key "1234") (let* ((key-bytes (ascii-string-to-byte-array key)) (cipher (make-cipher :arcfour :key key-bytes :mode :stream)) (text (ascii-string-to-byte-array (cryptos:to-base64 (copy-seq message))))) (format t "初始text: ~a~%" text) (encrypt-in-place cipher text) (format t "加密后text: ~a~%" text) ;; 重置密码实例状态为初始值 (reinitialize-instance cipher :key key-bytes :mode :stream) (decrypt-in-place cipher text) (format t "解密后text: ~a~%" text))
运行上述代码后,解密后的text输出将和初始值完全一致。
内容的提问来源于stack exchange,提问作者monkbeta
相关产品推荐
相关产品推荐

