Skip to content

Instantly share code, notes, and snippets.

@rgregg
Last active October 12, 2023 11:54
Show Gist options
  • Save rgregg/c07a91964300315c6c3e77f7b5b861e4 to your computer and use it in GitHub Desktop.
Save rgregg/c07a91964300315c6c3e77f7b5b861e4 to your computer and use it in GitHub Desktop.
Old: Sample code to generate the OneDrive Quick XOR Hash value for a file. The official documentation for the QuickXorHash is available here: https://learn.microsoft.com/en-us/onedrive/developer/code-snippets/quickxorhash?view=odsp-graph-online
// ------------------------------------------------------------------------------
// Copyright (c) 2016 Microsoft Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ------------------------------------------------------------------------------
namespace OneDrive
{
using System;
/// <summary>
/// A quick, simple non-cryptographic hash algorithm that works by XORing the bytes in a circular-shifting fashion.
///
/// A high level description of the algorithm without the introduction of the length is as follows:
///
/// Let's say a "block" is a 160 bit block of bits (e.g. byte[20]).
///
/// method block zero():
/// returns a block with all zero bits.
///
/// method block extend8(byte b):
/// returns a block with all zero bits except for the lower 8 bits which come from b.
///
/// method block extend64(int64 i):
/// returns a block of all zero bits except for the lower 64 bits which come from i.
///
/// method block rotate(block bl, int n):
/// returns bl rotated left by n bits.
///
/// method block xor(block bl1, block bl2):
/// returns a bitwise xor of bl1 with bl2
///
/// method block XorHash0(byte rgb[], int cb):
/// block ret = zero()
/// for (int i = 0; i < cb; i ++)
/// ret = xor(ret, rotate(extend8(rgb[i]), i * 11))
/// returns ret
///
/// entrypoint block XorHash(byte rgb[], int cb):
/// returns xor(extend64(cb), XorHash0(rgb, cb))
///
/// The final hash should xor the length of the data with the least significant bits of the resulting block.
/// </summary>
public class QuickXorHash : System.Security.Cryptography.HashAlgorithm
{
private const int BitsInLastCell = 32;
private const byte Shift = 11;
private const int Threshold = 600;
private const byte WidthInBits = 160;
private UInt64[] _data;
private Int64 _lengthSoFar;
private int _shiftSoFar;
public QuickXorHash()
{
this.Initialize();
}
protected override void HashCore(byte[] array, int ibStart, int cbSize)
{
unchecked
{
int currentShift = this._shiftSoFar;
// The bitvector where we'll start xoring
int vectorArrayIndex = currentShift / 64;
// The position within the bit vector at which we begin xoring
int vectorOffset = currentShift % 64;
int iterations = Math.Min(cbSize, QuickXorHash.WidthInBits);
for (int i = 0; i < iterations; i++)
{
bool isLastCell = vectorArrayIndex == this._data.Length - 1;
int bitsInVectorCell = isLastCell ? QuickXorHash.BitsInLastCell : 64;
// There's at least 2 bitvectors before we reach the end of the array
if (vectorOffset <= bitsInVectorCell - 8)
{
for (int j = ibStart + i; j < cbSize + ibStart; j += QuickXorHash.WidthInBits)
{
this._data[vectorArrayIndex] ^= (ulong)array[j] << vectorOffset;
}
}
else
{
int index1 = vectorArrayIndex;
int index2 = isLastCell ? 0 : (vectorArrayIndex + 1);
byte low = (byte)(bitsInVectorCell - vectorOffset);
byte xoredByte = 0;
for (int j = ibStart + i; j < cbSize + ibStart; j += QuickXorHash.WidthInBits)
{
xoredByte ^= array[j];
}
this._data[index1] ^= (ulong)xoredByte << vectorOffset;
this._data[index2] ^= (ulong)xoredByte >> low;
}
vectorOffset += QuickXorHash.Shift;
while (vectorOffset >= bitsInVectorCell)
{
vectorArrayIndex = isLastCell ? 0 : vectorArrayIndex + 1;
vectorOffset -= bitsInVectorCell;
}
}
// Update the starting position in a circular shift pattern
this._shiftSoFar = (this._shiftSoFar + QuickXorHash.Shift * (cbSize % QuickXorHash.WidthInBits)) % QuickXorHash.WidthInBits;
}
this._lengthSoFar += cbSize;
}
protected override byte[] HashFinal()
{
// Create a byte array big enough to hold all our data
byte[] rgb = new byte[(QuickXorHash.WidthInBits - 1) / 8 + 1];
// Block copy all our bitvectors to this byte array
for (Int32 i = 0; i < this._data.Length - 1; i++)
{
Buffer.BlockCopy(
BitConverter.GetBytes(this._data[i]), 0,
rgb, i * 8,
8);
}
Buffer.BlockCopy(
BitConverter.GetBytes(this._data[this._data.Length - 1]), 0,
rgb, (this._data.Length - 1) * 8,
rgb.Length - (this._data.Length - 1) * 8);
// XOR the file length with the least significant bits
// Note that GetBytes is architecture-dependent, so care should
// be taken with porting. The expected value is 8-bytes in length in little-endian format
var lengthBytes = BitConverter.GetBytes(this._lengthSoFar);
System.Diagnostics.Debug.Assert(lengthBytes.Length == 8);
for (int i = 0; i < lengthBytes.Length; i++)
{
rgb[(QuickXorHash.WidthInBits / 8) - lengthBytes.Length + i] ^= lengthBytes[i];
}
return rgb;
}
public override sealed void Initialize()
{
this._data = new ulong[(QuickXorHash.WidthInBits - 1) / 64 + 1];
this._shiftSoFar = 0;
this._lengthSoFar = 0;
}
public override int HashSize
{
get
{
return QuickXorHash.WidthInBits;
}
}
}
}
@dtheodor
Copy link

