JCOSecretKey.java
00001 package edu.virtualschool.jco;
00002
00003 import java.security.SecureRandom;
00004
00005 import org.bouncycastle.crypto.engines.RC4Engine;
00006 import org.bouncycastle.crypto.params.KeyParameter;
00007
00008 import edu.virtualschool.jwaa.RuntimeFault;
00009
00026 public class JCOSecretKey extends JCOSymmetricKey
00027 {
00029 final static int DEFAULT_KEY_LENGTH = 128/8;
00030 final static int MINIMUM_KEY_LENGTH = 40/8;
00031 final static int MAXIMUM_KEY_LENGTH = 2048/8;
00032
00037 public JCOSecretKey()
00038 {
00039 super(makeKeyParameter(DEFAULT_KEY_LENGTH));
00040 }
00046 public JCOSecretKey(int keyLengthInBytes) throws RuntimeFault
00047 {
00048 super(makeKeyParameter(keyLengthInBytes));
00049 }
00050 final static KeyParameter makeKeyParameter(int keyLengthInBytes)
00051 throws RuntimeFault
00052 {
00053 if (keyLengthInBytes < MINIMUM_KEY_LENGTH || keyLengthInBytes > MAXIMUM_KEY_LENGTH)
00054 throw new RuntimeFault("keylength " + keyLengthInBytes+ " must be "+MINIMUM_KEY_LENGTH+" to "+MAXIMUM_KEY_LENGTH+" bytes");
00055 SecureRandom random = new SecureRandom();
00056 byte[] randomBytes = new byte[keyLengthInBytes];
00057 random.nextBytes(randomBytes);
00058 return new KeyParameter(randomBytes);
00059 }
00069 public JCOSecretKey(String string)
00070 {
00071 this(JCOBase64.decode(string));
00072 }
00078 public JCOSecretKey(byte[] bytes)
00079 {
00080 super(new KeyParameter(bytes));
00081 }
00085 public final byte[] decryptBytes(byte[] inputBytes)
00086 {
00087 RC4Engine engine = new RC4Engine();
00088 engine.init(true, key);
00089 byte[] outputBytes = new byte[inputBytes.length];
00090 engine.processBytes(inputBytes, 0, inputBytes.length, outputBytes, 0);
00091 return outputBytes;
00092 }
00096 public final byte[] encryptBytes(byte[] inputBytes)
00097 {
00098 return decryptBytes(inputBytes);
00099 }
00103 public final String getAlgorithm()
00104 {
00105 return "RC4";
00106 }
00111 public final String getFormat()
00112 {
00113 return "RAW";
00114 }
00115 }