A short guide to encrypt strings with openssl (such as in Linux) and decrypt them in Java and vice-versa
Open SSL:
To encrypt a string using a password (using a random salt and base64 encoding the binary result):
echo -n 'string to encrypt' | openssl enc -des -a -e -k 'password to use' To decrypt a string (such as the one produced by the statement above):
echo 'base64 encoded string to decrypt' | openssl enc -des -a -d -k 'password to use'To make sure this works for you, just type the following (the "-n" is omitted from echo so a new line is printed):
echo 'test' | openssl enc -des -a -e -k 'pwd' | openssl enc -des -a -d -k 'pwd'
This should print 'test' to the standard output (without quotes) Java:
The full source code of the class is at the end of the post. Full maven based project can be obtained from "svn checkout http://tomas-sample-code.googlecode.com/svn/trunk/openssl-roundtrip".To decrypt a string encrypted with the above method, we have to understand the structure of the generated bytes. The openssl command creates the following structure (this is the "raw" bytes that get base64 encoded later):
bytes 1 - 8: "magic" word, fixed to "Salted__"
bytes 9 - 16: salt used to encrypt the string
bytes 17 and up: the actual encrypted value
The algorithm used in java is "PBEWithMD5AndDES" and the iteration count is 1.
Encryption in java follows the same rules, only the salt is randomly generated, to make sure that when we encrypt the same text twice with the same password, we get a different result (mostly).
I am using the Apache commons-codec library for base64 encoding.