01: /*
02: * Implementation of TripleDES algorithm, modified
03: * the source code to suite our requirements
04: *
05: * @ source cryptix
06: * @ created 13-12-2001
07: * @ Author Rajesh T
08: */
09:
10: package com.sun.portal.kssl;
11:
12: import com.sun.portal.ksecurity.Key;
13: import com.sun.portal.ksecurity.SecretKey;
14: import com.sun.portal.ksecurity.KeyBuilder;
15: import com.sun.portal.ksecurity.CryptoException;
16:
17: public final class TripleDES extends BlockCipher {
18:
19: private byte type;
20:
21: private static final int KEY_LENGTH = 24, DES_KEY_LENGTH = 64;
22:
23: private DES des1, des2, des3;
24:
25: public TripleDES() {
26: des1 = new DES();
27: des2 = new DES();
28: des3 = new DES();
29: type = Cipher.ALG_TRIPLEDES;
30: BLOCK_SIZE = 8;
31: }
32:
33: public byte getAlgorithm() {
34: return Cipher.ALG_TRIPLEDES;
35: }
36:
37: public void init(Key theKey, byte theMode) throws CryptoException {
38: if ((theKey.getType() != KeyBuilder.TYPE_TRIPLEDES)
39: || ((theMode != Cipher.MODE_ENCRYPT) && (theMode != Cipher.MODE_DECRYPT))) {
40: throw new CryptoException(CryptoException.ILLEGAL_VALUE);
41: }
42:
43: mode = theMode;
44: byte[] k = new byte[8];
45: byte[] userKey = new byte[(theKey.getSize() + 7) >>> 3];
46: ((SecretKey) theKey).getKey(userKey, (short) 0);
47:
48: System.arraycopy(userKey, 0, k, 0, 8);
49: SecretKey key1 = (SecretKey) KeyBuilder.buildKey(
50: KeyBuilder.TYPE_DES, (short) (8 << 3), false);
51: key1.setKey(k, (short) 0);
52: des1.init(key1, theMode);
53:
54: System.arraycopy(userKey, 8, k, 0, 8);
55: SecretKey key2 = (SecretKey) KeyBuilder.buildKey(
56: KeyBuilder.TYPE_DES, (short) (8 << 3), false);
57:
58: key2.setKey(k, (short) 0);
59: if (theMode == Cipher.MODE_ENCRYPT)
60: des2.init(key2, Cipher.MODE_DECRYPT);
61: else
62: des2.init(key2, Cipher.MODE_ENCRYPT);
63:
64: System.arraycopy(userKey, 16, k, 0, 8);
65: SecretKey key3 = (SecretKey) KeyBuilder.buildKey(
66: KeyBuilder.TYPE_DES, (short) (8 << 3), false);
67: key3.setKey(k, (short) 0);
68: des3.init(key3, theMode);
69:
70: if (theMode == Cipher.MODE_DECRYPT) {
71: DES des = des1;
72: des1 = des3;
73: des3 = des;
74: }
75:
76: }
77:
78: protected void coreCrypt(byte[] in, int inOffset, byte[] out,
79: int outOffset) {
80: des1.coreCrypt(in, inOffset, out, outOffset);
81: des2.coreCrypt(out, outOffset, out, outOffset);
82: des3.coreCrypt(out, outOffset, out, outOffset);
83: }
84:
85: }
|