1

我正在使用以下代码从钥匙串中获取密码。

-(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

我的问题是为什么我最后会得到这些垃圾字符?我该如何解决这个问题?我需要这个密码才能在我的应用程序中使用它。

4

1 回答 1

1

我从这个链接得到了答案。

获取字符的原因在提供的链接中进行了说明。我使用以下代码将密码转换为 NSString,这对我有用。

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

NSLog(@"%@",tempStr);
于 2012-11-17T12:28:59.353 回答