SymmetricKeyWrap.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. //
  2. // SymmetricKeyWrap.cs - Implements symmetric key wrap algorithms
  3. //
  4. // Author:
  5. // Tim Coleman ([email protected])
  6. //
  7. // Copyright (C) Tim Coleman, 2004
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System.IO;
  30. using System.Security.Cryptography;
  31. namespace System.Security.Cryptography.Xml {
  32. internal class SymmetricKeyWrap {
  33. public SymmetricKeyWrap ()
  34. {
  35. }
  36. public static byte[] AESKeyWrapEncrypt (byte[] rgbKey, byte[] rgbWrappedKeyData)
  37. {
  38. SymmetricAlgorithm symAlg = SymmetricAlgorithm.Create ("Rijndael");
  39. // Apparently no one felt the need to document that this requires Electronic Codebook mode.
  40. symAlg.Mode = CipherMode.ECB;
  41. // This was also not documented anywhere.
  42. symAlg.IV = new byte [16] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
  43. ICryptoTransform transform = symAlg.CreateEncryptor (rgbKey, symAlg.IV);
  44. int N = rgbWrappedKeyData.Length / 8;
  45. byte[] A;
  46. byte[] B = new Byte [16];
  47. byte [] C = new byte [8 * (N + 1)];
  48. // 1. if N is 1:
  49. // B = AES(K)enc(0xA6A6A6A6A6A6A6A6|P(1))
  50. // C(0) = MSB(B)
  51. // C(1) = LSB(B)
  52. if (N == 1) {
  53. A = new byte [8] {0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6};
  54. transform.TransformBlock (Concatenate (A, rgbWrappedKeyData), 0, 16, B, 0);
  55. Buffer.BlockCopy (MSB(B), 0, C, 0, 8);
  56. Buffer.BlockCopy (LSB(B), 0, C, 8, 8);
  57. } else {
  58. // if N > 1, perform the following steps:
  59. // 2. Initialize variables:
  60. // Set A to 0xA6A6A6A6A6A6A6A6
  61. // For i = 1 to N,
  62. // R(i) = P(i)
  63. A = new byte [8] {0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6, 0xa6};
  64. byte[][] R = new byte [N + 1][];
  65. for (int i = 1; i <= N; i += 1) {
  66. R [i] = new byte [8];
  67. Buffer.BlockCopy (rgbWrappedKeyData, 8 * (i - 1), R [i], 0, 8);
  68. }
  69. // 3. Calculate intermediate values:
  70. // For j = 0 to 5
  71. // For i = 1 to N
  72. // t = i + j * N
  73. // B = AES(K)enc(A|R(i))
  74. // A = XOR(t, MSB(B))
  75. // R(i) = LSB(B)
  76. for (int j = 0; j <= 5; j += 1) {
  77. for (int i = 1; i <= N; i += 1) {
  78. transform.TransformBlock (Concatenate (A, R [i]), 0, 16, B, 0);
  79. // Yawn. It was nice of those at NIST to document how exactly we should XOR
  80. // an integer value with a byte array. Not.
  81. byte[] T = BitConverter.GetBytes ((long) (N * j + i));
  82. // This is nice.
  83. if (BitConverter.IsLittleEndian)
  84. Array.Reverse (T);
  85. A = Xor (T, MSB(B));
  86. R [i] = LSB (B);
  87. }
  88. }
  89. // 4. Output the results:
  90. // Set C(0) = A
  91. // For i = 1 to N
  92. // C(i) = R(i)
  93. Buffer.BlockCopy (A, 0, C, 0, 8);
  94. for (int i = 1; i <= N; i += 1)
  95. Buffer.BlockCopy (R [i], 0, C, 8 * i, 8);
  96. }
  97. return C;
  98. }
  99. public static byte[] AESKeyWrapDecrypt (byte[] rgbKey, byte[] rgbEncryptedWrappedKeyData)
  100. {
  101. SymmetricAlgorithm symAlg = SymmetricAlgorithm.Create ("Rijndael");
  102. symAlg.Mode = CipherMode.ECB;
  103. symAlg.Key = rgbKey;
  104. int N = ( rgbEncryptedWrappedKeyData.Length / 8 ) - 1;
  105. // From RFC 3394 - Advanced Encryption Standard (AES) Key Wrap Algorithm
  106. //
  107. // Inputs: Ciphertext, (n+1) 64-bit values (C0, C1, ..., Cn), and Key, K (the KEK)
  108. // Outputs: Plaintext, n 64-bit values (P1, P2, ..., Pn)
  109. //
  110. // 1. Initialize variables.
  111. // Set A = C[0]
  112. byte[] A = new byte [8];
  113. Buffer.BlockCopy (rgbEncryptedWrappedKeyData, 0, A, 0, 8);
  114. // For i = 1 to n
  115. // R[i] = C[i]
  116. byte[] R = new byte [N * 8];
  117. Buffer.BlockCopy (rgbEncryptedWrappedKeyData, 8, R, 0, rgbEncryptedWrappedKeyData.Length - 8);
  118. // 2. Compute intermediate values.
  119. // For j = 5 to 0
  120. // For i = n to 1
  121. // B = AES-1(K, (A^t) | R[i]) where t = n*j+i
  122. // A = MSB (64,B)
  123. // R[i] = LSB (64,B)
  124. ICryptoTransform transform = symAlg.CreateDecryptor ();
  125. for (int j = 5; j >= 0; j -= 1) {
  126. for (int i = N; i >= 1; i -= 1) {
  127. byte[] T = BitConverter.GetBytes ((long) N * j + i);
  128. if (BitConverter.IsLittleEndian)
  129. Array.Reverse (T);
  130. byte[] B = new Byte [16];
  131. byte[] r = new Byte [8];
  132. Buffer.BlockCopy (R, 8 * (i - 1), r, 0, 8);
  133. byte[] ciphertext = Concatenate (Xor (A, T), r);
  134. transform.TransformBlock (ciphertext, 0, 16, B, 0);
  135. A = MSB (B);
  136. Buffer.BlockCopy (LSB (B), 0, R, 8 * (i - 1), 8);
  137. }
  138. }
  139. // 3. Output results
  140. // If A is an appropriate initial value
  141. // Then
  142. // For i = 1 to n
  143. // P[i] = R[i]
  144. // Else
  145. // Return an error
  146. return R;
  147. }
  148. public static byte[] TripleDESKeyWrapEncrypt (byte[] rgbKey, byte[] rgbWrappedKeyData)
  149. {
  150. SymmetricAlgorithm symAlg = SymmetricAlgorithm.Create ("TripleDES");
  151. // Algorithm from http://www.w3.org/TR/xmlenc-core/#sec-Alg-SymmetricKeyWrap
  152. // The following algorithm wraps (encrypts) a key (the wrapped key, WK) under a TRIPLEDES
  153. // key-encryption-key (KEK) as adopted from [CMS-Algorithms].
  154. // 1. Represent the key being wrapped as an octet sequence. If it is a TRIPLEDES key,
  155. // this is 24 octets (192 bits) with odd parity bit as the bottom bit of each octet.
  156. // rgbWrappedKeyData is the key being wrapped.
  157. // 2. Compute the CMS key checksum (Section 5.6.1) call this CKS.
  158. byte[] cks = ComputeCMSKeyChecksum (rgbWrappedKeyData);
  159. // 3. Let WKCKS = WK || CKS, where || is concatenation.
  160. byte[] wkcks = Concatenate (rgbWrappedKeyData, cks);
  161. // 4. Generate 8 random octets and call this IV.
  162. symAlg.GenerateIV ();
  163. // 5. Encrypt WKCKS in CBC mode using KEK as the key and IV as the initialization vector.
  164. // Call the results TEMP1.
  165. symAlg.Mode = CipherMode.CBC;
  166. symAlg.Padding = PaddingMode.None;
  167. symAlg.Key = rgbKey;
  168. byte[] temp1 = Transform (wkcks, symAlg.CreateEncryptor ());
  169. // 6. Let TEMP2 = IV || TEMP1.
  170. byte[] temp2 = Concatenate (symAlg.IV, temp1);
  171. // 7. Reverse the order of the octets in TEMP2 and call the result TEMP3.
  172. Array.Reverse (temp2); // TEMP3 is TEMP2
  173. // 8. Encrypt TEMP3 in CBC mode using the KEK and an initialization vector of 0x4adda22c79e82105.
  174. // The resulting cipher text is the desired result. It is 40 octets long if a 168 bit key
  175. // is being wrapped.
  176. symAlg.IV = new Byte [8] {0x4a, 0xdd, 0xa2, 0x2c, 0x79, 0xe8, 0x21, 0x05};
  177. byte[] rtnval = Transform (temp2, symAlg.CreateEncryptor ());
  178. return rtnval;
  179. }
  180. public static byte[] TripleDESKeyWrapDecrypt (byte[] rgbKey, byte[] rgbEncryptedWrappedKeyData)
  181. {
  182. SymmetricAlgorithm symAlg = SymmetricAlgorithm.Create ("TripleDES");
  183. // Algorithm from http://www.w3.org/TR/xmlenc-core/#sec-Alg-SymmetricKeyWrap
  184. // The following algorithm unwraps (decrypts) a key as adopted from [CMS-Algorithms].
  185. // 1. Check the length of the cipher text is reasonable given the key type. It must be
  186. // 40 bytes for a 168 bit key and either 32, 40, or 48 bytes for a 128, 192, or 256 bit
  187. // key. If the length is not supported or inconsistent with the algorithm for which the
  188. // key is intended, return error.
  189. // 2. Decrypt the cipher text with TRIPLEDES in CBC mode using the KEK and an initialization
  190. // vector (IV) of 0x4adda22c79e82105. Call the output TEMP3.
  191. symAlg.Mode = CipherMode.CBC;
  192. symAlg.Padding = PaddingMode.None;
  193. symAlg.Key = rgbKey;
  194. symAlg.IV = new Byte [8] {0x4a, 0xdd, 0xa2, 0x2c, 0x79, 0xe8, 0x21, 0x05};
  195. byte[] temp3 = Transform (rgbEncryptedWrappedKeyData, symAlg.CreateDecryptor ());
  196. // 3. Reverse the order of the octets in TEMP3 and call the result TEMP2.
  197. Array.Reverse (temp3); // TEMP2 is TEMP3.
  198. // 4. Decompose TEMP2 into IV, the first 8 octets, and TEMP1, the remaining octets.
  199. byte[] temp1 = new Byte [temp3.Length - 8];
  200. byte[] iv = new Byte [8];
  201. Buffer.BlockCopy (temp3, 0, iv, 0, 8);
  202. Buffer.BlockCopy (temp3, 8, temp1, 0, temp1.Length);
  203. // 5. Decrypt TEMP1 using TRIPLEDES in CBC mode using the KEK and the IV found in the previous step.
  204. // Call the result WKCKS.
  205. symAlg.IV = iv;
  206. byte[] wkcks = Transform (temp1, symAlg.CreateDecryptor ());
  207. // 6. Decompose WKCKS. CKS is the last 8 octets and WK, the wrapped key, are those octets before
  208. // the CKS.
  209. byte[] cks = new byte [8];
  210. byte[] wk = new byte [wkcks.Length - 8];
  211. Buffer.BlockCopy (wkcks, 0, wk, 0, wk.Length);
  212. Buffer.BlockCopy (wkcks, wk.Length, cks, 0, 8);
  213. // 7. Calculate the CMS key checksum over the WK and compare with the CKS extracted in the above
  214. // step. If they are not equal, return error.
  215. // 8. WK is the wrapped key, now extracted for use in data decryption.
  216. return wk;
  217. }
  218. private static byte[] Transform (byte[] data, ICryptoTransform t)
  219. {
  220. MemoryStream output = new MemoryStream ();
  221. CryptoStream crypto = new CryptoStream (output, t, CryptoStreamMode.Write);
  222. crypto.Write (data, 0, data.Length);
  223. crypto.FlushFinalBlock ();
  224. byte[] result = output.ToArray ();
  225. output.Close ();
  226. crypto.Close ();
  227. return result;
  228. }
  229. private static byte[] ComputeCMSKeyChecksum (byte[] data)
  230. {
  231. byte[] hash = HashAlgorithm.Create ("SHA1").ComputeHash (data);
  232. byte[] output = new byte [8];
  233. Buffer.BlockCopy (hash, 0, output, 0, 8);
  234. return output;
  235. }
  236. private static byte[] Concatenate (byte[] buf1, byte[] buf2)
  237. {
  238. byte[] output = new byte [buf1.Length + buf2.Length];
  239. Buffer.BlockCopy (buf1, 0, output, 0, buf1.Length);
  240. Buffer.BlockCopy (buf2, 0, output, buf1.Length, buf2.Length);
  241. return output;
  242. }
  243. private static byte[] MSB (byte[] input)
  244. {
  245. return MSB (input, 8);
  246. }
  247. private static byte[] MSB (byte[] input, int bytes)
  248. {
  249. byte[] output = new byte [bytes];
  250. Buffer.BlockCopy (input, 0, output, 0, bytes);
  251. return output;
  252. }
  253. private static byte[] LSB (byte[] input)
  254. {
  255. return LSB (input, 8);
  256. }
  257. private static byte[] LSB (byte[] input, int bytes)
  258. {
  259. byte[] output = new byte [bytes];
  260. Buffer.BlockCopy (input, bytes, output, 0, bytes);
  261. return output;
  262. }
  263. private static byte[] Xor (byte[] x, byte[] y)
  264. {
  265. // This should *not* happen.
  266. if (x.Length != y.Length)
  267. throw new CryptographicException ("Error performing Xor: arrays different length.");
  268. byte[] output = new byte [x.Length];
  269. for (int i = 0; i < x.Length; i += 1)
  270. output [i] = (byte) (x [i] ^ y [i]);
  271. return output;
  272. }
  273. /* private static byte[] Xor (byte[] x, int n)
  274. {
  275. byte[] output = new Byte [x.Length];
  276. for (int i = 0; i < x.Length; i += 1)
  277. output [i] = (byte) ((int) x [i] ^ n);
  278. return output;
  279. }*/
  280. }
  281. }