2013-01-09 10 views
5

SecKeyEncryptにJSON形式の文字列を入力として使用しています。 SecKeyEncryptを渡すと246未満のplainTextLengthが機能します。 246以上の長さを渡すと、戻り値:paramErr (-50)で失敗します。なぜSecKeyEncryptは246バイトより長い入力文字列に対してparamErr(-50)を返しますか?

それは文字列自体の問題かもしれません。私はSecKeyEncryptを送るかもしれないものの例は次のとおりです。

 
{"handle":"music-list","sym_key":"MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALeaEO7ZrjgOFGLBzBHZtQuzH2GNDYMLWP+fIFNu5Y+59C6HECY+jt0yOXXom2mzp/WYYI/9G+Ig8OD6YiKv2nMCAwEAAQ==","app_id":"xgfdt.LibraryTestApp","api_key":"7e080f74de3625b90dd293fc8be560a5cdfafc08"} 

第二百四十五の文字が「0」です。

この作業の間に変更される入力はplainTextLengthです。 SecKeyGetBlockSize()は私に256を返しているので、最大256文字の入力が有効です。ドキュメントから

 
+ (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; 
} 

答えて

7

:平文バッファ内のデータのバイト

plainTextLen

は、ここに私の暗号化方式です。これは、SecKeyGetBlockSize関数によって返される値以下でなければなりません。 PKCS1パディングを実行すると、暗号化できるデータの最大長は、SecKeyGetBlockSize関数(secKeyGetBlockSize() - 11)によって返された値よりも11バイト少なくなります。

(強調鉱山)

あなたはPKCS1パディングを使用しています。したがって、ブロックサイズが256の場合は、一度に最大245バイトしか暗号化できません。

+0

はい。ダー。ありがとう! – Mathew