Faster keychain access

When attempting to locate a particular key on a large keychain, using a loop that asks keychain scripting for the name of each key one by one is VERY slow. This construct instead asks for the names of all keys at once then repeats through that array to locate the appropriate one.

OS version: OS X

tell application "Keychain Scripting"
	set theKeyList to name of every Internet key of current keychain
	repeat with x from 1 to (length of theKeyList)
		if item x of theKeyList is "[url=http://www.example.com]www.example.com[/url]" then
			set thePassword to password of Internet key x of current keychain
			set theUserID to the account of Internet key x of current keychain
			exit repeat
		end if
	end repeat
end tell

If you need your password in a script, i.e. like this:

set powersettings to do shell script "pmset -g" password PWD with administrator privileges

and you don’t want to put your password in clear text in the script, then you can add your password in the Keychain Access application and use it from your script. In Keychain access, click File>New Password Item…, give it a name, put your account shortname in account, and enter the password. I called mine AS_Allow. Highlight it in the password list and under the Attributes button enter its kind as generic key. This is chosen because there aren’t many of them and the search is much faster. The script used is as follows:

tell application "Keychain Scripting"
	launch
	tell current keychain
		tell (some generic key whose name is "AS_Allow")
			set PWD to password
		end tell
	end tell
end tell

and this goes ahead of the call for a password in the script.