2010-09-14 103 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(); 
     } 
    } 
} 
相关问题