Advertisement
vilgelmbb

ApplyDocumentProtection to WordProcessingDocument

Dec 2nd, 2014
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 9.60 KB | None | 0 0
  1.         public static void ApplyDocumentProtection(WordprocessingDocument wdDocument, string strPassword)
  2.         {
  3.             // Generate the Salt
  4.             byte[] arrSalt = new byte[16];
  5.             RandomNumberGenerator rand = new RNGCryptoServiceProvider();
  6.             rand.GetNonZeroBytes(arrSalt);
  7.  
  8.             //Array to hold Key Values
  9.             byte[] generatedKey = new byte[4];
  10.  
  11.             //Maximum length of the password is 15 chars.
  12.             int intMaxPasswordLength = 15;
  13.  
  14.  
  15.             if (!String.IsNullOrEmpty(strPassword))
  16.             {
  17.                 // Truncate the password to 15 characters
  18.                 strPassword = strPassword.Substring(0, Math.Min(strPassword.Length, intMaxPasswordLength));
  19.  
  20.                 // Construct a new NULL-terminated string consisting of single-byte characters:
  21.                 //  -- > Get the single-byte values by iterating through the Unicode characters of the truncated Password.
  22.                 //   --> For each character, if the low byte is not equal to 0, take it. Otherwise, take the high byte.
  23.  
  24.                 byte[] arrByteChars = new byte[strPassword.Length];
  25.  
  26.                 for (int intLoop = 0; intLoop < strPassword.Length; intLoop++)
  27.                 {
  28.                     int intTemp = Convert.ToInt32(strPassword[intLoop]);
  29.                     arrByteChars[intLoop] = Convert.ToByte(intTemp & 0x00FF);
  30.                     if (arrByteChars[intLoop] == 0)
  31.                         arrByteChars[intLoop] = Convert.ToByte((intTemp & 0xFF00) >> 8);
  32.                 }
  33.  
  34.                 // Compute the high-order word of the new key:
  35.  
  36.                 // --> Initialize from the initial code array (see below), depending on the strPassword’s length.
  37.                 int intHighOrderWord = InitialCodeArray[arrByteChars.Length - 1];
  38.  
  39.                 // --> For each character in the strPassword:
  40.                 //      --> For every bit in the character, starting with the least significant and progressing to (but excluding)
  41.                 //          the most significant, if the bit is set, XOR the key’s high-order word with the corresponding word from
  42.                 //          the Encryption Matrix
  43.  
  44.                 for (int intLoop = 0; intLoop < arrByteChars.Length; intLoop++)
  45.                 {
  46.                     int tmp = intMaxPasswordLength - arrByteChars.Length + intLoop;
  47.                     for (int intBit = 0; intBit < 7; intBit++)
  48.                     {
  49.                         if ((arrByteChars[intLoop] & (0x0001 << intBit)) != 0)
  50.                         {
  51.                             intHighOrderWord ^= EncryptionMatrix[tmp, intBit];
  52.                         }
  53.                     }
  54.                 }
  55.  
  56.                 // Compute the low-order word of the new key:
  57.  
  58.                 // Initialize with 0
  59.                 int intLowOrderWord = 0;
  60.  
  61.                 // For each character in the strPassword, going backwards
  62.                 for (int intLoopChar = arrByteChars.Length - 1; intLoopChar >= 0; intLoopChar--)
  63.                 {
  64.                     // low-order word = (((low-order word SHR 14) AND 0x0001) OR (low-order word SHL 1) AND 0x7FFF)) XOR character
  65.                     intLowOrderWord = (((intLowOrderWord >> 14) & 0x0001) | ((intLowOrderWord << 1) & 0x7FFF)) ^ arrByteChars[intLoopChar];
  66.                 }
  67.  
  68.                 // Lastly,low-order word = (((low-order word SHR 14) AND 0x0001) OR (low-order word SHL 1) AND 0x7FFF)) XOR strPassword length XOR 0xCE4B.
  69.                 intLowOrderWord = (((intLowOrderWord >> 14) & 0x0001) | ((intLowOrderWord << 1) & 0x7FFF)) ^ arrByteChars.Length ^ 0xCE4B;
  70.  
  71.                 // Combine the Low and High Order Word
  72.                 int intCombinedkey = (intHighOrderWord << 16) + intLowOrderWord;
  73.  
  74.                 // The byte order of the result shall be reversed [Example: 0x64CEED7E becomes 7EEDCE64. end example],
  75.                 // and that value shall be hashed as defined by the attribute values.
  76.  
  77.                 for (int intTemp = 0; intTemp < 4; intTemp++)
  78.                 {
  79.                     generatedKey[intTemp] = Convert.ToByte(((uint)(intCombinedkey & (0x000000FF << (intTemp * 8)))) >> (intTemp * 8));
  80.                 }
  81.             }
  82.  
  83.             // Implementation Notes List:
  84.             // --> In this third stage, the reversed byte order legacy hash from the second stage shall be converted to Unicode hex
  85.             // --> string representation
  86.             StringBuilder sb = new StringBuilder();
  87.             for (int intTemp = 0; intTemp < 4; intTemp++)
  88.             {
  89.                 sb.Append(Convert.ToString(generatedKey[intTemp], 16));
  90.             }
  91.             generatedKey = Encoding.Unicode.GetBytes(sb.ToString().ToUpper());
  92.  
  93.             // Implementation Notes List:
  94.             //Word appends the binary form of the salt attribute and not the base64 string representation when hashing
  95.             // Before calculating the initial hash, you are supposed to prepend (not append) the salt to the key
  96.             byte[] tmpArray1 = generatedKey;
  97.             byte[] tmpArray2 = arrSalt;
  98.             byte[] tempKey = new byte[tmpArray1.Length + tmpArray2.Length];
  99.             Buffer.BlockCopy(tmpArray2, 0, tempKey, 0, tmpArray2.Length);
  100.             Buffer.BlockCopy(tmpArray1, 0, tempKey, tmpArray2.Length, tmpArray1.Length);
  101.             generatedKey = tempKey;
  102.  
  103.  
  104.             // Iterations specifies the number of times the hashing function shall be iteratively run (using each
  105.             // iteration's result as the input for the next iteration).
  106.             int iterations = 50000;
  107.  
  108.             // Implementation Notes List:
  109.             //Word requires that the initial hash of the password with the salt not be considered in the count.
  110.             //    The initial hash of salt + key is not included in the iteration count.
  111.             HashAlgorithm sha1 = new SHA1Managed();
  112.             generatedKey = sha1.ComputeHash(generatedKey);
  113.             byte[] iterator = new byte[4];
  114.             for (int intTmp = 0; intTmp < iterations; intTmp++)
  115.             {
  116.  
  117.                 //When iterating on the hash, you are supposed to append the current iteration number.
  118.                 iterator[0] = Convert.ToByte((intTmp & 0x000000FF) >> 0);
  119.                 iterator[1] = Convert.ToByte((intTmp & 0x0000FF00) >> 8);
  120.                 iterator[2] = Convert.ToByte((intTmp & 0x00FF0000) >> 16);
  121.                 iterator[3] = Convert.ToByte((intTmp & 0xFF000000) >> 24);
  122.  
  123.                 generatedKey = concatByteArrays(iterator, generatedKey);
  124.                 generatedKey = sha1.ComputeHash(generatedKey);
  125.             }
  126.  
  127.             // Apply the element
  128.             DocumentProtection documentProtection = new DocumentProtection();
  129.             documentProtection.Edit = DocumentProtectionValues.ReadOnly;
  130.  
  131.             OnOffValue docProtection = new OnOffValue(true);
  132.             documentProtection.Enforcement = docProtection;
  133.  
  134.             documentProtection.CryptographicAlgorithmClass = CryptAlgorithmClassValues.Hash;
  135.             documentProtection.CryptographicProviderType = CryptProviderValues.RsaFull;
  136.             documentProtection.CryptographicAlgorithmType = CryptAlgorithmValues.TypeAny;
  137.             documentProtection.CryptographicAlgorithmSid = 4; // SHA1
  138.             //    The iteration count is unsigned
  139.             UInt32Value uintVal = new UInt32Value();
  140.             uintVal.Value = (uint)iterations;
  141.             documentProtection.CryptographicSpinCount = uintVal;
  142.             documentProtection.Hash = Convert.ToBase64String(generatedKey);
  143.             documentProtection.Salt = Convert.ToBase64String(arrSalt);
  144.             wdDocument.MainDocumentPart.DocumentSettingsPart.Settings.AppendChild(documentProtection);
  145.             wdDocument.MainDocumentPart.DocumentSettingsPart.Settings.Save();
  146.  
  147.         }
  148.  
  149.     static int[] InitialCodeArray = { 0xE1F0, 0x1D0F, 0xCC9C, 0x84C0, 0x110C, 0x0E10, 0xF1CE, 0x313E, 0x1872, 0xE139, 0xD40F, 0x84F9, 0x280C, 0xA96A, 0x4EC3 };
  150.  
  151.         private static int[,] EncryptionMatrix = new int[15, 7]
  152.         {
  153.  
  154.             /* char 1  */ {0xAEFC, 0x4DD9, 0x9BB2, 0x2745, 0x4E8A, 0x9D14, 0x2A09},
  155.             /* char 2  */ {0x7B61, 0xF6C2, 0xFDA5, 0xEB6B, 0xC6F7, 0x9DCF, 0x2BBF},
  156.             /* char 3  */ {0x4563, 0x8AC6, 0x05AD, 0x0B5A, 0x16B4, 0x2D68, 0x5AD0},
  157.             /* char 4  */ {0x0375, 0x06EA, 0x0DD4, 0x1BA8, 0x3750, 0x6EA0, 0xDD40},
  158.             /* char 5  */ {0xD849, 0xA0B3, 0x5147, 0xA28E, 0x553D, 0xAA7A, 0x44D5},
  159.             /* char 6  */ {0x6F45, 0xDE8A, 0xAD35, 0x4A4B, 0x9496, 0x390D, 0x721A},
  160.             /* char 7  */ {0xEB23, 0xC667, 0x9CEF, 0x29FF, 0x53FE, 0xA7FC, 0x5FD9},
  161.             /* char 8  */ {0x47D3, 0x8FA6, 0x0F6D, 0x1EDA, 0x3DB4, 0x7B68, 0xF6D0},
  162.             /* char 9  */ {0xB861, 0x60E3, 0xC1C6, 0x93AD, 0x377B, 0x6EF6, 0xDDEC},
  163.             /* char 10 */ {0x45A0, 0x8B40, 0x06A1, 0x0D42, 0x1A84, 0x3508, 0x6A10},
  164.             /* char 11 */ {0xAA51, 0x4483, 0x8906, 0x022D, 0x045A, 0x08B4, 0x1168},
  165.             /* char 12 */ {0x76B4, 0xED68, 0xCAF1, 0x85C3, 0x1BA7, 0x374E, 0x6E9C},
  166.             /* char 13 */ {0x3730, 0x6E60, 0xDCC0, 0xA9A1, 0x4363, 0x86C6, 0x1DAD},
  167.             /* char 14 */ {0x3331, 0x6662, 0xCCC4, 0x89A9, 0x0373, 0x06E6, 0x0DCC},
  168.             /* char 15 */ {0x1021, 0x2042, 0x4084, 0x8108, 0x1231, 0x2462, 0x48C4}
  169.         };
  170.  
  171.         private static byte[] concatByteArrays(byte[] array1, byte[] array2)
  172.         {
  173.             byte[] result = new byte[array1.Length + array2.Length];
  174.             Buffer.BlockCopy(array2, 0, result, 0, array2.Length);
  175.             Buffer.BlockCopy(array1, 0, result, array2.Length, array1.Length);
  176.             return result;
  177.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement