TripleDESKeyWrap.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. /* TripleDESKeyWrap.java -- FIXME: briefly describe file purpose
  2. Copyright (C) 2006 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package gnu.javax.crypto.kwa;
  32. import gnu.java.security.Registry;
  33. import gnu.java.security.hash.Sha160;
  34. import gnu.javax.crypto.assembly.Assembly;
  35. import gnu.javax.crypto.assembly.Cascade;
  36. import gnu.javax.crypto.assembly.Direction;
  37. import gnu.javax.crypto.assembly.Stage;
  38. import gnu.javax.crypto.assembly.Transformer;
  39. import gnu.javax.crypto.assembly.TransformerException;
  40. import gnu.javax.crypto.cipher.IBlockCipher;
  41. import gnu.javax.crypto.cipher.TripleDES;
  42. import gnu.javax.crypto.mode.IMode;
  43. import gnu.javax.crypto.mode.ModeFactory;
  44. import java.security.InvalidKeyException;
  45. import java.security.SecureRandom;
  46. import java.util.Arrays;
  47. import java.util.HashMap;
  48. import java.util.Map;
  49. /**
  50. * The GNU implementation of the Triple DES Key Wrap Algorithm as described in
  51. * [1].
  52. * <p>
  53. * <b>IMPORTANT</b>: This class is NOT thread safe.
  54. * <p>
  55. * References:
  56. * <ol>
  57. * <li><a href="http://www.rfc-archive.org/getrfc.php?rfc=3217">Triple-DES and
  58. * RC2 Key Wrapping</a>.</li>
  59. * <li><a href="http://www.w3.org/TR/xmlenc-core/">XML Encryption Syntax and
  60. * Processing</a>.</li>
  61. * </ol>
  62. */
  63. public class TripleDESKeyWrap
  64. extends BaseKeyWrappingAlgorithm
  65. {
  66. private static final byte[] DEFAULT_IV = new byte[] {
  67. (byte) 0x4A, (byte) 0xDD, (byte) 0xA2, (byte) 0x2C,
  68. (byte) 0x79, (byte) 0xE8, (byte) 0x21, (byte) 0x05 };
  69. private Assembly asm;
  70. private HashMap asmAttributes = new HashMap();
  71. private HashMap modeAttributes = new HashMap();
  72. private Sha160 sha = new Sha160();
  73. private SecureRandom rnd;
  74. public TripleDESKeyWrap()
  75. {
  76. super(Registry.TRIPLEDES_KWA);
  77. }
  78. protected void engineInit(Map attributes) throws InvalidKeyException
  79. {
  80. rnd = (SecureRandom) attributes.get(IKeyWrappingAlgorithm.SOURCE_OF_RANDOMNESS);
  81. IMode des3CBC = ModeFactory.getInstance(Registry.CBC_MODE, new TripleDES(), 8);
  82. Stage des3CBCStage = Stage.getInstance(des3CBC, Direction.FORWARD);
  83. Cascade cascade = new Cascade();
  84. Object modeNdx = cascade.append(des3CBCStage);
  85. asmAttributes.put(modeNdx, modeAttributes);
  86. asm = new Assembly();
  87. asm.addPreTransformer(Transformer.getCascadeTransformer(cascade));
  88. modeAttributes.put(IBlockCipher.KEY_MATERIAL,
  89. attributes.get(KEY_ENCRYPTION_KEY_MATERIAL));
  90. asmAttributes.put(Assembly.DIRECTION, Direction.FORWARD);
  91. }
  92. protected byte[] engineWrap(byte[] in, int inOffset, int length)
  93. {
  94. // The same key wrap algorithm is used for both Two-key Triple-DES and
  95. // Three-key Triple-DES keys. When a Two-key Triple-DES key is to be
  96. // wrapped, a third DES key with the same value as the first DES key is
  97. // created. Thus, all wrapped Triple-DES keys include three DES keys.
  98. if (length != 16 && length != 24)
  99. throw new IllegalArgumentException("Only 2- and 3-key Triple DES keys are alowed");
  100. byte[] CEK = new byte[24];
  101. if (length == 16)
  102. {
  103. System.arraycopy(in, inOffset, CEK, 0, 16);
  104. System.arraycopy(in, inOffset, CEK, 16, 8);
  105. }
  106. else
  107. System.arraycopy(in, inOffset, CEK, 0, 24);
  108. // TODO: check for the following:
  109. // However, a Two-key Triple-DES key MUST NOT be used to wrap a Three-
  110. // key Triple-DES key that is comprised of three unique DES keys.
  111. // 1. Set odd parity for each of the DES key octets comprising the
  112. // Three-Key Triple-DES key that is to be wrapped, call the result
  113. // CEK.
  114. TripleDES.adjustParity(CEK, 0);
  115. // 2. Compute an 8 octet key checksum value on CEK as described above in
  116. // Section 2, call the result ICV.
  117. sha.update(CEK);
  118. byte[] hash = sha.digest();
  119. byte[] ICV = new byte[8];
  120. System.arraycopy(hash, 0, ICV, 0, 8);
  121. // 3. Let CEKICV = CEK || ICV.
  122. byte[] CEKICV = new byte[CEK.length + ICV.length];
  123. System.arraycopy(CEK, 0, CEKICV, 0, CEK.length);
  124. System.arraycopy(ICV, 0, CEKICV, CEK.length, ICV.length);
  125. // 4. Generate 8 octets at random, call the result IV.
  126. byte[] IV = new byte[8];
  127. nextRandomBytes(IV);
  128. // 5. Encrypt CEKICV in CBC mode using the key-encryption key. Use the
  129. // random value generated in the previous step as the initialization
  130. // vector (IV). Call the ciphertext TEMP1.
  131. modeAttributes.put(IMode.IV, IV);
  132. asmAttributes.put(Assembly.DIRECTION, Direction.FORWARD);
  133. byte[] TEMP1;
  134. try
  135. {
  136. asm.init(asmAttributes);
  137. TEMP1 = asm.lastUpdate(CEKICV);
  138. }
  139. catch (TransformerException x)
  140. {
  141. throw new RuntimeException(x);
  142. }
  143. // 6. Let TEMP2 = IV || TEMP1.
  144. byte[] TEMP2 = new byte[IV.length + TEMP1.length];
  145. System.arraycopy(IV, 0, TEMP2, 0, IV.length);
  146. System.arraycopy(TEMP1, 0, TEMP2, IV.length, TEMP1.length);
  147. // 7. Reverse the order of the octets in TEMP2. That is, the most
  148. // significant (first) octet is swapped with the least significant
  149. // (last) octet, and so on. Call the result TEMP3.
  150. byte[] TEMP3 = new byte[TEMP2.length];
  151. for (int i = 0, j = TEMP2.length - 1; i < TEMP2.length; i++, j--)
  152. TEMP3[j] = TEMP2[i];
  153. // 8. Encrypt TEMP3 in CBC mode using the key-encryption key. Use an
  154. // initialization vector (IV) of 0x4adda22c79e82105. The ciphertext
  155. // is 40 octets long.
  156. modeAttributes.put(IMode.IV, DEFAULT_IV);
  157. asmAttributes.put(Assembly.DIRECTION, Direction.FORWARD);
  158. byte[] result;
  159. try
  160. {
  161. asm.init(asmAttributes);
  162. result = asm.lastUpdate(TEMP3);
  163. }
  164. catch (TransformerException x)
  165. {
  166. throw new RuntimeException(x);
  167. }
  168. return result;
  169. }
  170. protected byte[] engineUnwrap(byte[] in, int inOffset, int length)
  171. throws KeyUnwrappingException
  172. {
  173. // 1. If the wrapped key is not 40 octets, then error.
  174. if (length != 40)
  175. throw new IllegalArgumentException("length MUST be 40");
  176. // 2. Decrypt the wrapped key in CBC mode using the key-encryption key.
  177. // Use an initialization vector (IV) of 0x4adda22c79e82105. Call the
  178. // output TEMP3.
  179. modeAttributes.put(IMode.IV, DEFAULT_IV);
  180. asmAttributes.put(Assembly.DIRECTION, Direction.REVERSED);
  181. byte[] TEMP3;
  182. try
  183. {
  184. asm.init(asmAttributes);
  185. TEMP3 = asm.lastUpdate(in, inOffset, 40);
  186. }
  187. catch (TransformerException x)
  188. {
  189. throw new RuntimeException(x);
  190. }
  191. // 3. Reverse the order of the octets in TEMP3. That is, the most
  192. // significant (first) octet is swapped with the least significant
  193. // (last) octet, and so on. Call the result TEMP2.
  194. byte[] TEMP2 = new byte[40];
  195. for (int i = 0, j = 40 - 1; i < 40; i++, j--)
  196. TEMP2[j] = TEMP3[i];
  197. // 4. Decompose TEMP2 into IV and TEMP1. IV is the most significant
  198. // (first) 8 octets, and TEMP1 is the least significant (last) 32
  199. // octets.
  200. byte[] IV = new byte[8];
  201. byte[] TEMP1 = new byte[32];
  202. System.arraycopy(TEMP2, 0, IV, 0, 8);
  203. System.arraycopy(TEMP2, 8, TEMP1, 0, 32);
  204. // 5. Decrypt TEMP1 in CBC mode using the key-encryption key. Use the
  205. // IV value from the previous step as the initialization vector.
  206. // Call the ciphertext CEKICV.
  207. modeAttributes.put(IMode.IV, IV);
  208. asmAttributes.put(Assembly.DIRECTION, Direction.REVERSED);
  209. byte[] CEKICV;
  210. try
  211. {
  212. asm.init(asmAttributes);
  213. CEKICV = asm.lastUpdate(TEMP1, 0, 32);
  214. }
  215. catch (TransformerException x)
  216. {
  217. throw new RuntimeException(x);
  218. }
  219. // 6. Decompose CEKICV into CEK and ICV. CEK is the most significant
  220. // (first) 24 octets, and ICV is the least significant (last) 8
  221. // octets.
  222. byte[] CEK = new byte[24];
  223. byte[] ICV = new byte[8];
  224. System.arraycopy(CEKICV, 0, CEK, 0, 24);
  225. System.arraycopy(CEKICV, 24, ICV, 0, 8);
  226. // 7. Compute an 8 octet key checksum value on CEK as described above in
  227. // Section 2. If the computed key checksum value does not match the
  228. // decrypted key checksum value, ICV, then error.
  229. sha.update(CEK);
  230. byte[] hash = sha.digest();
  231. byte[] computedICV = new byte[8];
  232. System.arraycopy(hash, 0, computedICV, 0, 8);
  233. if (! Arrays.equals(ICV, computedICV))
  234. throw new KeyUnwrappingException("ICV and computed ICV MUST match");
  235. // 8. Check for odd parity each of the DES key octets comprising CEK.
  236. // If parity is incorrect, then error.
  237. if (! TripleDES.isParityAdjusted(CEK, 0))
  238. throw new KeyUnwrappingException("Triple-DES key parity MUST be adjusted");
  239. // 9. Use CEK as a Triple-DES key.
  240. return CEK;
  241. }
  242. /**
  243. * Fills the designated byte array with random data.
  244. *
  245. * @param buffer the byte array to fill with random data.
  246. */
  247. private void nextRandomBytes(byte[] buffer)
  248. {
  249. if (rnd != null)
  250. rnd.nextBytes(buffer);
  251. else
  252. getDefaultPRNG().nextBytes(buffer);
  253. }
  254. }