mirror of
https://github.com/Alfresco/alfresco-community-repo.git
synced 2025-08-07 17:49:17 +00:00
Added Encryptor interface for symmetric encryption esp. targeting SealedObject
- This will allow a keystore to be checked in (.keystore) and specified by installer - Algorithm parameters embedded in SealedObject but also supported by other Cipher methods ALF-8646: RINF 38: Text data encryption ALF-8956: RINF 38: Encryption key password specified by installer ALF-9055: RINF 38: Support encryption against existing data git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@28438 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
This commit is contained in:
@@ -1,109 +0,0 @@
|
||||
package org.alfresco.repo.security.encryption;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.Key;
|
||||
import java.security.Security;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
|
||||
import org.alfresco.error.AlfrescoRuntimeException;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
|
||||
public class AESEncryptionEngine implements EncryptionEngine
|
||||
{
|
||||
private static String ALGORITHM = "AES/ECB/PKCS5Padding";
|
||||
private static final Log logger = LogFactory.getLog(AESEncryptionEngine.class);
|
||||
|
||||
private KeyProvider keyProvider;
|
||||
//private Key key;
|
||||
|
||||
private ThreadLocal<Cipher> cipher;
|
||||
|
||||
public AESEncryptionEngine()
|
||||
{
|
||||
}
|
||||
|
||||
public void setKeyProvider(KeyProvider keyProvider)
|
||||
{
|
||||
this.keyProvider = keyProvider;
|
||||
}
|
||||
|
||||
public void init()
|
||||
{
|
||||
this.cipher = new ThreadLocal<Cipher>();
|
||||
// key = keyProvider.getKey();
|
||||
// if(key == null)
|
||||
// {
|
||||
// throw new AlfrescoRuntimeException("Secret key is null.");
|
||||
// }
|
||||
}
|
||||
|
||||
protected byte[] process(int cipherMode, byte[] input)
|
||||
{
|
||||
Cipher cipher = this.cipher.get();
|
||||
|
||||
if(cipher == null)
|
||||
{
|
||||
try
|
||||
{
|
||||
cipher = Cipher.getInstance(ALGORITHM);
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
Security.addProvider(new BouncyCastleProvider());
|
||||
try
|
||||
{
|
||||
cipher = Cipher.getInstance(ALGORITHM);
|
||||
}
|
||||
catch(Exception e1)
|
||||
{
|
||||
throw new AlfrescoRuntimeException("Unable to initialise encryption engine", e1);
|
||||
}
|
||||
}
|
||||
|
||||
if(cipher == null)
|
||||
{
|
||||
throw new AlfrescoRuntimeException("Unable to initialise encryption engine");
|
||||
}
|
||||
|
||||
this.cipher.set(cipher);
|
||||
|
||||
logger.debug("Initialised thread local cipher");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
cipher.init(cipherMode, keyProvider.getKey());
|
||||
|
||||
// do the encryption/decryption in one go
|
||||
return cipher.doFinal(input);
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
throw new AlfrescoRuntimeException("Unexpected exception during encryption/decryption", e);
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] encrypt(byte[] input)
|
||||
{
|
||||
return process(Cipher.ENCRYPT_MODE, input);
|
||||
}
|
||||
|
||||
public byte[] decrypt(byte[] input)
|
||||
{
|
||||
return process(Cipher.DECRYPT_MODE, input);
|
||||
}
|
||||
|
||||
public byte[] encryptString(String input) throws UnsupportedEncodingException
|
||||
{
|
||||
byte[] in = input.getBytes("UTF-8");
|
||||
return encrypt(in);
|
||||
}
|
||||
|
||||
public String decryptAsString(byte[] input) throws UnsupportedEncodingException
|
||||
{
|
||||
return new String(decrypt(input), "UTF-8").trim();
|
||||
}
|
||||
}
|
@@ -0,0 +1,189 @@
|
||||
package org.alfresco.repo.security.encryption;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.io.Serializable;
|
||||
import java.security.AlgorithmParameters;
|
||||
import java.security.Key;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.SealedObject;
|
||||
|
||||
import org.alfresco.error.AlfrescoRuntimeException;
|
||||
import org.alfresco.util.Pair;
|
||||
import org.alfresco.util.PropertyCheck;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
/**
|
||||
* Basic support for encryption engines.
|
||||
*
|
||||
* @since 4.0
|
||||
*/
|
||||
public abstract class AbstractEncryptor implements Encryptor
|
||||
{
|
||||
private static final Log logger = LogFactory.getLog(AbstractEncryptor.class);
|
||||
|
||||
private KeyProvider keyProvider;
|
||||
|
||||
/**
|
||||
* Constructs with defaults
|
||||
*/
|
||||
protected AbstractEncryptor()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* @param keyProvider provides encryption keys based on aliases
|
||||
*/
|
||||
public void setKeyProvider(KeyProvider keyProvider)
|
||||
{
|
||||
this.keyProvider = keyProvider;
|
||||
}
|
||||
|
||||
public void init()
|
||||
{
|
||||
PropertyCheck.mandatory(this, "keyProvider", keyProvider);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Cipher getCipher(String keyAlias, AlgorithmParameters params, int mode)
|
||||
{
|
||||
// Get the encryption key
|
||||
Key key = keyProvider.getKey(keyAlias);
|
||||
if (key == null)
|
||||
{
|
||||
// No encryption possible
|
||||
return null;
|
||||
}
|
||||
try
|
||||
{
|
||||
Cipher cipher = getCipher(key, params, mode);
|
||||
// Done
|
||||
if (logger.isDebugEnabled())
|
||||
{
|
||||
logger.debug("Cipher constructed: alias=" + keyAlias + "; mode=" + mode + ": " + cipher);
|
||||
}
|
||||
return cipher;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new AlfrescoRuntimeException(
|
||||
"Failed to construct cipher: alias=" + keyAlias + "; mode=" + mode,
|
||||
e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Factory method to be written by implementations to construct <b>and initialize</b>
|
||||
* physical ciphering objects.
|
||||
*
|
||||
* @param keyAlias the key alias
|
||||
* @param params algorithm-specific parameters
|
||||
* @param mode the cipher mode
|
||||
* @return
|
||||
*/
|
||||
protected abstract Cipher getCipher(Key key, AlgorithmParameters params, int mode) throws Exception;
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public Pair<byte[], AlgorithmParameters> encrypt(String keyAlias, AlgorithmParameters params, byte[] input)
|
||||
{
|
||||
Cipher cipher = getCipher(keyAlias, params, Cipher.ENCRYPT_MODE);
|
||||
if (cipher == null)
|
||||
{
|
||||
return new Pair<byte[], AlgorithmParameters>(input, null);
|
||||
}
|
||||
try
|
||||
{
|
||||
byte[] output = cipher.doFinal(input);
|
||||
params = cipher.getParameters();
|
||||
return new Pair<byte[], AlgorithmParameters>(output, params);
|
||||
}
|
||||
catch (Throwable e)
|
||||
{
|
||||
throw new AlfrescoRuntimeException("Decryption failed for key alias: " + keyAlias, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public byte[] decrypt(String keyAlias, AlgorithmParameters params, byte[] input)
|
||||
{
|
||||
Cipher cipher = getCipher(keyAlias, params, Cipher.DECRYPT_MODE);
|
||||
if (cipher == null)
|
||||
{
|
||||
return input;
|
||||
}
|
||||
try
|
||||
{
|
||||
return cipher.doFinal(input);
|
||||
}
|
||||
catch (Throwable e)
|
||||
{
|
||||
throw new AlfrescoRuntimeException("Decryption failed for key alias: " + keyAlias, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* <p/>
|
||||
* Serializes and {@link #encrypt(byte[]) encrypts} the input data.
|
||||
*/
|
||||
@Override
|
||||
public Pair<byte[], AlgorithmParameters> encryptObject(String keyAlias, AlgorithmParameters params, Object input)
|
||||
{
|
||||
try
|
||||
{
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
|
||||
ObjectOutputStream oos = new ObjectOutputStream(bos);
|
||||
oos.writeObject(input);
|
||||
byte[] unencrypted = bos.toByteArray();
|
||||
return encrypt(keyAlias, params, unencrypted);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new AlfrescoRuntimeException("Failed to serialize or encrypt object", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
* <p/>
|
||||
* {@link #decrypt(byte[]) Decrypts} and deserializes the input data
|
||||
*/
|
||||
@Override
|
||||
public Object decryptObject(String keyAlias, AlgorithmParameters params, byte[] input)
|
||||
{
|
||||
try
|
||||
{
|
||||
byte[] unencrypted = decrypt(keyAlias, params, input);
|
||||
ByteArrayInputStream bis = new ByteArrayInputStream(unencrypted);
|
||||
ObjectInputStream ois = new ObjectInputStream(bis);
|
||||
Object obj = ois.readObject();
|
||||
return obj;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new AlfrescoRuntimeException("Failed to deserialize or decrypt object", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public SealedObject sealObject(String keyAlias, AlgorithmParameters params, Serializable input)
|
||||
{
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Serializable unsealObject(String keyAlias, SealedObject input)
|
||||
{
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
@@ -1,101 +1,21 @@
|
||||
package org.alfresco.repo.security.encryption;
|
||||
|
||||
import java.security.InvalidParameterException;
|
||||
import java.security.Key;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.Security;
|
||||
|
||||
import javax.crypto.KeyGenerator;
|
||||
import org.alfresco.util.ParameterCheck;
|
||||
|
||||
import org.alfresco.error.AlfrescoRuntimeException;
|
||||
import org.alfresco.repo.security.authentication.PasswordGenerator;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||
|
||||
public abstract class AbstractKeyProvider /*extends AbstractLifecycleBean*/ implements KeyProvider
|
||||
/**
|
||||
* Basic support for key providers
|
||||
*
|
||||
* @author Derek Hulley
|
||||
* @since 4.0
|
||||
*/
|
||||
public abstract class AbstractKeyProvider implements KeyProvider
|
||||
{
|
||||
private static final Log logger = LogFactory.getLog(KeyProvider.class);
|
||||
|
||||
private static int KEY_SIZE = 256; // this requires unlimited strength policy files
|
||||
private static int DEFAULT_KEY_SIZE = 128; // default key size should work if KEY_SIZE doesn't
|
||||
private static String KEY_ALGORITHM = "AES";
|
||||
|
||||
protected PasswordGenerator passwordGenerator;
|
||||
|
||||
private Key key;
|
||||
|
||||
public void setKey(Key key)
|
||||
@Override
|
||||
public Key getKey(AlfrescoKeyAlias keyAlias)
|
||||
{
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
|
||||
public PasswordGenerator getPasswordGenerator()
|
||||
{
|
||||
return passwordGenerator;
|
||||
}
|
||||
|
||||
public void setPasswordGenerator(PasswordGenerator passwordGenerator)
|
||||
{
|
||||
this.passwordGenerator = passwordGenerator;
|
||||
}
|
||||
|
||||
public Key getKey()
|
||||
{
|
||||
return key;
|
||||
}
|
||||
|
||||
protected KeyGenerator getKeyGenerator()
|
||||
{
|
||||
KeyGenerator keyGenerator = null;
|
||||
|
||||
try
|
||||
{
|
||||
keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
|
||||
}
|
||||
catch(NoSuchAlgorithmException e)
|
||||
{
|
||||
Security.addProvider(new BouncyCastleProvider());
|
||||
try
|
||||
{
|
||||
keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
|
||||
}
|
||||
catch(NoSuchAlgorithmException e1)
|
||||
{
|
||||
throw new AlfrescoRuntimeException("Unable to initialise encryption engine, no key generator is available", e1);
|
||||
}
|
||||
}
|
||||
|
||||
if(keyGenerator == null)
|
||||
{
|
||||
throw new AlfrescoRuntimeException("Unable to initialise encryption engine, no key generator is available");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
keyGenerator.init(KEY_SIZE);
|
||||
}
|
||||
catch(InvalidParameterException e)
|
||||
{
|
||||
logger.warn(KEY_SIZE + " bits key size is not supported, trying " + DEFAULT_KEY_SIZE + " bits");
|
||||
try
|
||||
{
|
||||
// try a smaller key size
|
||||
keyGenerator.init(DEFAULT_KEY_SIZE);
|
||||
}
|
||||
catch(InvalidParameterException e1)
|
||||
{
|
||||
throw new AlfrescoRuntimeException("Unable to initialise encryption engine, no key generator is available", e1);
|
||||
}
|
||||
}
|
||||
|
||||
return keyGenerator;
|
||||
}
|
||||
|
||||
protected Key generateSecretKey()
|
||||
{
|
||||
KeyGenerator keyGenerator = getKeyGenerator();
|
||||
return keyGenerator.generateKey();
|
||||
ParameterCheck.mandatory("keyAlias", keyAlias);
|
||||
return getKey(keyAlias.name());
|
||||
}
|
||||
}
|
||||
|
@@ -1,129 +0,0 @@
|
||||
package org.alfresco.repo.security.encryption;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.Security;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
|
||||
import org.alfresco.error.AlfrescoRuntimeException;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.bouncycastle.crypto.BufferedBlockCipher;
|
||||
import org.bouncycastle.crypto.CipherParameters;
|
||||
import org.bouncycastle.crypto.InvalidCipherTextException;
|
||||
import org.bouncycastle.crypto.engines.AESEngine;
|
||||
import org.bouncycastle.crypto.paddings.BlockCipherPadding;
|
||||
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
|
||||
import org.bouncycastle.crypto.paddings.ZeroBytePadding;
|
||||
import org.bouncycastle.crypto.params.KeyParameter;
|
||||
|
||||
public class DefaultEncryptionEngine implements EncryptionEngine
|
||||
{
|
||||
private static final Log logger = LogFactory.getLog(EncryptionEngine.class);
|
||||
|
||||
//private String encryptionProvider;
|
||||
private KeyProvider keyProvider;
|
||||
|
||||
private BufferedBlockCipher cipher;
|
||||
private AESEngine engine;
|
||||
|
||||
//private Cipher cipher;
|
||||
//private byte[] key;
|
||||
|
||||
public DefaultEncryptionEngine(/*byte[] key*/)
|
||||
{
|
||||
// TODO check that this hasn't already been done
|
||||
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
|
||||
//
|
||||
// this.key = key;
|
||||
}
|
||||
|
||||
public void setKeyProvider(KeyProvider keyProvider)
|
||||
{
|
||||
this.keyProvider = keyProvider;
|
||||
}
|
||||
|
||||
// public void setEncryptionProvider(String encryptionProvider)
|
||||
// {
|
||||
// this.encryptionProvider = encryptionProvider;
|
||||
// }
|
||||
|
||||
public void init()
|
||||
{
|
||||
//cipher = Cipher.getInstance("AES");
|
||||
this.engine = new AESEngine();
|
||||
|
||||
/*
|
||||
* Paddings available (http://www.bouncycastle.org/docs/docs1.6/org/bouncycastle/crypto/paddings/BlockCipherPadding.html):
|
||||
* - ISO10126d2Padding
|
||||
* - ISO7816d4Padding
|
||||
* - PKCS7Padding
|
||||
* - TBCPadding
|
||||
* - X923Padding
|
||||
* - ZeroBytePadding
|
||||
*/
|
||||
BlockCipherPadding blockCipherPadding = new ZeroBytePadding();
|
||||
this.cipher = new PaddedBufferedBlockCipher(engine, blockCipherPadding);
|
||||
|
||||
// logger.debug("Encryption cipher: " + cipher.getProvider().getInfo());
|
||||
}
|
||||
|
||||
protected byte[] process(boolean toEncrypt, byte[] input)
|
||||
{
|
||||
try
|
||||
{
|
||||
//CipherParameters param = new KeyParameter(keyProvider.getKey());
|
||||
//cipher.init(toEncrypt, param);
|
||||
|
||||
int inputLength = input.length;
|
||||
int maximumOutputLength = cipher.getOutputSize(inputLength);
|
||||
byte[] output = new byte[maximumOutputLength];
|
||||
|
||||
int outputOffset = 0;
|
||||
int outputLength = 0;
|
||||
int bytesProcessed = cipher.processBytes(input, 0, input.length, output, 0);
|
||||
outputOffset += bytesProcessed;
|
||||
outputLength += bytesProcessed;
|
||||
bytesProcessed = cipher.doFinal(output, outputOffset);
|
||||
outputOffset += bytesProcessed;
|
||||
outputLength += bytesProcessed;
|
||||
|
||||
if(outputLength == output.length)
|
||||
{
|
||||
return output;
|
||||
}
|
||||
else
|
||||
{
|
||||
byte[] truncatedOutput = new byte[outputLength];
|
||||
System.arraycopy(output, 0, truncatedOutput, 0, outputLength);
|
||||
return truncatedOutput;
|
||||
}
|
||||
}
|
||||
catch(InvalidCipherTextException ex)
|
||||
{
|
||||
throw new AlfrescoRuntimeException("Unexpected encryption error", ex);
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] encrypt(byte[] input)
|
||||
{
|
||||
return process(true, input);
|
||||
}
|
||||
|
||||
public byte[] decrypt(byte[] input)
|
||||
{
|
||||
return process(false, input);
|
||||
}
|
||||
|
||||
public byte[] encryptString(String input) throws UnsupportedEncodingException
|
||||
{
|
||||
byte[] in = input.getBytes("UTF-8");
|
||||
return encrypt(in);
|
||||
}
|
||||
|
||||
public String decryptAsString(byte[] input) throws UnsupportedEncodingException
|
||||
{
|
||||
return new String(decrypt(input), "UTF-8").trim();
|
||||
}
|
||||
|
||||
}
|
@@ -1,32 +0,0 @@
|
||||
package org.alfresco.repo.security.encryption;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
public class DefaultEncryptionEngineTest extends TestCase
|
||||
{
|
||||
private DefaultEncryptionEngine encryptionEngine;
|
||||
|
||||
public void setUp() throws Exception
|
||||
{
|
||||
encryptionEngine = new DefaultEncryptionEngine();
|
||||
encryptionEngine.setKeyProvider(new TestKeyProvider());
|
||||
}
|
||||
|
||||
public void testBasic()
|
||||
{
|
||||
try
|
||||
{
|
||||
String testString = "Hello World";
|
||||
|
||||
byte[] bytes = encryptionEngine.encryptString(testString);
|
||||
String output = encryptionEngine.decryptAsString(bytes);
|
||||
assertEquals("", testString, output);
|
||||
}
|
||||
catch(UnsupportedEncodingException ex)
|
||||
{
|
||||
fail("Unexpected exception: " + ex);
|
||||
}
|
||||
}
|
||||
}
|
@@ -0,0 +1,75 @@
|
||||
package org.alfresco.repo.security.encryption;
|
||||
|
||||
import java.security.AlgorithmParameters;
|
||||
import java.security.Key;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
|
||||
import org.alfresco.util.PropertyCheck;
|
||||
|
||||
/**
|
||||
* @author Derek Hulley
|
||||
* @since 4.0
|
||||
*/
|
||||
public class DefaultEncryptor extends AbstractEncryptor
|
||||
{
|
||||
private String cipherAlgorithm;
|
||||
private String cipherProvider;
|
||||
|
||||
private final ThreadLocal<Cipher> threadCipher;
|
||||
|
||||
/**
|
||||
* Default constructor for IOC
|
||||
*/
|
||||
public DefaultEncryptor()
|
||||
{
|
||||
threadCipher = new ThreadLocal<Cipher>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience constructor for tests
|
||||
*/
|
||||
/* package */ DefaultEncryptor(KeyProvider keyProvider, String cipherAlgorithm, String cipherProvider)
|
||||
{
|
||||
this();
|
||||
setKeyProvider(keyProvider);
|
||||
setCipherAlgorithm(cipherAlgorithm);
|
||||
setCipherProvider(cipherProvider);
|
||||
}
|
||||
|
||||
public void setCipherAlgorithm(String cipherAlgorithm)
|
||||
{
|
||||
this.cipherAlgorithm = cipherAlgorithm;
|
||||
}
|
||||
|
||||
public void setCipherProvider(String cipherProvider)
|
||||
{
|
||||
this.cipherProvider = cipherProvider;
|
||||
}
|
||||
|
||||
public void init()
|
||||
{
|
||||
super.init();
|
||||
PropertyCheck.mandatory(this, "cipherAlgorithm", cipherAlgorithm);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Cipher getCipher(Key key, AlgorithmParameters params, int mode) throws Exception
|
||||
{
|
||||
Cipher cipher = threadCipher.get();
|
||||
if (cipher == null)
|
||||
{
|
||||
if (cipherProvider == null)
|
||||
{
|
||||
cipher = Cipher.getInstance(cipherAlgorithm);
|
||||
}
|
||||
else
|
||||
{
|
||||
cipher = Cipher.getInstance(cipherAlgorithm, cipherProvider);
|
||||
}
|
||||
threadCipher.set(cipher);
|
||||
}
|
||||
cipher.init(mode, key, params);
|
||||
return cipher;
|
||||
}
|
||||
}
|
@@ -1,12 +0,0 @@
|
||||
package org.alfresco.repo.security.encryption;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
|
||||
|
||||
public interface EncryptionEngine
|
||||
{
|
||||
public byte[] encrypt(byte[] input);
|
||||
public byte[] decrypt(byte[] input);
|
||||
public byte[] encryptString(String input) throws UnsupportedEncodingException;
|
||||
public String decryptAsString(byte[] input) throws UnsupportedEncodingException;
|
||||
}
|
@@ -0,0 +1,86 @@
|
||||
package org.alfresco.repo.security.encryption;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.security.AlgorithmParameters;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.SealedObject;
|
||||
|
||||
import org.alfresco.util.Pair;
|
||||
|
||||
|
||||
/**
|
||||
* Interface providing methods to encrypt and decrypt data.
|
||||
*
|
||||
* @since 4.0
|
||||
*/
|
||||
public interface Encryptor
|
||||
{
|
||||
/**
|
||||
* Get the basic cipher that must be used for the given use-case
|
||||
*
|
||||
* @param keyAlias the encryption key alias
|
||||
* @param params the parameters for the encryption or decryption
|
||||
* @param mode the encryption mode
|
||||
* @return the cipher to use or <tt>null</tt> if there is no
|
||||
* key associated with the key alias
|
||||
*/
|
||||
Cipher getCipher(String keyAlias, AlgorithmParameters params, int mode);
|
||||
|
||||
/**
|
||||
* Encrypt some bytes
|
||||
*
|
||||
* @param keyAlias the encryption key alias
|
||||
* @param input the data to encrypt
|
||||
* @return the encrypted data and parameters used
|
||||
*/
|
||||
Pair<byte[], AlgorithmParameters> encrypt(String keyAlias, AlgorithmParameters params, byte[] input);
|
||||
|
||||
/**
|
||||
* Decrypt some bytes
|
||||
*
|
||||
* @param keyAlias the encryption key alias
|
||||
* @param input the data to decrypt
|
||||
* @return the unencrypted data
|
||||
*/
|
||||
byte[] decrypt(String keyAlias, AlgorithmParameters params, byte[] input);
|
||||
|
||||
/**
|
||||
* Encrypt an object
|
||||
*
|
||||
* @param keyAlias the encryption key alias
|
||||
* @param input the object to write to bytes
|
||||
* @return the encrypted data and parameters used
|
||||
*/
|
||||
Pair<byte[], AlgorithmParameters> encryptObject(String keyAlias, AlgorithmParameters params, Object input);
|
||||
|
||||
/**
|
||||
* Decrypt data as an object
|
||||
*
|
||||
* @param keyAlias the encryption key alias
|
||||
* @param input the data to decrypt
|
||||
* @return the unencrypted data deserialized
|
||||
*/
|
||||
Object decryptObject(String keyAlias, AlgorithmParameters params, byte[] input);
|
||||
|
||||
/**
|
||||
* Convenience method to seal on object up cryptographically
|
||||
*
|
||||
* @param keyAlias the encryption key alias
|
||||
* @param input the object to encrypt and seal
|
||||
* @return the sealed object that can be decrypted with the original key
|
||||
*/
|
||||
SealedObject sealObject(String keyAlias, AlgorithmParameters params, Serializable input);
|
||||
|
||||
/**
|
||||
* Convenience method to unseal on object up cryptographically.
|
||||
* <p/>
|
||||
* Note that the algorithm parameters are stored in the sealed object and are
|
||||
* not therefore required for decryption.
|
||||
*
|
||||
* @param keyAlias the encryption key alias
|
||||
* @param input the object to decrypt and unseal
|
||||
* @return the original unsealed object that was encrypted with the original key
|
||||
*/
|
||||
Serializable unsealObject(String keyAlias, SealedObject input);
|
||||
}
|
@@ -0,0 +1,61 @@
|
||||
package org.alfresco.repo.security.encryption;
|
||||
|
||||
import java.security.AlgorithmParameters;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.alfresco.util.Pair;
|
||||
import org.bouncycastle.util.Arrays;
|
||||
|
||||
/**
|
||||
* @since 4.0
|
||||
*/
|
||||
public class EncryptorTest extends TestCase
|
||||
{
|
||||
private DefaultEncryptor encryptor;
|
||||
|
||||
public void setUp() throws Exception
|
||||
{
|
||||
encryptor = new DefaultEncryptor(
|
||||
KeyStoreKeyProviderTest.getTestKeyStoreProvider(),
|
||||
"DESede/CBC/PKCS5Padding",
|
||||
null);
|
||||
encryptor.init(); // Not currently necessary
|
||||
}
|
||||
|
||||
public void testBasicBytes_NoKey()
|
||||
{
|
||||
byte[] bytes = new byte[] {11, 12, 13};
|
||||
|
||||
Pair<byte[], AlgorithmParameters> encryptedPair = encryptor.encrypt("fluff", null, bytes);
|
||||
byte[] decrypted = encryptor.decrypt(
|
||||
"fluff",
|
||||
encryptedPair.getSecond(),
|
||||
encryptedPair.getFirst());
|
||||
assertTrue("Encryption round trip failed. ", Arrays.areEqual(bytes, decrypted));
|
||||
}
|
||||
|
||||
public void testBasicBytes_WithKey()
|
||||
{
|
||||
byte[] bytes = new byte[] {11, 12, 13};
|
||||
|
||||
Pair<byte[], AlgorithmParameters> encryptedPair = encryptor.encrypt("mykey1", null, bytes);
|
||||
byte[] decrypted = encryptor.decrypt(
|
||||
"mykey1",
|
||||
encryptedPair.getSecond(),
|
||||
encryptedPair.getFirst());
|
||||
assertTrue("Encryption round trip failed. ", Arrays.areEqual(bytes, decrypted));
|
||||
}
|
||||
|
||||
public void testBasicObject()
|
||||
{
|
||||
Object testObject = " This is a string, but will be serialized ";
|
||||
|
||||
Pair<byte[], AlgorithmParameters> encryptedPair = encryptor.encryptObject("mykey2", null, testObject);
|
||||
Object output = encryptor.decryptObject(
|
||||
"mykey2",
|
||||
encryptedPair.getSecond(),
|
||||
encryptedPair.getFirst());
|
||||
assertEquals("Encryption round trip failed. ", testObject, output);
|
||||
}
|
||||
}
|
@@ -3,11 +3,37 @@ package org.alfresco.repo.security.encryption;
|
||||
import java.security.Key;
|
||||
|
||||
/**
|
||||
* A key provider returns the secret key used to encrypt text and mltext properties in the
|
||||
* database.
|
||||
*
|
||||
* A key provider returns the secret keys for different use cases.
|
||||
*
|
||||
* @since 4.0
|
||||
*/
|
||||
public interface KeyProvider
|
||||
{
|
||||
public Key getKey();
|
||||
/**
|
||||
* Enumeration of key aliases supported internally by Alfresco
|
||||
*
|
||||
* @author derekh
|
||||
* @since 4.0
|
||||
*/
|
||||
public static enum AlfrescoKeyAlias
|
||||
{
|
||||
METADATA,
|
||||
SOLR
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an encryption key if available.
|
||||
*
|
||||
* @param keyAlias the key alias
|
||||
* @return the encryption key or <tt>null</tt> if there is no associated key
|
||||
*/
|
||||
public Key getKey(String keyAlias);
|
||||
|
||||
/**
|
||||
* Get an encryption key if available, using a convenience constant.
|
||||
*
|
||||
* @param keyAlias the key alias
|
||||
* @return the encryption key or <tt>null</tt> if there is no associated key
|
||||
*/
|
||||
public Key getKey(AlfrescoKeyAlias keyAlias);
|
||||
}
|
||||
|
@@ -0,0 +1,161 @@
|
||||
package org.alfresco.repo.security.encryption;
|
||||
|
||||
import java.security.Key;
|
||||
import java.security.KeyStore;
|
||||
import java.security.UnrecoverableKeyException;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.alfresco.error.AlfrescoRuntimeException;
|
||||
import org.alfresco.util.ApplicationContextHelper;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* Tests {@link KeystoreKeyProvider}
|
||||
*
|
||||
* @author Derek Hulley
|
||||
* @since 4.0
|
||||
*/
|
||||
public class KeyStoreKeyProviderTest extends TestCase
|
||||
{
|
||||
private static final String FILE_ONE = "classpath:alfresco/keystore-tests/ks-test-1.jks";
|
||||
private static final String FILE_TWO = "classpath:alfresco/keystore-tests/ks-test-2.jks";
|
||||
private static final String FILE_THREE = "classpath:alfresco/keystore-tests/ks-test-3.jks";
|
||||
private static final String ALIAS_ONE = "mykey1";
|
||||
private static final String ALIAS_TWO = "mykey2";
|
||||
private static final String ALIAS_THREE = "mykey3";
|
||||
|
||||
public void setUp() throws Exception
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper utility to create a two-alias keystore.
|
||||
*/
|
||||
/* package */ static KeystoreKeyProvider getTestKeyStoreProvider()
|
||||
{
|
||||
Map<String, String> passwords = new HashMap<String, String>(5);
|
||||
passwords.put(KeystoreKeyProvider.KEY_KEYSTORE_PASSWORD, "ksPwd2");
|
||||
passwords.put(ALIAS_ONE, "aliasPwd1");
|
||||
passwords.put(ALIAS_TWO, "aliasPwd2");
|
||||
KeystoreKeyProvider ks = new KeystoreKeyProvider(
|
||||
FILE_TWO,
|
||||
"SunJCE",
|
||||
"JCEKS",
|
||||
passwords);
|
||||
return ks;
|
||||
}
|
||||
|
||||
public void testNoKeyStorePasswords() throws Exception
|
||||
{
|
||||
KeystoreKeyProvider keyProvider = new KeystoreKeyProvider(
|
||||
FILE_ONE,
|
||||
"SunJCE",
|
||||
"JCEKS",
|
||||
Collections.<String,String>emptyMap());
|
||||
// This has succeeded because we have not attempted to access it
|
||||
assertNull("Should be no keys available", keyProvider.getKey(ALIAS_ONE));
|
||||
}
|
||||
|
||||
public void testKeyStoreWithOnlyAliasPasswords() throws Exception
|
||||
{
|
||||
KeystoreKeyProvider keyProvider = new KeystoreKeyProvider(
|
||||
FILE_TWO,
|
||||
"SunJCE",
|
||||
"JCEKS",
|
||||
Collections.singletonMap(ALIAS_ONE, "aliasPwd1"));
|
||||
// This has succeeded because we have not attempted to access it
|
||||
assertNotNull("Should be able to key alias with same password", keyProvider.getKey(ALIAS_ONE));
|
||||
}
|
||||
|
||||
public void testAliasWithIncorrectPassword_One() throws Exception
|
||||
{
|
||||
try
|
||||
{
|
||||
new KeystoreKeyProvider(
|
||||
FILE_ONE,
|
||||
"SunJCE",
|
||||
"JCEKS",
|
||||
Collections.singletonMap(ALIAS_ONE, "password_fail"));
|
||||
fail("Expect to fail because password is incorrect");
|
||||
}
|
||||
catch (AlfrescoRuntimeException e)
|
||||
{
|
||||
// Expected
|
||||
assertTrue(e.getCause() instanceof UnrecoverableKeyException);
|
||||
}
|
||||
}
|
||||
|
||||
public void testAliasWithIncorrectPassword_Two() throws Exception
|
||||
{
|
||||
try
|
||||
{
|
||||
new KeystoreKeyProvider(
|
||||
FILE_TWO,
|
||||
"SunJCE",
|
||||
"JCEKS",
|
||||
Collections.singletonMap(ALIAS_TWO, "password_fail"));
|
||||
fail("Expect to fail because password is incorrect");
|
||||
}
|
||||
catch (AlfrescoRuntimeException e)
|
||||
{
|
||||
// Expected
|
||||
assertTrue(e.getCause() instanceof UnrecoverableKeyException);
|
||||
}
|
||||
}
|
||||
|
||||
public void testAliasWithCorrectPassword_One() throws Exception
|
||||
{
|
||||
KeystoreKeyProvider ks = new KeystoreKeyProvider(
|
||||
FILE_ONE,
|
||||
"SunJCE",
|
||||
"JCEKS",
|
||||
Collections.singletonMap(ALIAS_ONE, "aliasPwd1"));
|
||||
Key keyOne = ks.getKey(ALIAS_ONE);
|
||||
assertNotNull(keyOne);
|
||||
}
|
||||
|
||||
public void testAliasWithCorrectPassword_Two() throws Exception
|
||||
{
|
||||
Map<String, String> passwords = new HashMap<String, String>(5);
|
||||
passwords.put(ALIAS_ONE, "aliasPwd1");
|
||||
passwords.put(ALIAS_TWO, "aliasPwd2");
|
||||
KeystoreKeyProvider ks = new KeystoreKeyProvider(
|
||||
FILE_TWO,
|
||||
"SunJCE",
|
||||
"JCEKS",
|
||||
passwords);
|
||||
assertNotNull(ks.getKey(ALIAS_ONE));
|
||||
assertNotNull(ks.getKey(ALIAS_TWO));
|
||||
}
|
||||
|
||||
public void testAliasWithCorrectPassword_Three() throws Exception
|
||||
{
|
||||
Map<String, String> passwords = new HashMap<String, String>(5);
|
||||
passwords.put(ALIAS_ONE, "aliasPwd1");
|
||||
passwords.put(ALIAS_TWO, "aliasPwd2");
|
||||
passwords.put(ALIAS_THREE, "aliasPwd3");
|
||||
KeystoreKeyProvider ks = new KeystoreKeyProvider(
|
||||
FILE_THREE,
|
||||
"SunJCE",
|
||||
"JCEKS",
|
||||
passwords);
|
||||
assertNotNull(ks.getKey(ALIAS_ONE));
|
||||
assertNotNull(ks.getKey(ALIAS_TWO));
|
||||
assertNull(ks.getKey(ALIAS_THREE));
|
||||
}
|
||||
|
||||
/**
|
||||
* TODO: Do we need spring-crypto when it is V1.0?
|
||||
*/
|
||||
public void DISABLED_testSpringCrypto() throws Throwable
|
||||
{
|
||||
ApplicationContext ctx = ApplicationContextHelper.getApplicationContext(
|
||||
new String[] {"alfresco/keystore-tests/encryption-test-context.xml"});
|
||||
@SuppressWarnings("unused")
|
||||
KeyStore ks1 = (KeyStore) ctx.getBean("ks-test-1");
|
||||
}
|
||||
}
|
@@ -1,171 +1,246 @@
|
||||
package org.alfresco.repo.security.encryption;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.security.Key;
|
||||
import java.security.KeyStore;
|
||||
import java.security.KeyStoreException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.cert.CertificateException;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
|
||||
|
||||
import org.alfresco.error.AlfrescoRuntimeException;
|
||||
import org.alfresco.util.ParameterCheck;
|
||||
import org.alfresco.util.PropertyCheck;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.springframework.util.ResourceUtils;
|
||||
|
||||
/**
|
||||
*
|
||||
* Provides the system-wide secret key for symmetric database encryption from a key store
|
||||
* in the filesystem.
|
||||
*
|
||||
* @author Derek Hulley
|
||||
* @since 4.0
|
||||
*/
|
||||
public class KeystoreKeyProvider extends AbstractKeyProvider
|
||||
{
|
||||
public static final String KEY_KEYSTORE_PASSWORD = "keystore";
|
||||
|
||||
private static final Log logger = LogFactory.getLog(KeyProvider.class);
|
||||
|
||||
private static String KEY_STORE_TYPE = "JCEKS";
|
||||
private static String SECRET_KEY_ALIAS = "secret";
|
||||
|
||||
// key store holding the secret key for encrypting and decrypting repository properties
|
||||
private String keyStoreFile;
|
||||
|
||||
// key store passwords
|
||||
private char[] keyStorePassword;
|
||||
private char[] secretKeyPassword;
|
||||
|
||||
public void setKeyStoreFile(String keyStoreFile)
|
||||
{
|
||||
this.keyStoreFile = keyStoreFile;
|
||||
}
|
||||
|
||||
public void setKeyStorePassword(String keyStorePassword)
|
||||
{
|
||||
this.keyStorePassword = keyStorePassword.toCharArray();
|
||||
}
|
||||
// Will be cleared after initialization
|
||||
private Map<String, String> passwords;
|
||||
private String location;
|
||||
private String provider;
|
||||
private String type;
|
||||
private Map<String, Key> keys;
|
||||
|
||||
public void setSecretKeyPassword(String secretKeyPassword)
|
||||
{
|
||||
this.secretKeyPassword = secretKeyPassword.toCharArray();
|
||||
}
|
||||
|
||||
public Key getKey()
|
||||
{
|
||||
return super.getKey();
|
||||
}
|
||||
private final ReadLock readLock;
|
||||
private final WriteLock writeLock;
|
||||
|
||||
protected void saveKeyStore(KeyStore ks) throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException
|
||||
{
|
||||
FileOutputStream fos = null;
|
||||
|
||||
try
|
||||
{
|
||||
fos = new FileOutputStream(keyStoreFile);
|
||||
ks.store(fos, keyStorePassword);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if(fos != null)
|
||||
{
|
||||
fos.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Create a new secret key and store it in the keystore ks
|
||||
/**
|
||||
* Constructs the provider with required defaults
|
||||
*/
|
||||
protected void createSecretKey(KeyStore ks) throws Exception
|
||||
public KeystoreKeyProvider()
|
||||
{
|
||||
Key key = generateSecretKey();
|
||||
if(key == null)
|
||||
{
|
||||
throw new AlfrescoRuntimeException("Unable to generate secret key");
|
||||
}
|
||||
|
||||
byte[] encoded = key.getEncoded();
|
||||
|
||||
logger.debug("secret key size = " + (encoded.length * 8) + " bits");
|
||||
|
||||
KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry((SecretKey)key);
|
||||
|
||||
ks.setEntry(SECRET_KEY_ALIAS, skEntry, new KeyStore.PasswordProtection(secretKeyPassword));
|
||||
|
||||
saveKeyStore(ks);
|
||||
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
|
||||
readLock = lock.readLock();
|
||||
writeLock = lock.writeLock();
|
||||
keys = new HashMap<String, Key>(7);
|
||||
}
|
||||
|
||||
protected void loadKeyStore()
|
||||
/**
|
||||
* Convenience constructor for tests. Note that {@link #init()} is also called.
|
||||
*/
|
||||
/* package */ KeystoreKeyProvider(String location, String provider, String type, Map<String, String> passwords)
|
||||
{
|
||||
InputStream is = null;
|
||||
KeyStore ks = null;
|
||||
|
||||
try
|
||||
{
|
||||
ks = KeyStore.getInstance(KEY_STORE_TYPE);
|
||||
|
||||
File f = new File(keyStoreFile);
|
||||
if(!f.exists())
|
||||
{
|
||||
// no keystore, create one and save it
|
||||
ks.load(null, keyStorePassword);
|
||||
|
||||
// generate a secret key
|
||||
createSecretKey(ks);
|
||||
}
|
||||
else
|
||||
{
|
||||
is = new BufferedInputStream(new FileInputStream(keyStoreFile));
|
||||
ks.load(is, keyStorePassword);
|
||||
}
|
||||
}
|
||||
catch(Throwable e)
|
||||
{
|
||||
throw new AlfrescoRuntimeException(
|
||||
"Unable to load keystore from " + keyStoreFile, e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (is != null)
|
||||
|
||||
{
|
||||
try
|
||||
{
|
||||
is.close();
|
||||
}
|
||||
catch(IOException e)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
this();
|
||||
setLocation(location);
|
||||
setProvider(provider);
|
||||
setType(type);
|
||||
setPasswords(passwords);
|
||||
init();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Key key = ks.getKey(SECRET_KEY_ALIAS, secretKeyPassword);
|
||||
if(key == null)
|
||||
{
|
||||
createSecretKey(ks);
|
||||
}
|
||||
public void setLocation(String location)
|
||||
{
|
||||
this.location = location;
|
||||
}
|
||||
|
||||
setKey(key);
|
||||
}
|
||||
catch(Throwable e)
|
||||
{
|
||||
throw new AlfrescoRuntimeException(
|
||||
"Unable to get secret key from " + keyStoreFile, e);
|
||||
}
|
||||
public void setProvider(String provider)
|
||||
{
|
||||
this.provider = provider;
|
||||
}
|
||||
|
||||
public void setType(String type)
|
||||
{
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the map of passwords to access the keystore.
|
||||
* <p/>
|
||||
* Where required, <tt>null</tt> values must be inserted into the map to indicate the presence
|
||||
* of a key that is not protected by a password. They entry for {@link #KEY_KEYSTORE_PASSWORD}
|
||||
* is required if the keystore is password protected.
|
||||
*
|
||||
* @param passwords a map of passwords including <tt>null</tt> values
|
||||
*/
|
||||
public void setPasswords(Map<String, String> passwords)
|
||||
{
|
||||
this.passwords = new HashMap<String, String>(passwords);
|
||||
}
|
||||
|
||||
public void init()
|
||||
{
|
||||
ParameterCheck.mandatory("keyStoreFile", keyStoreFile);
|
||||
ParameterCheck.mandatory("passwordGenerator", passwordGenerator);
|
||||
writeLock.lock();
|
||||
try
|
||||
{
|
||||
safeInit();
|
||||
}
|
||||
finally
|
||||
{
|
||||
writeLock.unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes class; must be done in a write lock.
|
||||
*/
|
||||
private void safeInit()
|
||||
{
|
||||
if (!PropertyCheck.isValidPropertyString(location))
|
||||
{
|
||||
location = null;
|
||||
}
|
||||
if (!PropertyCheck.isValidPropertyString(provider))
|
||||
{
|
||||
provider = null;
|
||||
}
|
||||
if (!PropertyCheck.isValidPropertyString(type))
|
||||
{
|
||||
type = null;
|
||||
}
|
||||
|
||||
PropertyCheck.mandatory(this, "location", location);
|
||||
// Extract the keystore password
|
||||
String pwdKeyStore = passwords.get(KEY_KEYSTORE_PASSWORD);
|
||||
|
||||
loadKeyStore();
|
||||
// Make sure we choose the default type, if required
|
||||
if (type == null)
|
||||
{
|
||||
type = KeyStore.getDefaultType();
|
||||
}
|
||||
|
||||
KeyStore ks = null;
|
||||
InputStream is = null;
|
||||
try
|
||||
{
|
||||
if (provider == null)
|
||||
{
|
||||
ks = KeyStore.getInstance(type);
|
||||
}
|
||||
else
|
||||
{
|
||||
ks = KeyStore.getInstance(type, provider);
|
||||
}
|
||||
// Load it up
|
||||
File ksFile = ResourceUtils.getFile(location);
|
||||
if (!ksFile.exists())
|
||||
{
|
||||
throw new IOException("Unable to find keystore file: " + ksFile);
|
||||
}
|
||||
is = new FileInputStream(ksFile);
|
||||
ks.load(is, pwdKeyStore == null ? null : pwdKeyStore.toCharArray());
|
||||
// Loaded
|
||||
if (logger.isDebugEnabled())
|
||||
{
|
||||
logger.debug(
|
||||
"Initialize keystore provider: \n" +
|
||||
" Location: " + location + "\n" +
|
||||
" Provider: " + provider + "\n" +
|
||||
" Type: " + type);
|
||||
}
|
||||
}
|
||||
catch (Throwable e)
|
||||
{
|
||||
throw new AlfrescoRuntimeException(
|
||||
"Failed to initialize keystore provider: \n" +
|
||||
" Location: " + location + "\n" +
|
||||
" Provider: " + provider + "\n" +
|
||||
" Type: " + type,
|
||||
e);
|
||||
}
|
||||
finally
|
||||
{
|
||||
pwdKeyStore = null;
|
||||
passwords.remove(KEY_KEYSTORE_PASSWORD);
|
||||
if (is != null)
|
||||
{
|
||||
try { is.close(); } catch (Throwable e) {}
|
||||
}
|
||||
}
|
||||
|
||||
// Now get the other keys
|
||||
for (Map.Entry<String, String> element : passwords.entrySet())
|
||||
{
|
||||
String keyAlias = element.getKey();
|
||||
String passwordStr = element.getValue();
|
||||
if (!PropertyCheck.isValidPropertyString(passwordStr))
|
||||
{
|
||||
// Force a failure because the property was not properly initialized
|
||||
PropertyCheck.mandatory(this, "passwords." + keyAlias, null);
|
||||
}
|
||||
// Null is an acceptable value (means no key)
|
||||
Key key = null;
|
||||
// Attempt to key the key
|
||||
try
|
||||
{
|
||||
key = ks.getKey(keyAlias, passwordStr == null ? null : passwordStr.toCharArray());
|
||||
keys.put(keyAlias, key);
|
||||
// Key loaded
|
||||
if (logger.isDebugEnabled())
|
||||
{
|
||||
logger.debug(
|
||||
"Retrieved key from keystore: \n" +
|
||||
" Location: " + location + "\n" +
|
||||
" Provider: " + provider + "\n" +
|
||||
" Type: " + type + "\n" +
|
||||
" Alias: " + keyAlias + "\n" +
|
||||
" Password?: " + (passwordStr != null));
|
||||
}
|
||||
}
|
||||
catch (Throwable e)
|
||||
{
|
||||
throw new AlfrescoRuntimeException(
|
||||
"Failed to retrieve key from keystore: \n" +
|
||||
" Location: " + location + "\n" +
|
||||
" Provider: " + provider + "\n" +
|
||||
" Type: " + type + "\n" +
|
||||
" Alias: " + keyAlias + "\n" +
|
||||
" Password?: " + (passwordStr != null),
|
||||
e);
|
||||
}
|
||||
}
|
||||
// Clear passwords
|
||||
passwords.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Key getKey(String keyAlias)
|
||||
{
|
||||
readLock.lock();
|
||||
try
|
||||
{
|
||||
return keys.get(keyAlias);
|
||||
}
|
||||
finally
|
||||
{
|
||||
readLock.unlock();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,26 +0,0 @@
|
||||
package org.alfresco.repo.security.encryption;
|
||||
|
||||
import java.security.Key;
|
||||
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.SecretKey;
|
||||
|
||||
import org.alfresco.error.AlfrescoRuntimeException;
|
||||
|
||||
public class TestKeyProvider implements KeyProvider
|
||||
{
|
||||
public Key getKey()
|
||||
{
|
||||
try
|
||||
{
|
||||
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
|
||||
SecretKey key = keyGenerator.generateKey();
|
||||
return key;
|
||||
// return Hex.decode("80000000000000000000000000000000");
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
throw new AlfrescoRuntimeException("Unexpected exception generating secret key", e);
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user