2012-11-17 22 views
1

我正在使用以下代碼來獲取密鑰鏈中的密碼。在osx中​​使用SecKeychainFindGenericPassword時獲取passwordData中的附加數據

-(OSStatus *)getPasswordFromKeyChain:(NSString *)username{ 
    OSStatus status; 

    const char *cService_name = "Mac App"; 
    UInt32 service_length = strlen(cService_name); 

    const char *cUser_name = [username cStringUsingEncoding:NSUTF8StringEncoding]; 
    UInt32 username_length = strlen(cUser_name); 

    void *passwordData = nil; 
    SecKeychainItemRef itemRef = nil; 
    UInt32 passwordLength = nil; 

    status = SecKeychainFindGenericPassword(
            NULL,   // default keychain 
            service_length, // length of service name 
            cService_name, // service name 
            username_length,// length of account name 
            cUser_name, // account name 
            &passwordLength, // length of password 
            passwordData,  // pointer to password data 
            NULL    // the item reference 
            ); 
    NSLog(@"%s",passwordData); 

    status = SecKeychainItemFreeContent (NULL,   //No attribute data to release 
            passwordData); //Release data buffer allocated by SecKeychainFindGenericPassword 

    return status; 
} 

這工作正常,因爲我獲得成功的狀態。

但是,當我嘗試打印我獲得的密碼時,得到以下結果 - 如果密碼超過6個字符,我會在實際密碼末尾看到一些垃圾字符。例如

2012-11-17 12:01:28.731 MAC App[2042:303] sssssss`—~ 

如果密碼少於或等於6個字符,我會得到正確的密碼。例如

2012-11-17 12:01:33.244 MAC App[2042:303] ssssss 

我的問題是爲什麼我在最後得到這些垃圾字符?我該如何解決這個問題?我需要這個密碼才能在我的應用程序中使用它。

回答

1

我從this link得到了我的答案。

獲取字符的原因在提供的鏈接中進行了解釋。我使用下面的代碼將密碼轉換爲NSString,併爲我工作。

NSString *tempStr = [[NSString alloc]initWithBytes:passwordData length:passwordLength encoding:NSUTF8StringEncoding]; 

NSLog(@"%@",tempStr); 
相關問題