根据链接:http://codeartisan.blogspot.in/2009/05/public-key-cryptography-in-java.html您应该尝试以下操作
生成2048位RSA私钥
$ openssl genrsa -out private_key.pem 2048
将私钥转换为 PKCS#8 格式(以便 Java 可以读取)
$ openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out private_key.der -nocrypt
以 DER 格式输出公钥部分(以便 Java 可以读取)
$ openssl rsa -in private_key.pem -pubout -outform DER -out public_key.der
你可以阅读下面的java代码:
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class Demo {
public static final String PRIVATE_KEY="/home/user/private.der";
public static final String PUBLIC_KEY="/home/user/public.der";
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
//get the private key
File file = new File(PRIVATE_KEY);
FileInputStream fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) file.length()];
dis.readFully(keyBytes);
dis.close();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(spec);
System.out.println("Exponent :" + privKey.getPrivateExponent());
System.out.println("Modulus" + privKey.getModulus());
//get the public key
File file1 = new File(PUBLIC_KEY);
FileInputStream fis1 = new FileInputStream(file1);
DataInputStream dis1 = new DataInputStream(fis1);
byte[] keyBytes1 = new byte[(int) file1.length()];
dis1.readFully(keyBytes1);
dis1.close();
X509EncodedKeySpec spec1 = new X509EncodedKeySpec(keyBytes1);
KeyFactory kf1 = KeyFactory.getInstance("RSA");
RSAPublicKey pubKey = (RSAPublicKey) kf1.generatePublic(spec1);
System.out.println("Exponent :" + pubKey.getPublicExponent());
System.out.println("Modulus" + pubKey.getModulus());
}
}
程序输出:
PUBLIC KEY EXPO : 65537
PRIVATE KEY : 16540425323481903232154296082061217323015064904150073221896716535825697862890781586244035403066600439504989225032100277459509106847714925918656002207273016950425690931486784061794302602299415224979080443644674838230854689682941689891752703570749249869153966528967635783430367525635094847999700308350727275663213969614628360232440655477057807291869565586695953970804798770095849408924111596670565606097668752646013504502815936286143578191877967720393294592625997337105475883689954727277867955887242546330469781268095607005541678733388864537898085207735975487415418212440417692928205650585590564551063589766600954407329