2014-10-02 30 views
2

我使用RNCryptor成功地在iOS中加密/解密數據。RNCryptor:獲取公鑰爲NSString

我想獲得公鑰發送到服務器,所以它可以加密一些數據。

NSString *saltString = @"salt'n'peppa"; 
NSData *salt = [saltString dataUsingEncoding:NSUTF8StringEncoding]; 
NSData *key = [RNCryptor keyForPassword:password 
            salt:salt 
           settings:kRNCryptorAES256Settings.keySettings]; 

此時,key中有一些數據。不過,我似乎無法工作,如何將公鑰作爲一個字符串:

NSString *publicKey = [[NSString alloc] initWithData:key encoding:NSUTF8StringEncoding]; 

我試過不同的編碼,但似乎沒有任何工作。

這裏是RNCryptor的keyForPassword方法:

+ (NSData *)keyForPassword:(NSString *)password salt:(NSData *)salt settings:(RNCryptorKeyDerivationSettings)keySettings 
{ 
    NSMutableData *derivedKey = [NSMutableData dataWithLength:keySettings.keySize]; 

    // See Issue #77. V2 incorrectly calculated key for multi-byte characters. 
    NSData *passwordData; 
    if (keySettings.hasV2Password) { 
    passwordData = [NSData dataWithBytes:[password UTF8String] length:[password length]]; 
    } 
    else { 
    passwordData = [password dataUsingEncoding:NSUTF8StringEncoding]; 
    } 

    // Use the built-in PBKDF2 if it's available. Otherwise, we have our own. Hello crazy function pointer. 
    int result; 
    int (*PBKDF)(CCPBKDFAlgorithm algorithm, const char *password, size_t passwordLen, 
       const uint8_t *salt, size_t saltLen, 
       CCPseudoRandomAlgorithm prf, uint rounds, 
       uint8_t *derivedKey, size_t derivedKeyLen); 

    PBKDF = CCKeyDerivationPBKDF ?: RN_CCKeyDerivationPBKDF; 

    result = PBKDF(keySettings.PBKDFAlgorithm,   // algorithm 
       passwordData.bytes,     // password 
       passwordData.length,    // passwordLength 
       salt.bytes,       // salt 
       salt.length,      // saltLen 
       keySettings.PRF,     // PRF 
       keySettings.rounds,     // rounds 
       derivedKey.mutableBytes,   // derivedKey 
       derivedKey.length);     // derivedKeyLen 

    // Do not log password here 
    NSAssert(result == kCCSuccess, @"Unable to create AES key for password: %d", result); 

    return derivedKey; 
} 

我得到我做得majorly錯誤的,因爲谷歌搜索的感覺出現很少。

回答

4

密鑰不是字符串,而是數據。只是一系列隨機(字節)的字節。將其轉換爲字符串發送到服務器的唯一方法是編碼字節。一種常用的方法是使用base 64編碼。然後,服務器可以將基礎64編碼的字符串轉換回密鑰的原始字節。

+0

如果服務器運行PHP,您可以通過提供'NSData'對象作爲POST數據發送原始字節,然後使用'file_get_contents('php:// input')'在PHP中讀取它。這種方式不需要base64編碼。 PHP的字符串數據類型比'NSString'更接近'NSData'(儘管這可能會在PHP的未來版本中發生變化......) – 2014-10-02 05:30:17

+0

@maddy非常感謝。這很有道理。 – 2014-10-02 10:45:13

+0

@AbhiBeckert我沒有使用PHP,但多數民衆贊成知道。我會記住它 – 2014-10-02 10:46:01