2017-02-11 5 views
0

키 체인에서 내 앱의 비밀 키를 검색하여 서버 인증에 사용할 수 있도록하려고합니다. 성공적으로 거기에 저장했지만 그것을 다시 얻을 수 없습니다.osx 키 체인에서 키 가져 오기

func getClientKey(){ 
    let keyValptr:UnsafeMutablePointer<UnsafeMutableRawPointer?>? 
    let lenPtr:UnsafeMutablePointer<UInt32>? = UInt32(13) //how do i do this? 
    _ = SecKeychainFindGenericPassword(nil, 
     UInt32(serviceName.characters.count), serviceName, 
     UInt32(accountName.characters.count), accountName, 
     lenPtr, keyValptr, nil) 

    print(keyValptr) 
} 

나는 문제가있는 줄을 주석 처리했습니다. 함수에 전달할 정확한 포인터를 얻는 방법은 무엇입니까? 그것은 당신이 UnsafeMutablePoiner<T>? (또는 UnsafeMutablePoiner<T>)을 통과 할 때, 일반적으로

+0

'VAR는 len :

은 다음처럼 작성할 필요가 있습니다. – vacawama

답변

1

(나는 값이 실제로 무엇을 선택할 것)을 UnsafeMutablePointer<UInt32>?, 당신은 유형 T (안 T에 대한 포인터)의 변수를 선언하고로 전달하고자 inout 매개 변수 (접두어 &)

문제에 따라 keyValPtr을 전달하는 방법도 잘못되었습니다.

passwordLength: UnsafeMutablePointer<UInt32>? 매개 변수의 경우 UInt32 변수를 선언해야합니다. passwordData: UnsafeMutablePointer<UnsafeMutableRawPointer?>?의 경우 UnsafeMutableRawPointer? 유형의 변수를 선언해야합니다.

그리고 불행하게도 이것은 중요한 문제가 아닐 수 있습니다. 스위프트 StringUnsafePointer<Int8>?에 직접 전달할 때 UTF-8 표현을 기반으로 길이를 계산해야합니다. 함수에`& len`을 통과 한 후 UINT32 = 13`과 :

func getClientKey() { 
    var keyVal: UnsafeMutableRawPointer? = nil 
    var len: UInt32 = 13 //<- this value is ignored though... 
    let status = SecKeychainFindGenericPassword(
     nil, 
     UInt32(serviceName.utf8.count), serviceName, //### Use `utf8.count` 
     UInt32(accountName.utf8.count), accountName, //### Use `utf8.count` 
     &len,  //### to pass `UnsafeMutablePointer<UInt32>?`, declare a variable of `UInt32`. 
     &keyVal, //### to pass `UnsafeMutablePointer<UnsafeMutableRawPointer?>?`, declare a variable of `UnsafeMutableRawPointer?`. 
     nil 
    ) 

    if status == noErr { 
     let keyData = Data(bytes: keyVal!, count: Int(len)) 
     //### As noted in the API reference of `SecKeychainFindGenericPassword`, 
     // "You should use the SecKeychainItemFreeContent function to free the memory pointed to by this parameter." 
     SecKeychainItemFreeContent(nil, keyVal) 

     print(keyData as NSData) 
     print(String(data: keyData, encoding: .utf8) ?? "?") 
    } else { 
     //You should not silently ignore erros... 
     print("Error: \(status)") 
    } 
}