Tôi đang sử dụng SecKeyEncrypt
với chuỗi được định dạng JSON làm đầu vào. Nếu vượt qua SecKeyEncrypt
plainTextLength dưới 246, nó hoạt động. Nếu tôi vượt qua nó dài 246 hoặc hơn, nó không thành công với giá trị trả về: paramErr (-50)
.Tại sao SecKeyEncrypt trả về paramErr (-50) cho chuỗi đầu vào dài hơn 246 byte?
Nó có thể là vấn đề của chính chuỗi đó. Ví dụ về những gì tôi có thể gửi SecKeyEncrypt
là:
{"handle":"music-list","sym_key":"MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALeaEO7ZrjgOFGLBzBHZtQuzH2GNDYMLWP+fIFNu5Y+59C6HECY+jt0yOXXom2mzp/WYYI/9G+Ig8OD6YiKv2nMCAwEAAQ==","app_id":"xgfdt.LibraryTestApp","api_key":"7e080f74de3625b90dd293fc8be560a5cdfafc08"}
Ký tự 245 là '0'.
Đầu vào CHỈ thay đổi giữa thao tác này và là plainTextLength. SecKeyGetBlockSize()
đang trả lại 256 cho tôi, vì vậy mọi đầu vào tối đa 256 ký tự sẽ hoạt động.
Đây là phương pháp mã hóa của tôi:
+ (NSData*)encrypt:(NSString*)data usingPublicKeyWithTag:(NSString*)tag { OSStatus status = noErr; size_t cipherBufferSize; uint8_t *cipherBuffer; // [cipherBufferSize] size_t dataSize = 246;//[data lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; const uint8_t* textData = [[data dataUsingEncoding:NSUTF8StringEncoding] bytes]; SecKeyRef publicKey = [Encryption copyPublicKeyForTag:tag]; NSAssert(publicKey, @"The public key being referenced by tag must have been stored in the keychain before attempting to encrypt data using it!"); // Allocate a buffer cipherBufferSize = SecKeyGetBlockSize(publicKey); // this value will not get modified, whereas cipherBufferSize may. const size_t fullCipherBufferSize = cipherBufferSize; cipherBuffer = malloc(cipherBufferSize); NSMutableData* accumulatedEncryptedData = [NSMutableData dataWithCapacity:0]; // Error handling 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; // Encrypt using the public key. status = SecKeyEncrypt( publicKey, kSecPaddingPKCS1, dataToEncrypt, subsize, cipherBuffer, &cipherBufferSize ); [accumulatedEncryptedData appendBytes:cipherBuffer length:cipherBufferSize]; } if (publicKey) CFRelease(publicKey); free(cipherBuffer); return accumulatedEncryptedData; }
Đúng. Duh. Cảm ơn! – Mathew