Save data into keychain using Shell Script

58 Views Asked by At

I am trying to save some static data into keychain using ShellScript. But when I try fetch that data via native swift code it does not provided the data. My code is as follow:

ShellScript:

service_name="MyKeychainService"

# Specify the account name for the keychain item
account_name="MyAccount"

# Specify the string data you want to save
string_data="YourSecretString"

# Save the string data into the keychain
security add-generic-password -a "$account_name" -s "$service_name" -w "$string_data" -U

iOS native Swift Code:

func retrieveDataFromKeychain(service: String, account: String) -> String? {
    var query = [
        kSecClass: kSecClassGenericPassword,
        kSecAttrService: service,
        kSecAttrAccount: account,
        kSecReturnData: kCFBooleanTrue as Any,
        kSecMatchLimit: kSecMatchLimitOne
    ] as [String: Any]

    var data: AnyObject?
    let status = SecItemCopyMatching(query as CFDictionary, &data)

    if status == errSecSuccess {
        if let retrievedData = data as? Data {
            return String(data: retrievedData, encoding: .utf8)
        }
    }

    return nil
}

Usage:

let service = "MyKeychainService"
let account = "MyAccount"

if let retrievedData = retrieveDataFromKeychain(service: service, account: account) {
    print("Retrieved data from keychain: \(retrievedData)")
} else {
    print("Failed to retrieve data from keychain")
}
0

There are 0 best solutions below