01: /*
02: * $Id: SecretKeyEncryptionStrategy.java 10976 2008-02-25 09:20:41Z holger $
03: * --------------------------------------------------------------------------------------
04: * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
05: *
06: * The software in this package is published under the terms of the CPAL v1.0
07: * license, a copy of which has been included with this distribution in the
08: * LICENSE.txt file.
09: */
10:
11: package org.mule.security;
12:
13: import org.mule.api.lifecycle.InitialisationException;
14: import org.mule.api.lifecycle.LifecycleTransitionResult;
15: import org.mule.config.i18n.CoreMessages;
16: import org.mule.util.StringMessageUtils;
17:
18: import java.security.GeneralSecurityException;
19: import java.security.spec.AlgorithmParameterSpec;
20: import java.security.spec.KeySpec;
21:
22: import javax.crypto.KeyGenerator;
23: import javax.crypto.SecretKey;
24: import javax.crypto.spec.SecretKeySpec;
25:
26: /**
27: * SecretKey based encryption using JCE. Users must specify a key as an array of
28: * bytes. This can be set directly on the strategy or a keyFactory can be specified.
29: * A keyFactory is an implementation of {@link SecretKeyFactory} and must return a
30: * byte array. The default algorthm used by this strategy is Blowfish, but users can
31: * specify any valid algorithm supported by JCE.
32: *
33: * @see SecretKeyFactory
34: */
35: public class SecretKeyEncryptionStrategy extends
36: AbstractJCEEncryptionStrategy {
37:
38: public static final String DEFAULT_ALGORITHM = "Blowfish";
39:
40: private byte[] key;
41: private SecretKeyFactory keyFactory;
42:
43: public SecretKeyEncryptionStrategy() {
44: algorithm = DEFAULT_ALGORITHM;
45: }
46:
47: public LifecycleTransitionResult initialise()
48: throws InitialisationException {
49: if (key == null) {
50: if (keyFactory == null) {
51: throw new InitialisationException(CoreMessages
52: .objectIsNull("Key / KeyFactory"), this );
53: } else {
54: try {
55: key = keyFactory.getKey();
56: } catch (Exception e) {
57: throw new InitialisationException(e, this );
58: }
59: }
60: }
61: return super .initialise();
62: }
63:
64: protected KeySpec createKeySpec() {
65: return new SecretKeySpec(key, algorithm);
66: }
67:
68: protected AlgorithmParameterSpec createAlgorithmParameterSpec() {
69: return null;
70: }
71:
72: public void setKey(byte[] rawKey) {
73: this .key = rawKey;
74: }
75:
76: public void setKey(String rawKey) {
77: this .key = StringMessageUtils.getBytes(rawKey);
78: }
79:
80: public SecretKeyFactory getKeyFactory() {
81: return keyFactory;
82: }
83:
84: public void setKeyFactory(SecretKeyFactory keyFactory) {
85: this .keyFactory = keyFactory;
86: }
87:
88: protected SecretKey getSecretKey() throws GeneralSecurityException {
89: return KeyGenerator.getInstance(algorithm).generateKey();
90: }
91:
92: }
|