我正在尝试使用 Racket Crypto library 到 encrypt 16 字节的块和 16 字节的 key 。我期望有一个 16 字节的输出块,但我得到了一个 32 字节的输出块。
15 字节输入块提供 16 位输出。
#lang racket
(require (planet vyzo/crypto))
(bytes-length (encrypt cipher:aes-128-ecb
(string->bytes/latin-1 "0123456789ABCDEF") ; 16-byte key
(make-bytes 16) ; IV
(string->bytes/latin-1 "0123456789ABCDEF"))) ; 16-byte data
; -> 32
(bytes-length (encrypt cipher:aes-128-ecb
(string->bytes/latin-1 "0123456789ABCDEF") ; 16-byte key
(make-bytes 16)
(string->bytes/latin-1 "0123456789ABCDE"))) ; 15-byte data
; -> 16
我有什么地方错了吗?这是由于填充吗?
注意:我知道 ECB 模式的问题,我的目标是实现 CBC 模式。
最佳答案
你是对的,这是因为填充。不幸的是,vyzo/crypto lib 的 API 不允许您轻松禁用填充(这是正确的,请参阅下面的警告)。
如何禁用填充
但是,基于此 Thread on the Racket users mailing list ,您可以像这样禁用填充:
#lang racket
(require (planet vyzo/crypto) (planet vyzo/crypto/util))
(define (cipher-encrypt-unpadded type key iv)
(lambda (ptext)
(let ((octx (cipher-encrypt type key iv #:padding #f)))
(bytes-append (cipher-update! octx ptext)
(cipher-final! octx)))))
(define (cipher-decrypt-unpadded type key iv)
(lambda (ctext)
(let ((ictx (cipher-decrypt type key iv #:padding #f)))
(bytes-append (cipher-update! ictx ctext)
(cipher-final! ictx)))))
; bytes-> bytes
; convenience function for encryption
(define enc-aes-128-ecb-unpadded
(cipher-encrypt-unpadded cipher:aes-128-ecb
(string->bytes/latin-1 "0123456789ABCDEF"); 16-byte key
(make-bytes 16)))
; bytes -> bytes
; convenience function for decryption
(define dec-aes-128-ecb-unpadded
(cipher-decrypt-unpadded cipher:aes-128-ecb
(string->bytes/latin-1 "0123456789ABCDEF"); 16-byte key
(make-bytes 16)))
(define message (string->bytes/latin-1 "0123456789ABCDEF")) ; 16-byte data
(bytes-length (enc-aes-128-ecb-unpadded message))
; -> 16
(dec-aes-128-ecb-unpadded (enc-aes-128-ecb-unpadded message))
; -> #"0123456789ABCDEF"
这在我的机器上运行良好。此外,切换到 CBC 模式很简单。
警告
当您禁用填充时,您的消息的长度必须是块大小的倍数。对于 AES128,它是 16 字节的精确倍数。否则这个函数会在你面前爆炸:
(enc-aes-128-ecb-unpadded (string->bytes/latin-1 "too short!"))
EVP_CipherFinal_ex: libcrypto error: data not multiple of block length [digital envelope routines:EVP_EncryptFinal_ex:101183626]
关于encryption - AES 输出 block 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16872578/