wechat-miniprogram / sm-crypto

miniprogram sm crypto library
MIT License
440 stars 88 forks source link

这里的`padding===pkcs#5`应该是弄错了,实质应该是`pkcs#7` #23

Closed TheNorthMemory closed 2 years ago

TheNorthMemory commented 2 years ago

https://github.com/wechat-miniprogram/sm-crypto/blob/29fb341b341bbf7a309a575c9351d2b2b3fd89aa/src/sm4/index.js#L272-L276

https://github.com/wechat-miniprogram/sm-crypto/blob/29fb341b341bbf7a309a575c9351d2b2b3fd89aa/src/sm4/index.js#L327-L331

援引两个RFC文档,pkcs#5 填充尾数只会是1到8,而SM4k大小是16,按照程序逻辑是有可能填充上116,这里应该是用错了。

RFC2898 PKCS#5 section 6.1.2

  1. Separate the encoded message EM into a message M and a padding string PS: EM = M || PS , where the padding string PS consists of some number psLen octets each with value psLen, where psLen is between 1 and 8. If it is not possible to separate the encoded message EM in this manner, output "decryption error" and stop.

RFC2415 PKCS#7 section-10.3

  1. Some content-encryption algorithms assume the input length is a multiple of k octets, where k > 1, and let the application define a method for handling inputs whose lengths are not a multiple of k octets. For such algorithms, the method shall be to pad the input at the trailing end with k - (l mod k) octets all having value k - (l mod k), where l is the length of the input. In other words, the input is padded at the trailing end with one of the following strings:

          01 -- if l mod k = k-1
         02 02 -- if l mod k = k-2
                     .
                     .
                     .
       k k ... k k -- if l mod k = 0

    The padding can be removed unambiguously since all input is padded and no padding string is a suffix of another. This padding method is well-defined if and only if k < 256; methods for larger k are an open issue for further study.

JuneAndGreen commented 2 years ago

是的,sm4 16字节1个分组,默认值和参数值写成了 pkcs#5,这里我修改一下,实际上传 pkcs#5 或 pkcs#7 应该都是要用 pkcs#7 填充。

JuneAndGreen commented 2 years ago

miniprogram-sm-crypto@0.3.7 已修改