Converting Windows Phone 7 ANID to Windows Phone 8 ANID2
Windows Phone 7 has a anonymous user ID property called ANID. Windows Phone 8 replaced that with ANID2. The difference is that ANID2 is dependent on the app's publisher ID. With ANID and ANID2 you can identify your user. This is helpful for example if you want to store some of her app data in a cloud.
The problem
The problem is that if a user upgrades her phone from WP7 to WP8, her ANID changes. Before, her ANID was same in all of her apps. Now, as the publisher ID is part of the ANID2, her ANID2 will be the same in different apps only if the apps are from the same publisher.
The solution
If you use ANID to identify your users, it maybe useful to always convert the ANID to ANID2. This way, even if your user upgrades her phone, you can still identify her. It’s possible to convert from ANID to ANID2. Microsoft has released a C++ sample on how to do the conversion and this post shows the same algorithm in C#, with a big help from SO.
The code
To do the conversion from ANID to ANID2, you have to have your publisher id (GUID). Also, the WP7 ANID must be in “full” format. Some example code on net shows how you take a substring from the ANID and use that as an ID. Don’t do that. You need the whole ANID (in theory, at least).
Here’s the code which does the conversion:
public static string GetAnid2FromAnid(string anid, Guid publisherId) { var anidAsBytes = System.Text.Encoding.Unicode.GetBytes(anid); var publisherAsBytes = publisherId.ToByteArray(); var macObject = new HMACSHA256(anidAsBytes.Take(anidAsBytes.Length / 2).ToArray()); var hashedBytes = macObject.ComputeHash(publisherAsBytes); var result = Convert.ToBase64String(hashedBytes); return result; }