Skip to content

Instantly share code, notes, and snippets.

@e23z
Created July 26, 2017 14:30
Show Gist options
  • Select an option

  • Save e23z/8ce378e406434fbff781b99e47470f0f to your computer and use it in GitHub Desktop.

Select an option

Save e23z/8ce378e406434fbff781b99e47470f0f to your computer and use it in GitHub Desktop.
[Unique Device ID] How to get an unique device id to use for some purpose in a mobile app. #xamarin #ios #android #wp #mobile
// --------------------------------------
// ANDROID
// --------------------------------------
var id = Android.OS.Build.Serial;
// --------------------------------------
// iOS
// --------------------------------------
/*
* The value of CurrentDevice.IdentifierForVendor changes if the app is removed and reinstalled.
* Therefore some ID (the value of IdentifierForVendor) is stored to the keychain and
* reused every time (even after a reinstall). See http://stackoverflow.com/a/22937460
*/
String id;
String ServiceId = "KeyChainAccountStore";
//use the bundle identifier of the app to identifie the value in the keychain
String appId = NSBundle.MainBundle.InfoDictionary["CFBundleIdentifier"].ToString();
//Try to read the id from the keychain
var rec = new SecRecord(SecKind.GenericPassword)
{
Service = ServiceId,
Account = appId,
};
SecStatusCode res;
var match = SecKeyChain.QueryAsRecord(rec, out res);
//Store a new ID to the keychain
if (match?.Generic == null)
{
//Get the vendor ID (does change after a reinstall of the app)
var vendorId = UIKit.UIDevice.CurrentDevice.IdentifierForVendor.AsString().Replace("-", "");
SecRecord record = new SecRecord(SecKind.GenericPassword)
{
Service = ServiceId,
Account = appId,
Generic = NSData.FromString(vendorId),
Accessible = SecAccessible.Always
};
var statusCode = SecKeyChain.Add(record);
if(statusCode != SecStatusCode.Success)
Debug.WriteLine("Could not save key to KeyChain: " + statusCode);
id = vendorId;
}
else
{ //Use ID from keychain
id = match.Generic.ToString();
}
return id;
// --------------------------------------
// WUP & WINDOWS PHONE 8.1
// --------------------------------------
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
String id = NoDevieIdFound;
try
{
var token = HardwareIdentification.GetPackageSpecificToken(null);
var hardwareId = token.Id;
byte[] bytes = new byte[hardwareId.Length];
using (var dataReader = DataReader.FromBuffer(hardwareId))
dataReader.ReadBytes(bytes);
//create the MD5 hash of the device id to create a shorter id
var alg = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
var hashed = alg.HashData(CryptographicBuffer.CreateFromByteArray(bytes));
id = CryptographicBuffer.EncodeToHexString(hashed);
}
catch (Exception)
{
//ignore
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment