我使用SecKeyEncryptJSON 格式的字符串作为输入。如果传递SecKeyEncrypt小于 246 的 plainTextLength,它可以工作。如果我传递它的长度为 246 或更多,它会失败并返回 value: paramErr (-50)。
这可能是字符串本身的问题。我可能发送的一个示例SecKeyEncrypt是:
{ “手柄”: “音乐列表”, “sym_key”: “MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALeaEO7ZrjgOFGLBzBHZtQuzH2GNDYMLWP + fIFNu5Y + 59C6HECY + jt0yOXXom2mzp / WYYI / 9G + Ig8OD6YiKv2nMCAwEAAQ ==”, “APP_ID”: “xgfdt.LibraryTestApp”, “API_KEY”: “7e080f74de3625b90dd293fc8be560a5cdfafc08” }
第 245 个字符是“0”。
在此工作之间发生变化的唯一输入是plainTextLength。SecKeyGetBlockSize()正在向我返回 256,因此任何长达 256 个字符的输入都应该有效。
这是我的加密方法:
+ (NSData*)encrypt:(NSString*)data usingPublicKeyWithTag:(NSString*)tag
{
OSStatus 状态 = noErr;
size_t cipherBufferSize;
uint8_t *cipherBuffer;
// [密码缓冲区大小]
size_t dataSize = 246;//[数据长度OfBytesUsingEncoding:NSUTF8StringEncoding];
const uint8_t* textData = [[data dataUsingEncoding:NSUTF8StringEncoding] bytes];
SecKeyRef publicKey = [加密 copyPublicKeyForTag:tag];
NSAssert(publicKey, @"在尝试使用它加密数据之前,标签引用的公钥必须已经存储在钥匙串中!");
// 分配一个缓冲区
cipherBufferSize = SecKeyGetBlockSize(publicKey);
// 这个值不会被修改,而 cipherBufferSize 可以。
const size_t fullCipherBufferSize = cipherBufferSize;
cipherBuffer = malloc(cipherBufferSize);
NSMutableData* 累积加密数据 = [NSMutableData dataWithCapacity:0];
// 错误处理
for (int ii = 0; ii*fullCipherBufferSize < dataSize; ii++) {
const uint8_t* dataToEncrypt = (textData+(ii*fullCipherBufferSize));
const size_t subsize = (((ii+1)*fullCipherBufferSize) > dataSize) ?fullCipherBufferSize-(((ii+1)*fullCipherBufferSize) - dataSize) : fullCipherBufferSize;
// 使用公钥加密。
状态 = SecKeyEncrypt(公钥,
kSecPaddingPKCS1,
数据加密,
小尺寸,
密码缓冲区,
&cipherBufferSize
);
[accumulatedEncryptedData appendBytes:cipherBuffer 长度:cipherBufferSize];
}
if (publicKey) CFRelease(publicKey);
免费(密码缓冲区);
返回累积加密数据;
}