2010-09-14 101 views
0

我需要在java代碼中使用openssl。例如在java中使用openssl創建密鑰

$ openssl genrsa -out private.pem 2048 

$ openssl pkcs8 -topk8 -in private.pem -outform DER -out private.der -nocrypt 

$ openssl rsa -in private.pem -pubout -outform DER -out public.der 

是否有任何庫或方法來實現這個?

+0

你只是想找一種方法來在java代碼中執行這3條語句嗎?您是否有理由在批處理或shell腳本中使用它們? – Sean 2010-09-14 18:12:34

+0

我必須在java代碼中調用這些命令,因爲我稍後將在代碼中使用這些文件。實際上主要的問題是,當第二個命令沒有完成第三個命令不執行時,第三個命令使用與第二個命令相同的文件。有些睡覺可以解決問題,但它有風險 – 2010-09-16 12:54:26

回答

0

最好的方法是使用Java庫進行此操作。我現在不能寫出確切的代碼,但它不是很難。看看java.security.KeyPairGenerator等等。這將是理解密碼學的好經驗。

但是,如果您只需要調用這三個命令行,Process.waitFor()調用就是答案。你可以使用這個類。

package ru.donz.util.javatools; 

import java.io.*; 

/** 
* Created by IntelliJ IDEA. 
* User: Donz 
* Date: 25.05.2010 
* Time: 21:57:52 
* Start process, read all its streams and write them to pointed streams. 
*/ 
public class ConsoleProcessExecutor 
{ 
    /** 
    * Start process, redirect its streams to pointed streams and return only after finishing of this process 
    * 
    * @param args  process arguments including executable file 
    * @param runtime just Runtime object for process 
    * @param workDir working dir 
    * @param out   stream for redirecting System.out of process 
    * @param err   stream for redirecting System.err of process 
    * @throws IOException 
    * @throws InterruptedException 
    */ 
    public static void execute(String[] args, Runtime runtime, File workDir, OutputStream out, OutputStream err) 
      throws IOException, InterruptedException 
    { 
     Process process = runtime.exec(args, null, workDir); 

     new Thread(new StreamReader(process.getInputStream(), out)).start(); 
     new Thread(new StreamReader(process.getErrorStream(), err)).start(); 

     int rc = process.waitFor(); 
     if(rc != 0) 
     { 
      StringBuilder argSB = new StringBuilder(); 
      for(String arg : args) 
      { 
       argSB.append(arg).append(' '); 
      } 
      throw new RuntimeException("Process execution failed. Return code: " + rc + "\ncommand: " + argSB); 
     } 
    } 

} 

class StreamReader implements Runnable 
{ 
    private final InputStream in; 
    private final OutputStream out; 


    public StreamReader(InputStream in, OutputStream out) 
    { 
     this.in = in; 
     this.out = out; 
    } 

    @Override 
    public void run() 
    { 
     int c; 
     try 
     { 
      while((c = in.read()) != -1) 
      { 
       out.write(c); 
      } 
      out.flush(); 
     } 
     catch(IOException e) 
     { 
      e.printStackTrace(); 
     } 
    } 
} 
相關問題