01-24-2013 04:02 AM - edited 01-24-2013 04:13 AM
Since I was stuck with this for weeks I will help you all out with my working example code. Hope you enjoy it. I really don't want to put you in the same tunnel where I was. Cause you simply can't find anything about this on the internet. Well, not with using your own existing public and private keys.
Now, lets start.
Convert your Private PEM key to DER using openssl
1) openssl pkcs8 -topk8 -inform PEM -outform DER -in my.private.key -nocrypt > pkcs8_private_key.der
2) we will get the public key of your PEM .crt (Certificate file)
//Here what I did and use
openssl pkcs8 -topk8 -inform PEM -outform DER -in my.private.key -nocrypt > pkcs8_private_key.der //First get the private key RSAPrivateKey privKey = privKey = (RSAPrivateKey)PKCS8_PrivateKeyDecoder.decode(getClass().getResourceAsStream("pkcs8_private_key.der" ), "PKCS8"); //Now get the public key from our PEM RSA certificate InputStream stream = getClass().getResourceAsStream("sams.crt"); byte[] base64bytes = new byte[stream.available()]; stream.read(base64bytes, 0, base64bytes.length); stream.close(); X509Certificate cert = (X509Certificate) CertificateUtilities.readCertificateFile("X509", base64bytes); pubKey = (RSAPublicKey) cert.getPublicKey(); //Initiate the Crypto system RSACryptoSystem crypt = crypt = new RSACryptoSystem(2048); //I used 2048 bits keys //Example method to encrypt data with the above objects public String encrypt(String data){ try{ if(data.length() > 0){ NoCopyByteArrayOutputStream out = new NoCopyByteArrayOutputStream(); data = data.trim(); byte[] plain = data.getBytes(); RSAEncryptorEngine eng = new RSAEncryptorEngine(this.pubKey); PKCS1FormatterEngine fengine = new PKCS1FormatterEngine(eng); BlockEncryptor cryptoStream = new BlockEncryptor(fengine, out); cryptoStream.write( plain, 0, plain.length ); cryptoStream.flush(); cryptoStream.close(); out.close(); byte[] cipherText = out.getByteArray(); String encMessage = Base64OutputStream.encodeAsString(cipherText, 0, cipherText.length, false, false); return encMessage; }else{ return ""; } } catch(Exception err){ System.err.println(err.toString()); return ""; } }
Also, i you need help with anything. Contact me on twitter: @digital_human or visit my blog: http://victorangelier.blogspot.com
01-24-2013 04:41 AM
01-24-2013 08:56 AM
Yes I can, where and howto do it?
01-24-2013 08:58 AM
01-24-2013 09:01 AM
You are way to fast
Thx
01-24-2013 09:24 AM
Consider it done.