【问题标题】:Creating keys by using openssl in java在java中使用openssl创建密钥
【发布时间】:2010-09-14 16:47:09
【问题描述】:

我需要在 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

是否有任何库或方法可以实现这一点?

【问题讨论】:

  • 您是否只是在寻找一种在 Java 代码中执行这 3 条语句的方法?您是否有理由希望它们在代码中而不是批处理或 shell 脚本中?
  • 我必须在java代码中调用这些命令,因为我稍后会在代码中使用这些文件。实际上主要的问题是,第三条命令与第二条命令使用相同的文件,因此当第二条命令没有完成时,第三条命令不执行。一些睡眠可以解决问题,但有风险

标签: java openssl


【解决方案1】:

最好的方法是使用 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();
        }
    }
}

【讨论】:

    猜你喜欢
    • 2022-12-04
    • 2013-03-04
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    • 2013-06-14
    • 2013-04-08
    • 2020-07-23
    • 1970-01-01
    相关资源
    最近更新 更多