I'm not very familiar with encryption of files in java or openssl for that matter. I know the basics from school but have never actually implemented it.
Now I've been given the following 3 commands:
//generate random base64 private key
openssl rand -base64 32 -out (keypath)
//Encrypt random key with public key
openssl rsautl -encrypt -inkey (encryptionkey) -pubin -in (input) -out (output)
//encrypt file
openssl enc -aes-256-cbc -salt -in (input) -out (output) -pass file:(keypath)
I need to replicate this exactly in java. Is there an easy way of doing this? Are there a library i can use which makes this easier?
For the first line I'm using the SecureRandom function from java 7 to generate a byte array which i then encore to base64 using apache commons codec library. like so:
byte[] bytes = new byte[32];
new SecureRandom().nextBytes(bytes);
String test = new String(Base64.encodeBase64(bytes));
test = test.substring(0, Math.min(test.length(), 10));
If i'm not mistaken this should do the same thing.
For the second I need to encrypt the file containing the output from the above script using a provided public RSA key. Is there a difference between encrypting a file or the data inside the file? meaning does the actual file add bits?
The third however is where it gets hard since it needs a salt and the aes-256-cbc encryption standard. I'm hoping there is a library which encompasses all the functionality required. If so can anyone point me in the right direction? I was reading about bouncy castle's crypto library but haven't had much luck finding the things i need.
kind regards
The random byte array code is fine but why Base64 encode the random bytes, that is really only neccessary for display of perhaps use where only ASCII charactrers are required.
For AES encryption see the Java docs for javax.crypto.
Use
SecureRandom
to create the iv and prepend it to the encrypted data, it does not need to be secret. On decryption just pick the iv from the data to use for the iv.