使用SecKeyWrapper加密16字节的UTF8(ccStatus == -4304) [英] Encrypting 16 bytes of UTF8 with SecKeyWrapper breaks (ccStatus == -4304)

查看:167
本文介绍了使用SecKeyWrapper加密16字节的UTF8(ccStatus == -4304)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Apple的 SecKeyWrapper 类来自 CryptoExercise Apple文档中的示例代码,用AES128进行一些对称加密。出于某种原因,当我加密1-15个字符或17个字符时,它会正确加密和解​​密。有16个字符,我可以加密,但在解密后,它会在 CCCryptorFinal 调用 ccStatus == -4304 ,表示解码错误。 (去图。)

I'm using Apple's SecKeyWrapper class from the CryptoExercise sample code in the Apple docs to do some symmetric encryption with AES128. For some reason, when I encrypt 1-15 characters or 17 characters, it encrypts and decrypts correctly. With 16 characters, I can encrypt, but on decrypt it throws an exception after the CCCryptorFinal call with ccStatus == -4304, which indicates a decode error. (Go figure.)

我知道AES128每个加密块使用16个字节,所以我得到的印象是错误与明文长度有关块边界。有没有人使用 CommonCryptor SecKeyWrapper

I understand that AES128 uses 16 bytes per encrypted block, so I get the impression that the error has something to do with the plaintext length falling on the block boundary. Has anyone run into this issue using CommonCryptor or SecKeyWrapper?

推荐答案

以下几行......

The following lines...

// We don't want to toss padding on if we don't need to
if (*pkcs7 != kCCOptionECBMode) {
  if ((plainTextBufferSize % kChosenCipherBlockSize) == 0) {
*pkcs7 = 0x0000;
  } else {
    *pkcs7 = kCCOptionPKCS7Padding;
  }
}

...是我的问题的罪魁祸首。为了解决这个问题,我只需要对它们进行评论。

... are the culprits of my issue. To solve it, I simply had to comment them out.

据我所知,加密过程不是在加密方面进行填充,但当时仍在期待在解密端填充,导致解密过程失败(这通常是我遇到的情况)。

As far as I can tell, the encryption process was not padding on the encryption side, but was then still expecting padding on the decryption side, causing the decryption process to fail (which is generally what I was experiencing).

始终使用 kCCOptionPKCS7Padding 对于满足长度%16 == 0 的字符串以及那些不满足的字符串。而且,这是对 CryptoExercise 示例代码的 SecKeyWrapper 类的修改。不确定这会如何影响您使用 CommonCrypto 与自制卷包装器。

Always using kCCOptionPKCS7Padding to encrypt/decrypt is working for me so far, for strings that satisfy length % 16 == 0 and those that don't. And, again, this is a modification to the SecKeyWrapper class of the CryptoExercise example code. Not sure how this impacts those of you using CommonCrypto with home-rolled wrappers.

这篇关于使用SecKeyWrapper加密16字节的UTF8(ccStatus == -4304)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