These openssl shell commands create an RSA key pair and write the public and private keys to DER files.
Here the private key file is not password protected (-nocrypt) to make things simple.
$ openssl genrsa -out keypair.pem 2048 Generating RSA private key, 2048 bit long modulus ............+++ ................................+++ e is 65537 (0x10001) $ openssl rsa -in keypair.pem -outform DER -pubout -out public.der writing RSA key $ openssl pkcs8 -topk8 -nocrypt -in keypair.pem -outform DER -out private.der
Now that you have the DER files, you can read them in Java and use KeySpec and KeyFactory to create PublicKey and PrivateKey .
public byte[] readFileBytes(String filename) throws IOException { Path path = Paths.get(filename); return Files.readAllBytes(path); } public PublicKey readPublicKey(String filename) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(readFileBytes(filename)); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePublic(publicSpec); } public PrivateKey readPrivateKey(String filename) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(readFileBytes(filename)); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(keySpec); }
Using public and private keys, you can encrypt and decrypt small amounts of data (which correspond to your RSA module). I recommend supplementing OAEP .
public byte[] encrypt(PublicKey key, byte[] plaintext) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher.doFinal(plaintext); } public byte[] decrypt(PrivateKey key, byte[] ciphertext) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding"); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(ciphertext); }
Here it is associated with simple encryption and decryption:
public void Hello() { try { PublicKey publicKey = readPublicKey("public.der"); PrivateKey privateKey = readPrivateKey("private.der"); byte[] message = "Hello World".getBytes("UTF8"); byte[] secret = encrypt(publicKey, message); byte[] recovered_message = decrypt(privateKey, secret); System.out.println(new String(recovered_message, "UTF8")); } catch (Exception e) { e.printStackTrace(); } }