entries;
+ private EntriesAdapter adapter;
+
+ private Entry nextSelection = null;
+ private void showNoAccount(){
+ Snackbar noAccountSnackbar = Snackbar.make(findViewById(R.id.listView), R.string.no_accounts, Snackbar.LENGTH_INDEFINITE)
+ .setAction("Add", new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ scanQRCode();
+ }
+ });
+ noAccountSnackbar.show();
+ }
+
+ private void scanQRCode(){
+ new IntentIntegrator(MainActivity.this)
+ .setCaptureActivity(CaptureActivityAnyOrientation.class)
+ .setOrientationLocked(false)
+ .initiateScan();
+ }
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setTitle(R.string.app_name);
+ getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
+ setContentView(R.layout.activity_main);
+ Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
+ setSupportActionBar(toolbar);
+
+ final ListView listView = (ListView) findViewById(R.id.listView);
+ final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
+
+ entries = SettingsHelper.load(this);
+
+ adapter = new EntriesAdapter();
+ adapter.setEntries(entries);
+
+ listView.setAdapter(adapter);
+
+ listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
+ @Override
+ public boolean onItemLongClick(AdapterView> adapterView, View view, int i, long l) {
+ nextSelection = entries.get(i);
+ startActionMode(MainActivity.this);
+
+ return true;
+ }
+ });
+
+ if(entries.isEmpty()){
+ showNoAccount();
+ }
+
+ int progress = ((int) (System.currentTimeMillis() / 1000) % 30);
+ progressBar.setProgress((int) (1000.0 * progress / 30.0));
+
+ ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress", 1000);
+ animation.setDuration((30 - progress) * 1000);
+ animation.setInterpolator(new LinearInterpolator());
+ animation.start();
+
+
+ final Handler handler = new Handler();
+ final Runnable handlerTask = new Runnable()
+ {
+ @Override
+ public void run() {
+ int progress = (int) (System.currentTimeMillis() / 1000) % 30 ;
+
+ if(progress == 0){
+ progressBar.setProgress(progress);
+
+ ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress", 1000);
+ animation.setDuration(30 * 1000);
+ animation.setInterpolator(new LinearInterpolator());
+ animation.start();
+ }
+
+ for(int i =0;i< adapter.getCount();i++){
+ if(progress == 0 || adapter.getItem(i).getCurrentOTP() == null){
+ adapter.getItem(i).setCurrentOTP(TOTPHelper.generate(adapter.getItem(i).getSecret()));
+ }
+ }
+ adapter.notifyDataSetChanged();
+
+ handler.postDelayed(this, 1000);
+ }
+ };
+ handlerTask.run();
+ }
+
+ @Override
+ protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
+ super.onActivityResult(requestCode, resultCode, intent);
+
+ if (requestCode == IntentIntegrator.REQUEST_CODE && resultCode == Activity.RESULT_OK) {
+ try {
+ Entry e = new Entry(intent.getStringExtra(Intents.Scan.RESULT));
+ e.setCurrentOTP(TOTPHelper.generate(e.getSecret()));
+ entries.add(e);
+ SettingsHelper.store(this, entries);
+
+ adapter.notifyDataSetChanged();
+
+ Snackbar.make(findViewById(R.id.listView), "Account added", Snackbar.LENGTH_LONG).show();
+ } catch (Exception e) {
+ Snackbar.make(findViewById(R.id.listView), "Invalid QR Code", Snackbar.LENGTH_LONG).setCallback(new Snackbar.Callback() {
+ @Override
+ public void onDismissed(Snackbar snackbar, int event) {
+ super.onDismissed(snackbar, event);
+
+ if(entries.isEmpty()){
+ showNoAccount();
+ }
+ }
+ }).show();
+
+ return;
+ }
+ }
+
+ if(entries.isEmpty()){
+ showNoAccount();
+ }
+ }
+
+ @Override
+ public boolean onCreateOptionsMenu(Menu menu) {
+ getMenuInflater().inflate(R.menu.menu_main, menu);
+ return true;
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ int id = item.getItemId();
+
+ if (id == R.id.action_scan) {
+ scanQRCode();
+
+ return true;
+ } else if(id == R.id.action_about){
+ WebView view = (WebView) LayoutInflater.from(this).inflate(R.layout.dialog_about, null);
+ view.loadUrl("file:///android_res/raw/about.html");
+ new AlertDialog.Builder(this).setView(view).show();
+
+ return true;
+ }
+
+ return super.onOptionsItemSelected(item);
+ }
+
+ @Override
+ public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
+ MenuInflater inflater = actionMode.getMenuInflater();
+ inflater.inflate(R.menu.menu_edit, menu);
+
+ return true;
+ }
+
+ @Override
+ public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
+ adapter.setCurrentSelection(nextSelection);
+ adapter.notifyDataSetChanged();
+ actionMode.setTitle(adapter.getCurrentSelection().getLabel());
+
+ return true;
+ }
+
+ @Override
+ public boolean onActionItemClicked(final ActionMode actionMode, MenuItem menuItem) {
+ int id = menuItem.getItemId();
+
+ if (id == R.id.action_delete) {
+ AlertDialog.Builder alert = new AlertDialog.Builder(this);
+ alert.setTitle("Remove " + adapter.getCurrentSelection().getLabel() + "?");
+ alert.setMessage("Are you sure you want do remove this account?");
+
+ alert.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int whichButton) {
+ entries.remove(adapter.getCurrentSelection());
+
+ Snackbar.make(findViewById(R.id.listView), "Account removed", Snackbar.LENGTH_LONG).setCallback(new Snackbar.Callback() {
+ @Override
+ public void onDismissed(Snackbar snackbar, int event) {
+ super.onDismissed(snackbar, event);
+
+ if (entries.isEmpty()) {
+ showNoAccount();
+ }
+ }
+ }).show();
+
+ actionMode.finish();
+ }
+ });
+
+ alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int whichButton) {
+ dialog.cancel();
+ actionMode.finish();
+ }
+ });
+
+ alert.show();
+
+ return true;
+ }
+ else if (id == R.id.action_edit) {
+ AlertDialog.Builder alert = new AlertDialog.Builder(this);
+ alert.setTitle("Rename");
+
+ final EditText input = new EditText(this);
+ input.setText(adapter.getCurrentSelection().getLabel());
+ alert.setView(input);
+
+ alert.setPositiveButton("Save", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int whichButton) {
+ adapter.getCurrentSelection().setLabel(input.getEditableText().toString());
+ actionMode.finish();
+ }
+ });
+
+ alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
+ public void onClick(DialogInterface dialog, int whichButton) {
+ dialog.cancel();
+ actionMode.finish();
+ }
+ });
+
+ alert.show();
+
+ return true;
+ }
+
+ return false;
+ }
+
+ @Override
+ public void onDestroyActionMode(ActionMode actionMode) {
+ adapter.setCurrentSelection(null);
+ adapter.notifyDataSetChanged();
+
+ SettingsHelper.store(this, entries);
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/net/bierbaumer/otp_authenticator/SecretKeyWrapper.java b/app/src/main/java/net/bierbaumer/otp_authenticator/SecretKeyWrapper.java
new file mode 100644
index 00000000..0a322c4d
--- /dev/null
+++ b/app/src/main/java/net/bierbaumer/otp_authenticator/SecretKeyWrapper.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.bierbaumer.otp_authenticator;
+
+import android.annotation.TargetApi;
+import android.content.Context;
+import android.os.Build;
+import android.security.KeyPairGeneratorSpec;
+
+import java.io.IOException;
+import java.math.BigInteger;
+import java.security.GeneralSecurityException;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.KeyStore;
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+
+import javax.crypto.Cipher;
+import javax.crypto.SecretKey;
+import javax.security.auth.x500.X500Principal;
+
+/**
+ * Wraps {@link SecretKey} instances using a public/private key pair stored in
+ * the platform {@link KeyStore}. This allows us to protect symmetric keys with
+ * hardware-backed crypto, if provided by the device.
+ *
+ * See key wrapping for more
+ * details.
+ *
+ * Not inherently thread safe.
+ */
+public class SecretKeyWrapper {
+ private final Cipher mCipher;
+ private final KeyPair mPair;
+
+ /**
+ * Create a wrapper using the public/private key pair with the given alias.
+ * If no pair with that alias exists, it will be generated.
+ */
+ public SecretKeyWrapper(Context context, String alias)
+ throws GeneralSecurityException, IOException {
+ mCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
+
+ final KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
+ keyStore.load(null);
+
+ if (!keyStore.containsAlias(alias)) {
+ generateKeyPair(context, alias);
+ }
+
+ // Even if we just generated the key, always read it back to ensure we
+ // can read it successfully.
+ final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(
+ alias, null);
+ mPair = new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey());
+ }
+
+ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
+ private static void generateKeyPair(Context context, String alias)
+ throws GeneralSecurityException {
+ final Calendar start = new GregorianCalendar();
+ final Calendar end = new GregorianCalendar();
+ end.add(Calendar.YEAR, 100);
+
+ final KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
+ .setAlias(alias)
+ .setSubject(new X500Principal("CN=" + alias))
+ .setSerialNumber(BigInteger.ONE)
+ .setStartDate(start.getTime())
+ .setEndDate(end.getTime())
+ .build();
+
+ final KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
+
+ gen.initialize(spec);
+ gen.generateKeyPair();
+ }
+
+ /**
+ * Wrap a {@link SecretKey} using the public key assigned to this wrapper.
+ * Use {@link #unwrap(byte[])} to later recover the original
+ * {@link SecretKey}.
+ *
+ * @return a wrapped version of the given {@link SecretKey} that can be
+ * safely stored on untrusted storage.
+ */
+ public byte[] wrap(SecretKey key) throws GeneralSecurityException {
+ mCipher.init(Cipher.WRAP_MODE, mPair.getPublic());
+ return mCipher.wrap(key);
+ }
+
+ /**
+ * Unwrap a {@link SecretKey} using the private key assigned to this
+ * wrapper.
+ *
+ * @param blob a wrapped {@link SecretKey} as previously returned by
+ * {@link #wrap(SecretKey)}.
+ */
+ public SecretKey unwrap(byte[] blob) throws GeneralSecurityException {
+ mCipher.init(Cipher.UNWRAP_MODE, mPair.getPrivate());
+
+ return (SecretKey) mCipher.unwrap(blob, "AES", Cipher.SECRET_KEY);
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/net/bierbaumer/otp_authenticator/SettingsHelper.java b/app/src/main/java/net/bierbaumer/otp_authenticator/SettingsHelper.java
new file mode 100644
index 00000000..61ce8aab
--- /dev/null
+++ b/app/src/main/java/net/bierbaumer/otp_authenticator/SettingsHelper.java
@@ -0,0 +1,68 @@
+package net.bierbaumer.otp_authenticator;
+
+import android.content.Context;
+import android.os.Build;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+
+import java.io.File;
+import java.util.ArrayList;
+
+import javax.crypto.SecretKey;
+
+import static net.bierbaumer.otp_authenticator.Utils.readFully;
+import static net.bierbaumer.otp_authenticator.Utils.writeFully;
+
+public class SettingsHelper {
+ public static final String KEY_FILE = "otp.key";
+ public static final String SETTINGS_FILE = "secrets.dat";
+
+ public static void store(Context context, ArrayList entries){
+ JSONArray a = new JSONArray();
+
+ for(Entry e: entries){
+ try {
+ a.put(e.toJSON());
+ } catch (JSONException e1) {
+ }
+ }
+
+ try {
+ byte[] data = a.toString().getBytes();
+
+ int currentApiVersion = android.os.Build.VERSION.SDK_INT;
+ if (currentApiVersion >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
+ SecretKey key = EncryptionHelper.loadOrGenerateKeys(context, new File(context.getFilesDir() + "/" + KEY_FILE));
+ data = EncryptionHelper.encrypt(key,data);
+ }
+
+ writeFully(new File(context.getFilesDir() + "/" + SETTINGS_FILE), data);
+
+ } catch (Exception e) {
+ }
+
+ }
+
+ public static ArrayList load(Context context){
+ ArrayList entries = new ArrayList<>();
+
+ try {
+ byte[] data = readFully(new File(context.getFilesDir() + "/" + SETTINGS_FILE));
+
+ int currentApiVersion = android.os.Build.VERSION.SDK_INT;
+ if (currentApiVersion >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
+ SecretKey key = EncryptionHelper.loadOrGenerateKeys(context, new File(context.getFilesDir() + "/" + KEY_FILE));
+ data = EncryptionHelper.decrypt(key, data);
+ }
+ JSONArray a = new JSONArray(new String(data));
+
+ for(int i=0;i< a.length(); i++){
+ entries.add(new Entry(a.getJSONObject(i) ));
+ }
+ }
+ catch (Exception e) {
+ }
+ return entries;
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/net/bierbaumer/otp_authenticator/TOTPHelper.java b/app/src/main/java/net/bierbaumer/otp_authenticator/TOTPHelper.java
new file mode 100644
index 00000000..ced4b8d8
--- /dev/null
+++ b/app/src/main/java/net/bierbaumer/otp_authenticator/TOTPHelper.java
@@ -0,0 +1,52 @@
+package net.bierbaumer.otp_authenticator;
+
+import org.apache.commons.codec.binary.Base32;
+
+import javax.crypto.Mac;
+import javax.crypto.spec.SecretKeySpec;
+
+
+public class TOTPHelper {
+ public static final String SHA1 = "HmacSHA1";
+
+ public static String generate(byte[] secret) {
+ return String.format("%06d", generate(secret, System.currentTimeMillis() / 1000, 6));
+ }
+
+ public static int generate(byte[] key, long t, int digits)
+ {
+ int r = 0;
+ try {
+ t /= 30;
+ byte[] data = new byte[8];
+ long value = t;
+ for (int i = 8; i-- > 0; value >>>= 8) {
+ data[i] = (byte) value;
+ }
+
+ SecretKeySpec signKey = new SecretKeySpec(key, SHA1);
+ Mac mac = Mac.getInstance(SHA1);
+ mac.init(signKey);
+ byte[] hash = mac.doFinal(data);
+
+
+ int offset = hash[20 - 1] & 0xF;
+
+ long truncatedHash = 0;
+ for (int i = 0; i < 4; ++i) {
+ truncatedHash <<= 8;
+ truncatedHash |= (hash[offset + i] & 0xFF);
+ }
+
+ truncatedHash &= 0x7FFFFFFF;
+ truncatedHash %= Math.pow(10,digits);
+
+ r = (int) truncatedHash;
+ }
+
+ catch(Exception e){
+ }
+
+ return r;
+ }
+}
diff --git a/app/src/main/java/net/bierbaumer/otp_authenticator/Utils.java b/app/src/main/java/net/bierbaumer/otp_authenticator/Utils.java
new file mode 100644
index 00000000..45c83ce3
--- /dev/null
+++ b/app/src/main/java/net/bierbaumer/otp_authenticator/Utils.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package net.bierbaumer.otp_authenticator;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+public class Utils {
+ public static void writeFully(File file, byte[] data) throws IOException {
+ final OutputStream out = new FileOutputStream(file);
+ try {
+ out.write(data);
+ } finally {
+ out.close();
+ }
+ }
+
+ public static byte[] readFully(File file) throws IOException {
+ final InputStream in = new FileInputStream(file);
+ try {
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ byte[] buffer = new byte[1024];
+ int count;
+ while ((count = in.read(buffer)) != -1) {
+ bytes.write(buffer, 0, count);
+ }
+ return bytes.toByteArray();
+ } finally {
+ in.close();
+ }
+ }
+}
diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml
new file mode 100644
index 00000000..b5c8ee55
--- /dev/null
+++ b/app/src/main/res/layout/activity_main.xml
@@ -0,0 +1,58 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/layout/content_main.xml b/app/src/main/res/layout/content_main.xml
new file mode 100644
index 00000000..6a9561d6
--- /dev/null
+++ b/app/src/main/res/layout/content_main.xml
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/res/layout/dialog_about.xml b/app/src/main/res/layout/dialog_about.xml
new file mode 100644
index 00000000..bd0249aa
--- /dev/null
+++ b/app/src/main/res/layout/dialog_about.xml
@@ -0,0 +1,7 @@
+
+
\ No newline at end of file
diff --git a/app/src/main/res/layout/row.xml b/app/src/main/res/layout/row.xml
new file mode 100644
index 00000000..e7d8fd98
--- /dev/null
+++ b/app/src/main/res/layout/row.xml
@@ -0,0 +1,29 @@
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/menu/menu_edit.xml b/app/src/main/res/menu/menu_edit.xml
new file mode 100644
index 00000000..2295af22
--- /dev/null
+++ b/app/src/main/res/menu/menu_edit.xml
@@ -0,0 +1,18 @@
+
diff --git a/app/src/main/res/menu/menu_main.xml b/app/src/main/res/menu/menu_main.xml
new file mode 100644
index 00000000..a8d164c2
--- /dev/null
+++ b/app/src/main/res/menu/menu_main.xml
@@ -0,0 +1,16 @@
+
diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.png b/app/src/main/res/mipmap-hdpi/ic_launcher.png
new file mode 100644
index 00000000..cd604e41
Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher.png differ
diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.png b/app/src/main/res/mipmap-mdpi/ic_launcher.png
new file mode 100644
index 00000000..5b9945bb
Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher.png differ
diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/app/src/main/res/mipmap-xhdpi/ic_launcher.png
new file mode 100644
index 00000000..2fc00613
Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ
diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
new file mode 100644
index 00000000..c8441026
Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ
diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
new file mode 100644
index 00000000..ae4cb590
Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ
diff --git a/app/src/main/res/raw/about.html b/app/src/main/res/raw/about.html
new file mode 100644
index 00000000..008d8565
--- /dev/null
+++ b/app/src/main/res/raw/about.html
@@ -0,0 +1,27 @@
+
+
+
+
+
+
+
+
+
+ OTP Authenticator 1.0
+ © 2015 - Bruno Bierbaumer
+ Project Homepage
+ Acknowledgments
+
+
+
diff --git a/app/src/main/res/raw/opensource.html b/app/src/main/res/raw/opensource.html
new file mode 100644
index 00000000..ceaa0838
--- /dev/null
+++ b/app/src/main/res/raw/opensource.html
@@ -0,0 +1,31 @@
+
+
+
+
+
+
+
+