Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to encrypt decrypt with RSA keys in java
    text
    copied!<p>I need to replace the encrypt and decrypt step from Unix to java code with the <code>rsaprivatekey.pem</code> and <code>rsapublickey.pem</code> keys generated with openssl</p> <p>I generate the keys</p> <pre><code>openssl genrsa -out /tmp/rsaprivatekey.pem -des3 1024 openssl rsa -in /tmp/rsaprivatekey.pem -pubout -out /tmp/rsapublickey.pem </code></pre> <p>i use the keys in unix (i need do it in java)</p> <pre><code>echo "Text to encript"| openssl rsautl -encrypt -inkey /tmp/rsapublickey.pem -pubin -out out.enc openssl rsautl -decrypt -inkey /tmp/rsaprivatekey.pem -in out.enc </code></pre> <p>This was my attempt to do it</p> <pre><code>public static void main(String[] args) { Base64 base64 = new Base64(); String TextStream = "this is the input text"; byte[] Cipher; System.out.println("input:\n" + TextStream); Cipher = encrypt(TextStream); System.out.println("cipher:\n" + base64.encodeAsString(Cipher)); System.out.println("decrypt:\n" + decrypt(Cipher)); } private static byte[] encrypt(String Buffer) { try { Cipher rsa; rsa = Cipher.getInstance("RSA"); rsa.init(Cipher.ENCRYPT_MODE, getPrivateKey(PRIVATE_PATH)); return rsa.doFinal(Buffer.getBytes()); } catch (Exception e) { e.printStackTrace(); } return null; } private static String decrypt(byte[] buffer) { try { Cipher rsa; rsa = Cipher.getInstance("RSA"); rsa.init(Cipher.DECRYPT_MODE, getPrivateKey(PUBLIC_PATH)); byte[] utf8 = rsa.doFinal(buffer); return new String(utf8, "UTF8"); } catch (Exception e) { e.printStackTrace(); } return null; } public static PrivateKey getPrivateKey(String filename) throws Exception { File f = new File(filename); FileInputStream fis = new FileInputStream(f); DataInputStream dis = new DataInputStream(fis); byte[] keyBytes = new byte[(int) f.length()]; dis.readFully(keyBytes); dis.close(); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePrivate(spec); } public static PublicKey getPublicKey(String filename) throws Exception { File f = new File(filename); FileInputStream fis = new FileInputStream(f); DataInputStream dis = new DataInputStream(fis); byte[] keyBytes = new byte[(int) f.length()]; dis.readFully(keyBytes); dis.close(); X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePublic(spec); } </code></pre> <p>but it not works, the PKCS8EncodedKeySpec/X509EncodedKeySpec are not correct... but i do not know what to put</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload