PasswordBasedEncryptor - password based encryption made simple

There are a bunch of algorithms and even more crypto-libraries, tools, whatever in the wild. If you just need to encrypt and decrypt data based on a user provided password without fluff, take a look at this one.


/*
 * Lithium Utilities
 * 
 * Copyright 2007-2011 Tibor Bősze <tibor.boesze@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package hu.lithium.utils.crypto;


import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

/**
 * Utility class for password based encryption of... well mostly other passwords.
 * 
 * @author tibi
 * @version 1.1
 */
public class PasswordBasedEncryptor {

	private static final String algo = "PBEWithMD5AndDES";
	private static final int iterations = 7;
	private static final byte[] salt = new byte[] { (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, (byte) 0xDE,
			(byte) 0xAD, (byte) 0xBE, (byte) 0xEF };
	
	private final SecretKey secretKey;
	private final PBEParameterSpec params;

	public PasswordBasedEncryptor(char[] password) throws InvalidKeySpecException, NoSuchAlgorithmException {
		this(password, salt, iterations);
	}

	public PasswordBasedEncryptor(char[] password, byte[] salt, int iterations) throws InvalidKeySpecException,
			NoSuchAlgorithmException {
		params = new PBEParameterSpec(salt, iterations);
		PBEKeySpec ks = new PBEKeySpec(password);
		secretKey = SecretKeyFactory.getInstance(algo).generateSecret(ks);
		ks.clearPassword();
	}

	public byte[] encrypt(byte[] raw) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
			InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
		Cipher c = Cipher.getInstance(algo);
		c.init(Cipher.ENCRYPT_MODE, secretKey, params);
		return c.doFinal(raw);
	}

	public byte[] decrypt(byte[] enc) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
			InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
		Cipher c = Cipher.getInstance(algo);
		c.init(Cipher.DECRYPT_MODE, secretKey, params);
		return c.doFinal(enc);
	}

	public String encryptToBase64(byte[] raw) throws NoSuchAlgorithmException, NoSuchPaddingException,
			InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
		return new String(Base64.encode(encrypt(raw)));
	}

	public byte[] decryptFromBase64(String encb64) throws NoSuchAlgorithmException, NoSuchPaddingException,
			InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
		return decrypt(Base64.decode(encb64));
	}
	
	public static void main(String[] args) throws Exception {
		
		if (args.length != 3) {
			System.out.println("Usage: {encrypt|decrypt} <password> <data>");
			return;
		}
		
		boolean decrypt = "decrypt".equalsIgnoreCase(args[0]);
		String password = args[1]==null?"secret":args[1];
		String data = args[2]==null?"example":args[2];
		
		PasswordBasedEncryptor pbe = new PasswordBasedEncryptor(password.toCharArray());
		if (!decrypt) {
			System.out.println("encrypt(" + data + "): " + pbe.encryptToBase64(data.getBytes()));
		} else {
			System.out.println("decrypt(" + data + "): " + new String(pbe.decryptFromBase64(data)));
		}
	}

}
© 2003-2020 lithium.io7.org
Content on this site is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.