/*
Swisscom Safe Connect
Copyright (C) 2014 Swisscom
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.swisscom.safeconnect.utils;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Created by vadim on 19.08.14.
*/
public class DeviceIdProvider {
private static String deviceId = "";
final protected static char[] hexArray = "0123456789abcdef".toCharArray();
private static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public static String init(Context context) {
String[] params = { "android_id" };
Cursor c = context.getContentResolver()
.query(Uri.parse("content://com.google.android.gsf.gservices"), null, null,
params, null);
// this happens when no google apps are present on the device
if (c == null) {
throw new IllegalStateException("Cannot retrieve android id");
}
if (!c.moveToFirst() || c.getColumnCount() < 2) {
throw new IllegalStateException("Cannot retrieve android id");
}
try {
deviceId = Long.toHexString(Long.parseLong(c.getString(1)));
} catch (NumberFormatException e) {
throw new IllegalStateException("Cannot retrieve android id");
}
c.close();
// hash the value to get the key
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(deviceId.getBytes());
deviceId = bytesToHex(messageDigest.digest());
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Cannot retrieve android id");
}
return deviceId;
}
public static String getDeviceId() {
return deviceId;
}
}