/* 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.security; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import android.util.Log; import com.swisscom.safeconnect.BuildConfig; import com.swisscom.safeconnect.utils.Config; public class Token { private static String bytesToHex(byte[] a) { StringBuilder sb = new StringBuilder(); for(byte b: a) sb.append(String.format("%02x", b&0xff)); return sb.toString(); } /** * will generate a token for the specified data * @param data data to be sent * @return token that the server will check to prove the validity of the data */ public static String generateToken(String phoneNumber, String data) { if (data == null) throw new NullPointerException("data cannot be null"); String preKey = ""; byte[] key = hash(preKey); Encryptor enc = new Encryptor(key, hash(data)); long timestamp = System.currentTimeMillis(); try { return URLEncoder.encode(enc.encrypt(String.valueOf(timestamp)), "UTF-8"); } catch (UnsupportedEncodingException e) { if (BuildConfig.DEBUG) Log.e(Config.TAG, "encoding error", e); return ""; } } public static byte[] hash(String data) { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { if (BuildConfig.DEBUG) Log.e(Config.TAG, "digest error ", e); } if (digest != null) { digest.update(data.getBytes()); return digest.digest(); } return new byte[32]; } }