Skip to main content

Encryptic

Posted by evanx on April 19, 2007 at 4:17 AM PDT

Earlier we considered using straight Base-64 for hiding sensitive data from prying eyes.

Let's take it a step further and actually encrypt the data using a known password.

Code snippet

We implement the following class to support password-based encryption using the DES algorithm.

public class PBECipher {
    private static final String pbeAlgorithm = "PBEWithMD5AndDES";
    private static final String defaultPassword = "ssh ssh!";
    ...
    public PBECipher() {
        this(defaultPassword);
    }
   
    public PBECipher(String password) {
        try {
            parameterSpec = new PBEParameterSpec(salt, iterationCount);
            secretKey = createSecretKey(password);
            encryptCipher = createEncryptCipher();
            decryptCipher = createDecryptCipher();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    ...
    public String decrypt(String string) {
        try {
            return new String(decryptCipher.doFinal(Base64.decode(string)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }   

where we instantiate a PBEParameterSpec with an arbitrary 8-byte salt and iterationCount.