我想创建一个简单的java应用程序(mac),需要在一个网站和输出我的密码与Keychain中的网站相关联。
我的问题是我的应用程序无法从输出中读取密码。如果我手动写入:
security find-internet-password -gs www.google.com
进入终端,我得到几行信息,然后-> password: "mypassword"。但是在我的应用程序中,我只看到了信息行,但最后一行应该是密码,不存在或为空。
我代码:public static void command(){
try{
String command = "security find-internet-password -gs www.google.com";
Process child = Runtime.getRuntime().exec(command);
BufferedReader r = new BufferedReader(new InputStreamReader(child.getInputStream()));
String s;
while ((s = r.readLine()) != null) {
System.out.println(s);
}
System.out.println(r.readLine());
r.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
我没有得到任何错误,但只是上面的代码没有显示密码。如果需要的话,我正在使用Eclipse。由于
应用程序打印:
keychain: "/Users/*username*/Library/Keychains/login.keychain"
class: "inet"
attributes:
0x00000007 <blob>="www.google.com"
0x00000008 <blob>=<NULL>
"acct"<blob>="*username*"
"atyp"<blob>="http"
"cdat"<timedate>=0x323031*numbers*3333325A00 "2011*numbers*132Z 00"
"crtr"<uint32>="rimZ"
"cusi"<sint32>=<NULL>
"desc"<blob>=<NULL>
"icmt"<blob>=<NULL>
"invi"<sint32>=<NULL>
"mdat"<timedate>=0x3230331*numbers*33834375A00 "20115*numbers*3847Z 00"
"nega"<sint32>=<NULL>
"path"<blob>="/"
"port"<uint32>=0x00000000
"prot"<blob>=<NULL>
"ptcl"<uint32>="htps"
"scrp"<sint32>=<NULL>
"sdmn"<blob>="www.google.com"
"srvr"<blob>="www.google.com"
"type"<uint32>=<NULL>
但是最后一行不见了,应该是
password: "mypassword"
是InputStreamReader不读取密码吗?有别的方法可以得到密码吗?
没有在输出中获得密码的原因是它没有打印到标准输出中,而是打印到标准输出中。
如果你在代码中用child.getErrorStream()
代替child.getInputStream()
,你会得到正确的Password:secret!
行。
你可以使用如下修改后的代码:
public static boolean command(String host) {
try {
String command = "security find-internet-password -gs " + host;
Process child = Runtime.getRuntime().exec(command);
try (BufferedReader out = new BufferedReader(new InputStreamReader(
child.getInputStream()));
BufferedReader err = new BufferedReader(
new InputStreamReader(child.getErrorStream()))) {
String user = null;
String password = null;
String s;
while ((s = out.readLine()) != null) {
if (s.matches(" *"acct".*")) {
user = s.replaceAll("^.*="", "").replace(""", "");
}
}
s = err.readLine();
password = s.replaceAll("^.*: *"", "").replace(""", "");
System.out.println("user: " + user);
System.out.println("pwd: " + password);
return true;
}
} catch (IOException e) {
return false;
}
}