All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.dirksm.crypt.AES Maven / Gradle / Ivy

package com.github.dirksm.crypt;

import static com.google.common.io.BaseEncoding.base64;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang3.StringUtils;

import com.github.dirksm.crypt.exception.EncryptionException;
import com.google.common.base.Charsets;

public class AES implements Encryptor, Decryptor {
	
	private static final String PREFIX = "{AES}";
	private final String passphrase;
	
	public AES(String passphrase) {
		String formatted = StringUtils.trimToEmpty(passphrase);
		this.passphrase = StringUtils.rightPad(formatted, 16, 'X').substring(0,16);
	}
	
	protected String getPassphrase() {
		return this.passphrase;
	}
	
	public String decrypt(String encryptedData) throws EncryptionException {
		Cipher c;
		byte[] decrypted;
		try {
			c = cipher(Cipher.DECRYPT_MODE);
			String encrypted = encryptedData.substring(PREFIX.length());
			decrypted = c.doFinal(base64().decode(encrypted));
			return new String(decrypted, Charsets.UTF_8);
		} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
			throw new EncryptionException("Could not decrypt value with provided passphrase.", e);
		}
	}

	public String encrypt(String password) throws EncryptionException {
		try {
			Cipher c = cipher(Cipher.ENCRYPT_MODE);
			final byte[] encrypted = c.doFinal(password.getBytes(Charsets.UTF_8));
			return PREFIX + base64().encode(encrypted);
		} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
			throw new EncryptionException("Could not encrypt value with provided passphrase.", e);
		}
	}
	
	public boolean canDecrypt(String value) {
		return value.startsWith(PREFIX);
	}

	private Cipher cipher(int mode) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
		Key key = new SecretKeySpec(this.passphrase.getBytes(Charsets.UTF_8), 0, this.passphrase.length(), "AES");
		
		Cipher cipher = Cipher.getInstance(key.getAlgorithm());
		cipher.init(mode, key);
		
		return cipher;
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy