password – macOS: How to add a keychain item, to other than the default keychain (securely)?

Consider we wanted to create a keychain, then add a generic-password:

❯ security create-keychain -P test.keychain

So I create a keychain test.keychain, located here: "/Users/akharrou/Library/Keychains/test.keychain-db".

Next, I want to add an item to this keychain:

❯ man 1 security
...
add-generic-password (-h) (-a account) (-s service) (-w password) (options...)
     (keychain)
❯ security add-generic-password -a $USER -s app.stackexchange 
    "/Users/akharrou/Library/Keychains/test.keychain-db"

This creates a generic password, with no password field filled in. But of course I want the password field filled in, and I want to give the password via prompt, either from terminal or, even better, the “Security Agent” popup box; OR on the command line securely, via e.g. standard input, or something like: -w $(cat <(cat path/to/passwd.txt)) (the file being protected with permissions).

The problem is NONE of the above seems to be possible, I tried…

❯ security add-generic-password -a $USER -s app.textexpander  
    "/Users/akharrou/Library/Keychains/test.keychain-db" -w

This is wrong syntax, of course won’t work.

❯ security add-generic-password -a $USER -s app.textexpander -w 
    "/Users/akharrou/Library/Keychains/test.keychain-db"

This takes the keychain (path) as password, not what we want.

❯ security add-generic-password -a $USER -s app.textexpander -w "" 
    "/Users/akharrou/Library/Keychains/test.keychain-db"

This still produces an empty password field, doesn’t solve our problem.

❯ security add-generic-password -a $USER -s app.textexpander 
    -w $(cat <(cat path/to/passwd)) 
    "/Users/akharrou/Library/Keychains/test.keychain-db"

This doesn’t work and complains as though there was a syntax error.

❯ security add-generic-password -a $USER -s app.textexpander 
    -w "mywonderfulpassword" 
    "/Users/akharrou/Library/Keychains/test.keychain-db"

This is not secure, the password is leaked in the process table.


Anybody know how this is done ?