2015-02-11 128 views
0

我對Android開發相當新,並試圖使用Jsch使用私鑰訪問遠程服務器。我已將私鑰放在res/raw文件夾中,但在嘗試進行身份驗證時,如何訪問私鑰的文件路徑正在掙扎。我以前得到這個Java項目的工作。這裏是我迄今爲止的副本。使用Android Jsch addidentity使用Android

private Session sshConnect() throws JSchException, IOException 
{ 
    try 
    { 
     //Login details 
     jschSession = jsch.getSession(sshUsername, sshServer, 22); 

     //Connect using private key and corresponding passphrase 
     jsch.addIdentity("./res/raw/id_rsa", passphrase); 

     //Ignore SSH key warnings 
     java.util.Properties config = new java.util.Properties(); 
     config.put("StrictHostKeyChecking", "no"); 
     jschSession.setConfig(config); 

     //System.out.println(localPort); 
     jschSession.connect(); 
     return jschSession; 
    } 
    catch (Exception ex) 
    { 
     throw new RuntimeException("SSH connection failed: " + ex.getMessage(), ex); 
    } 
} 

這則引發以下錯誤,當我嘗試運行

java.lang.RuntimeException: SSH connection failed: java.io.FileNotFoundException: ./res/raw/id_rsa: open failed: ENOENT (No such file or directory) 

我嘗試了以下嘗試訪問該資源文件夾的內容,有沒有這樣的運氣:

jsch.addIdentity("file:///android_res/raw/id_rsa", passphrase); 

回答

0

我不知道有一種方法可以將原始資源作爲文件訪問。

您可能需要將資源保存到臨時路徑,並參考addIdentity中的資源。

用於訪問資源,參見例如:
Android how to get access to raw resources that i put in res folder?

+0

謝謝你,有沒有我可以訪問其他文件,而在資源或資產的文件夾存儲任何其他方式? @馬丁 – user3424480 2015-02-12 22:00:11

1

簡單地說,你可以從原始文件夾中的文件。

InputStream privateKeyByteStream = getResources() 
      .openRawResource(
       getResources().getIdentifier("private_key_without_extension", "raw", getPackageName())); 

然後你的答案再加身份

jSch.addIdentity("anyIdentityName", privateKeyBytes, publicKeyBytes, passphrase);