Can you qualify the names byte[] array, int ibStart, int cbSize, byte rgb[], int cb that you use in your pseudocode and in the implementation? What do they stand for?

@buzzluck68
Copy link

I added this code to a hash tool I created, but when I compare the QuickXorHash value for a file that exists on my local machine as well as my OneDrive for Business, the values are different. I was hoping to use this as a quick way to verify the files are still identical between local drives and OneDrive (since this is the only hash value available for OneDrive for Business accounts). Any ideas on why the values for the exact same file would be different?

QuickXorHash code sample result:
test_quickxorhash_sample_result

OneDrive Graph API result:
microsoft_graph_hash_quickxor_result

@buzzluck68
Copy link

I found the issue, and it was in the way I was converting the byte array to a string.
Here is the code I was using originally:

int i;
StringBuilder outPut = new StringBuilder(byteArray.Length);
for (i = 0; i < byteArray.Length; i++)
{
     outPut.Append(byteArray[i].ToString("x2"));
}
return outPut.ToString();

But, after some more research, here is what I found that worked correctly, and is also cleaner:
return Convert.ToBase64String(byteArray);

This results in the hash now matching what OneDrive returns.

@moander
Copy link

moander commented Jun 28, 2023

It took me a few hours to figure out that Sharepoint give you a unexpected XOR if you upload the file with .msg extension....

@vikram9491
Copy link

@buzzluck68
byte[] byteArray = { 48, 49, 86, 50, 75, 85, 89, 82, 70, 81 ,72, 53, 72 ,69, 86, 52, 82, 85, 84 ,82, 66, 73, 87, 87 ,79 ,76 ,84, 73, 50 ,83, 78, 83, 81, 80 };
int i;
StringBuilder outPut = new StringBuilder(byteArray.Length);
for (i = 0; i < byteArray.Length; i++)
{
outPut.Append(byteArray[i].ToString("x2"));
}
var base64encoded = Convert.ToBase64String(byteArray);
Console.WriteLine(base64encoded); but for me result is not matching what OneDrive returns.

@moander
Copy link

moander commented Oct 12, 2023

but for me result is not matching what OneDrive returns.

@vikram9491 what kind if file are you uploading? OneDrive rewrite some uploaded files and therefor the xor is also changed (apparently)

@vikram9491
Copy link

@moander Actually I need to find deduplication files i am using .docx file , for that i need to create quickxorhash , but when i try ike above is not matching what OneDrive api returns.

@vikram9491
Copy link

vikram9491 commented Oct 12, 2023

@moander I tried like this to still i am not able to create quickxorhash value
byte[] hashArray = { 48, 49, 86, 50, 75, 85, 89, 82, 70, 81 ,72, 53, 72 ,69, 86, 52, 82, 85, 84 ,82, 66, 73, 87, 87 ,79 ,76 ,84, 73, 50 ,83, 78, 83, 81, 80 };
quickXorHash.HashCore(hashArray,0,hashArray.Length);
var hashValue = quickXorHash.HashFinal();

    Console.WriteLine("OneDrive QuickXorHash Value:");
    foreach (var b in hashValue)
    {
        Console.Write(b + " ");
	}
   // Convert the hash value to Base64 string
    string base64Hash = Convert.ToBase64String(hashValue);
    Console.WriteLine("\nBase64 Hash Value: " + base64Hash);

In addition to that suppose if my bitsinlastcell input has 272 bit and output has widthinbits has 242 bit then what is shift and threshold value i should give ......?
in this line what hashlength i should pass...? quickXorHash.HashCore(hashArray,0,hashArray.Length);

@moander
Copy link

moander commented Oct 12, 2023

@vikram9491 let me know if you figure it out. I concluded that it is not possible. The calculated xor is correct but the .docx or .eml file is modified so it's impossible for you to calculate the correct xor beforehand 👎

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment