外壳程序中的这些openssl命令创建RSA密钥对,并将公用密钥和专用密钥写入 DER 格式的文件。
在这里,私钥文件没有密码保护(-nocrypt),以使事情变得简单。
$ openssl genrsa -out keypair.pem 2048Generating RSA private key, 2048 bit long modulus............+++................................+++e is 65537 (0x10001)$ openssl rsa -in keypair.pem -outform DER -pubout -out public.derwriting RSA key$ openssl pkcs8 -topk8 -nocrypt -in keypair.pem -outform DER -out private.der
现在有了DER文件,您可以用Java读取它们,并使用 KeySpec 和 KeyFactory 创建 PublicKey 和
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{ X509EnpredKeySpec publicSpec = new X509EnpredKeySpec(readFileBytes(filename)); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePublic(publicSpec); }public PrivateKey readPrivateKey(String filename) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException{ PKCS8EnpredKeySpec keySpec = new PKCS8EnpredKeySpec(readFileBytes(filename)); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(keySpec); }使用公钥和私钥,可以加密和解密少量数据(适合RSA模数)。我建议使用 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);}在这里,它与简单的加密和解密结合在一起:
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(); }}


