/*
* Copyright 2002-2007 the original author or authors.
*
* 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 org.internna.iwebmvc.crypto.impl;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.internna.iwebmvc.crypto.Cipherer;
import org.internna.iwebmvc.crypto.Decipherer;
import org.springframework.beans.factory.InitializingBean;
import static org.internna.iwebmvc.utils.StringUtils.*;
/**
* 3DES implementation based on BouncyCastle libraries.
*
* @author Jose Noheda
* @since 1.0
*/
public class DES3CiphererDecipherer implements Cipherer, Decipherer, InitializingBean {
protected final Log logger = LogFactory.getLog(getClass());
private static final int RANDOM = 168;
private static final String ENCODING = "UTF8";
private Cipher cipherer;
private Cipher decipherer;
public final Cipher getCipherer() {
return cipherer;
}
public final Cipher getDecipherer() {
return decipherer;
}
/**
* Initialization method. Creates DESede/ECB/PKCS5Padding keys. A new key
* is generated with each invocation (redeploy/reboot).
*
* @throws java.lang.Exception
*/
@Override public final void afterPropertiesSet() throws Exception {
Security.addProvider(new BouncyCastleProvider());
cipherer = Cipher.getInstance("DESede/ECB/PKCS5Padding", "BC");
SecretKey key = getEncryptionKey();
cipherer.init(Cipher.ENCRYPT_MODE, key);
decipherer = Cipher.getInstance("DESede/ECB/PKCS5Padding", "BC");
decipherer.init(Cipher.DECRYPT_MODE, key);
if (logger.isInfoEnabled()) logger.info("Cryptography loaded with [DESede/ECB/PKCS5Padding] algorityhms and initialized");
}
/**
* Generates a simetric random 3DES key.
*
* @return a non null instance
* @throws NoSuchAlgorithmException
*/
protected SecretKey getEncryptionKey() throws NoSuchAlgorithmException {
KeyGenerator keyGen = KeyGenerator.getInstance("DESede");
keyGen.init(RANDOM);
return keyGen.generateKey();
}
@Override
@SuppressWarnings("unchecked")
public final <T> T encrypt(T object) {
if (object instanceof String) return (T) encryptString(object.toString());
return object;
}
/**
* Performs the actual encryption using the generated key.
* @param element a string to be encrypted
* @return an unintelligible String
*/
protected String encryptString(final String element) {
try {
byte[] bytes = cipherer.doFinal(element.getBytes(ENCODING));
bytes = Base64.encodeBase64(bytes);
return new String(bytes, ENCODING);
} catch (Exception ex) {
if (logger.isDebugEnabled()) logger.debug("Could not encrypt [" + element + "]: " + ex.getMessage() + " (Returning unencrypted value)");
return element;
}
}
/**
* Performs the actual deciphering using the generated key.
*
* @param encText
* @return a readable String
*/
@Override public final String decrypt(final String encText) {
try {
String toDecode = replace(encText, " ", "+");
byte[] bytes = toDecode.getBytes(ENCODING);
bytes = Base64.decodeBase64(bytes);
return new String(decipherer.doFinal(bytes), ENCODING);
} catch (Exception ex) {
return encText;
}
}
/**
* Detects encrypted text.
*
* @param test a String
* @return <code>true</code> if the string was previously encrypted
*/
@Override public final boolean isEncrypted(String test) {
return hasText(test) ? !decrypt(test).equals(test) : false;
}
@Override public String toString() {
return "Triple DES Cipherer/Decipherer";
}
}