Formatting RSA keys for OpenSSL in Java

前端 未结 1 973
陌清茗
陌清茗 2020-12-08 05:54

Background

RSA key generation with OpenSSL on Linux using the command,

openssl genrsa -out mykey.pem 1024

created the following:

1条回答
  •  时光取名叫无心
    2020-12-08 06:38

    The OpenSSL private key is in a non-standard format, while the Java code is creating a standard, PKCS-#8–encoded private key.

    OpenSSL can convert the standard key format to the non-standard form. You can write Java code to do the same, but it requires some third-party libraries and a good knowledge of ASN.1 helps too.

    To convert a PKCS #8 key to OpenSSL format, use OpenSSL's pkcs8 utility.

    openssl pkcs8 -nocrypt -inform der < pvt.der > pvt.pem
    

    To convert an RSA key stored as a DER-encoded SubjectPublicKeyInfo to PEM format, use OpenSSL's rsa utility.

    openssl rsa -pubin -inform der < pub.der > pub.pem
    

    This assumes that the private key is stored in "binary" (DER) format, not Base-64 encoded. The Java code to create and store keys like this would look something like:

    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    KeyPair pair = gen.generateKeyPair();
    FileOutputStream ospvt = new FileOutputStream("pvt.der");
    try {
      ospvt.write(pair.getPrivate().getEncoded());
      ospvt.flush();
    } finally {
      ospvt.close();
    }
    FileOutputStream ospub = new FileOutputStream("pub.der");
    try {
      ospub.write(pair.getPublic().getEncoded());
      ospub.flush();
    } finally {
      ospub.close();
    }
    

    0 讨论(0)
提交回复
热议问题