1package org.bouncycastle.crypto.engines;
2
3import java.security.SecureRandom;
4
5import org.bouncycastle.crypto.CipherParameters;
6import org.bouncycastle.crypto.Digest;
7import org.bouncycastle.crypto.InvalidCipherTextException;
8import org.bouncycastle.crypto.Wrapper;
9import org.bouncycastle.crypto.digests.SHA1Digest;
10import org.bouncycastle.crypto.modes.CBCBlockCipher;
11import org.bouncycastle.crypto.params.KeyParameter;
12import org.bouncycastle.crypto.params.ParametersWithIV;
13
14/**
15 * Wrap keys according to
16 * <A HREF="http://www.ietf.org/internet-drafts/draft-ietf-smime-key-wrap-01.txt">
17 * draft-ietf-smime-key-wrap-01.txt</A>.
18 * <p>
19 * Note:
20 * <ul>
21 * <li>this is based on a draft, and as such is subject to change - don't use this class for anything requiring long term storage.
22 * <li>if you are using this to wrap triple-des keys you need to set the
23 * parity bits on the key and, if it's a two-key triple-des key, pad it
24 * yourself.
25 * </ul>
26 */
27public class DESedeWrapEngine
28    implements Wrapper
29{
30   /** Field engine */
31   private CBCBlockCipher engine;
32
33   /** Field param */
34   private KeyParameter param;
35
36   /** Field paramPlusIV */
37   private ParametersWithIV paramPlusIV;
38
39   /** Field iv */
40   private byte[] iv;
41
42   /** Field forWrapping */
43   private boolean forWrapping;
44
45   /** Field IV2           */
46   private static final byte[] IV2 = { (byte) 0x4a, (byte) 0xdd, (byte) 0xa2,
47                                       (byte) 0x2c, (byte) 0x79, (byte) 0xe8,
48                                       (byte) 0x21, (byte) 0x05 };
49
50    //
51    // checksum digest
52    //
53    Digest  sha1 = new SHA1Digest();
54    byte[]  digest = new byte[20];
55
56   /**
57    * Method init
58    *
59    * @param forWrapping
60    * @param param
61    */
62    public void init(boolean forWrapping, CipherParameters param)
63    {
64
65        this.forWrapping = forWrapping;
66        this.engine = new CBCBlockCipher(new DESedeEngine());
67
68        if (param instanceof KeyParameter)
69        {
70            this.param = (KeyParameter)param;
71
72            if (this.forWrapping)
73            {
74
75                // Hm, we have no IV but we want to wrap ?!?
76                // well, then we have to create our own IV.
77                this.iv = new byte[8];
78
79                SecureRandom sr = new SecureRandom();
80
81                sr.nextBytes(iv);
82
83                this.paramPlusIV = new ParametersWithIV(this.param, this.iv);
84            }
85        }
86        else if (param instanceof ParametersWithIV)
87        {
88            this.paramPlusIV = (ParametersWithIV)param;
89            this.iv = this.paramPlusIV.getIV();
90            this.param = (KeyParameter)this.paramPlusIV.getParameters();
91
92            if (this.forWrapping)
93            {
94                if ((this.iv == null) || (this.iv.length != 8))
95                {
96                    throw new IllegalArgumentException("IV is not 8 octets");
97                }
98            }
99            else
100            {
101                throw new IllegalArgumentException(
102                        "You should not supply an IV for unwrapping");
103            }
104        }
105    }
106
107   /**
108    * Method getAlgorithmName
109    *
110    * @return the algorithm name "DESede".
111    */
112   public String getAlgorithmName()
113   {
114      return "DESede";
115   }
116
117   /**
118    * Method wrap
119    *
120    * @param in
121    * @param inOff
122    * @param inLen
123    * @return the wrapped bytes.
124    */
125   public byte[] wrap(byte[] in, int inOff, int inLen)
126   {
127      if (!forWrapping)
128      {
129         throw new IllegalStateException("Not initialized for wrapping");
130      }
131
132      byte keyToBeWrapped[] = new byte[inLen];
133
134      System.arraycopy(in, inOff, keyToBeWrapped, 0, inLen);
135
136      // Compute the CMS Key Checksum, (section 5.6.1), call this CKS.
137      byte[] CKS = calculateCMSKeyChecksum(keyToBeWrapped);
138
139      // Let WKCKS = WK || CKS where || is concatenation.
140      byte[] WKCKS = new byte[keyToBeWrapped.length + CKS.length];
141
142      System.arraycopy(keyToBeWrapped, 0, WKCKS, 0, keyToBeWrapped.length);
143      System.arraycopy(CKS, 0, WKCKS, keyToBeWrapped.length, CKS.length);
144
145      // Encrypt WKCKS in CBC mode using KEK as the key and IV as the
146      // initialization vector. Call the results TEMP1.
147      byte TEMP1[] = new byte[WKCKS.length];
148
149      System.arraycopy(WKCKS, 0, TEMP1, 0, WKCKS.length);
150
151      int noOfBlocks = WKCKS.length / engine.getBlockSize();
152      int extraBytes = WKCKS.length % engine.getBlockSize();
153
154      if (extraBytes != 0)
155      {
156         throw new IllegalStateException("Not multiple of block length");
157      }
158
159      engine.init(true, paramPlusIV);
160
161      for (int i = 0; i < noOfBlocks; i++)
162      {
163         int currentBytePos = i * engine.getBlockSize();
164
165         engine.processBlock(TEMP1, currentBytePos, TEMP1, currentBytePos);
166      }
167
168      // Left TEMP2 = IV || TEMP1.
169      byte[] TEMP2 = new byte[this.iv.length + TEMP1.length];
170
171      System.arraycopy(this.iv, 0, TEMP2, 0, this.iv.length);
172      System.arraycopy(TEMP1, 0, TEMP2, this.iv.length, TEMP1.length);
173
174      // Reverse the order of the octets in TEMP2 and call the result TEMP3.
175      byte[] TEMP3 = new byte[TEMP2.length];
176
177      for (int i = 0; i < TEMP2.length; i++)
178      {
179         TEMP3[i] = TEMP2[TEMP2.length - (i + 1)];
180      }
181
182      // Encrypt TEMP3 in CBC mode using the KEK and an initialization vector
183      // of 0x 4a dd a2 2c 79 e8 21 05. The resulting cipher text is the desired
184      // result. It is 40 octets long if a 168 bit key is being wrapped.
185      ParametersWithIV param2 = new ParametersWithIV(this.param, IV2);
186
187      this.engine.init(true, param2);
188
189      for (int i = 0; i < noOfBlocks + 1; i++)
190      {
191         int currentBytePos = i * engine.getBlockSize();
192
193         engine.processBlock(TEMP3, currentBytePos, TEMP3, currentBytePos);
194      }
195
196      return TEMP3;
197   }
198
199   /**
200    * Method unwrap
201    *
202    * @param in
203    * @param inOff
204    * @param inLen
205    * @return the unwrapped bytes.
206    * @throws InvalidCipherTextException
207    */
208    public byte[] unwrap(byte[] in, int inOff, int inLen)
209           throws InvalidCipherTextException
210    {
211        if (forWrapping)
212        {
213            throw new IllegalStateException("Not set for unwrapping");
214        }
215
216        if (in == null)
217        {
218            throw new InvalidCipherTextException("Null pointer as ciphertext");
219        }
220
221        if (inLen % engine.getBlockSize() != 0)
222        {
223            throw new InvalidCipherTextException("Ciphertext not multiple of "
224                    + engine.getBlockSize());
225        }
226
227      /*
228      // Check if the length of the cipher text is reasonable given the key
229      // type. It must be 40 bytes for a 168 bit key and either 32, 40, or
230      // 48 bytes for a 128, 192, or 256 bit key. If the length is not supported
231      // or inconsistent with the algorithm for which the key is intended,
232      // return error.
233      //
234      // we do not accept 168 bit keys. it has to be 192 bit.
235      int lengthA = (estimatedKeyLengthInBit / 8) + 16;
236      int lengthB = estimatedKeyLengthInBit % 8;
237
238      if ((lengthA != keyToBeUnwrapped.length) || (lengthB != 0)) {
239         throw new XMLSecurityException("empty");
240      }
241      */
242
243      // Decrypt the cipher text with TRIPLedeS in CBC mode using the KEK
244      // and an initialization vector (IV) of 0x4adda22c79e82105. Call the output TEMP3.
245      ParametersWithIV param2 = new ParametersWithIV(this.param, IV2);
246
247      this.engine.init(false, param2);
248
249      byte TEMP3[] = new byte[inLen];
250
251      System.arraycopy(in, inOff, TEMP3, 0, inLen);
252
253      for (int i = 0; i < (TEMP3.length / engine.getBlockSize()); i++)
254      {
255         int currentBytePos = i * engine.getBlockSize();
256
257         engine.processBlock(TEMP3, currentBytePos, TEMP3, currentBytePos);
258      }
259
260      // Reverse the order of the octets in TEMP3 and call the result TEMP2.
261      byte[] TEMP2 = new byte[TEMP3.length];
262
263      for (int i = 0; i < TEMP3.length; i++)
264      {
265         TEMP2[i] = TEMP3[TEMP3.length - (i + 1)];
266      }
267
268      // Decompose TEMP2 into IV, the first 8 octets, and TEMP1, the remaining octets.
269      this.iv = new byte[8];
270
271      byte[] TEMP1 = new byte[TEMP2.length - 8];
272
273      System.arraycopy(TEMP2, 0, this.iv, 0, 8);
274      System.arraycopy(TEMP2, 8, TEMP1, 0, TEMP2.length - 8);
275
276      // Decrypt TEMP1 using TRIPLedeS in CBC mode using the KEK and the IV
277      // found in the previous step. Call the result WKCKS.
278      this.paramPlusIV = new ParametersWithIV(this.param, this.iv);
279
280      this.engine.init(false, this.paramPlusIV);
281
282      byte[] WKCKS = new byte[TEMP1.length];
283
284      System.arraycopy(TEMP1, 0, WKCKS, 0, TEMP1.length);
285
286      for (int i = 0; i < (WKCKS.length / engine.getBlockSize()); i++)
287      {
288         int currentBytePos = i * engine.getBlockSize();
289
290         engine.processBlock(WKCKS, currentBytePos, WKCKS, currentBytePos);
291      }
292
293      // Decompose WKCKS. CKS is the last 8 octets and WK, the wrapped key, are
294      // those octets before the CKS.
295      byte[] result = new byte[WKCKS.length - 8];
296      byte[] CKStoBeVerified = new byte[8];
297
298      System.arraycopy(WKCKS, 0, result, 0, WKCKS.length - 8);
299      System.arraycopy(WKCKS, WKCKS.length - 8, CKStoBeVerified, 0, 8);
300
301      // Calculate a CMS Key Checksum, (section 5.6.1), over the WK and compare
302      // with the CKS extracted in the above step. If they are not equal, return error.
303      if (!checkCMSKeyChecksum(result, CKStoBeVerified))
304      {
305         throw new InvalidCipherTextException(
306            "Checksum inside ciphertext is corrupted");
307      }
308
309      // WK is the wrapped key, now extracted for use in data decryption.
310      return result;
311   }
312
313    /**
314     * Some key wrap algorithms make use of the Key Checksum defined
315     * in CMS [CMS-Algorithms]. This is used to provide an integrity
316     * check value for the key being wrapped. The algorithm is
317     *
318     * - Compute the 20 octet SHA-1 hash on the key being wrapped.
319     * - Use the first 8 octets of this hash as the checksum value.
320     *
321     * @param key
322     * @return the CMS checksum.
323     * @throws RuntimeException
324     * @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
325     */
326    private byte[] calculateCMSKeyChecksum(
327        byte[] key)
328    {
329        byte[]  result = new byte[8];
330
331        sha1.update(key, 0, key.length);
332        sha1.doFinal(digest, 0);
333
334        System.arraycopy(digest, 0, result, 0, 8);
335
336        return result;
337    }
338
339    /**
340     * @param key
341     * @param checksum
342     * @return true if okay, false otherwise.
343     * @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
344     */
345    private boolean checkCMSKeyChecksum(
346        byte[] key,
347        byte[] checksum)
348    {
349        byte[] calculatedChecksum = calculateCMSKeyChecksum(key);
350
351        if (checksum.length != calculatedChecksum.length)
352        {
353            return false;
354        }
355
356        for (int i = 0; i != checksum.length; i++)
357        {
358            if (checksum[i] != calculatedChecksum[i])
359            {
360                return false;
361            }
362        }
363
364        return true;
365    }
366}
367