· 5 years ago · Mar 05, 2020, 03:52 PM
1package com.isen.secumobileisen
2
3import android.app.AlertDialog
4import android.content.Intent
5import android.content.SharedPreferences
6import android.content.pm.PackageInfo
7import android.content.pm.PackageManager
8import android.os.Build
9import androidx.appcompat.app.AppCompatActivity
10import androidx.security.crypto.EncryptedSharedPreferences
11import androidx.security.crypto.MasterKeys
12import android.os.Bundle
13import android.util.Base64
14import android.util.Log
15import com.google.firebase.auth.FirebaseAuth
16import kotlinx.android.synthetic.main.activity_home.*
17import java.lang.Exception
18
19import java.security.MessageDigest
20import androidx.core.app.ComponentActivity.ExtraData
21import androidx.core.content.ContextCompat.getSystemService
22import android.icu.lang.UCharacter.GraphemeClusterBreak.T
23
24
25class HomeActivity : AppCompatActivity() {
26
27 private val preferencesName = "SharedPreferences"
28 lateinit var sharedPreferences: SharedPreferences
29
30 override fun onCreate(savedInstanceState: Bundle?) {
31 super.onCreate(savedInstanceState)
32 setContentView(R.layout.activity_home)
33
34 histoIcon.setOnClickListener {
35 goToHisto()
36 }
37
38 listIcon.setOnClickListener {
39 goToList()
40 }
41
42 listPIcon.setOnClickListener {
43 goToListP()
44 }
45
46 btn_logout.setOnClickListener {
47 logout()
48 }
49 }
50
51 private fun goToHisto() {
52 //start next activity
53 val intent = Intent(this@HomeActivity, HistoActivity::class.java)
54 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
55 startActivity(intent)
56 }
57
58 private fun goToList() {
59 //start next activity
60 val intent = Intent(this@HomeActivity, MainActivity::class.java)
61 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
62 startActivity(intent)
63 }
64
65 private fun goToListP() {
66 //start next activity
67 val intent = Intent(this@HomeActivity, ListActivity::class.java)
68 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
69 startActivity(intent)
70 }
71
72 private fun logout() {
73 FirebaseAuth.getInstance().signOut()
74 val intent = Intent(this@HomeActivity, LoginActivity::class.java)
75 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
76 startActivity(intent)
77 finish()
78 }
79
80 private fun initEncryptedSharedPreferences() {
81 getSharedPreferences(preferencesName, MODE_PRIVATE).edit().apply()
82
83 val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
84
85 sharedPreferences = EncryptedSharedPreferences.create(
86 preferencesName,
87 masterKeyAlias,
88 applicationContext,
89 EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
90 EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
91 )
92 }
93
94 private fun saveValue() {
95 sharedPreferences.edit().putString("DATA", hashFunction("SHA-512", "")).apply()
96 }
97
98 private fun readValue(): String? {
99 return sharedPreferences.getString("DATA", "")
100 }
101
102 private fun hashFunction(type: String, input: String): String {
103 val hexChars = "Kotlin?NeverAgain"
104 val bytes = MessageDigest
105 .getInstance(type)
106 .digest(input.toByteArray())
107 val result = StringBuilder(bytes.size * 2)
108
109 bytes.forEach {
110 val i = it.toInt()
111 result.append(hexChars[i shr 4 and 0x0f])
112 result.append(hexChars[i and 0x0f])
113 }
114 return result.toString()
115 }
116
117}
118
119
120package com.isen.secumobileisen
121
122import android.app.AlertDialog
123import android.app.ProgressDialog
124import android.content.Intent
125import android.content.pm.PackageInfo
126import android.content.pm.PackageManager
127import android.os.Build
128import android.os.Bundle
129import android.security.keystore.KeyGenParameterSpec
130import android.security.keystore.KeyProperties
131import android.text.TextUtils
132import android.util.Base64
133import android.util.Log
134import android.view.View
135import android.widget.Button
136import android.widget.EditText
137import android.widget.TextView
138import android.widget.Toast
139import androidx.appcompat.app.AppCompatActivity
140import com.google.firebase.auth.FirebaseAuth
141import kotlinx.android.synthetic.main.activity_login.*
142import java.lang.Exception
143import java.security.Key
144import java.security.KeyStore
145import java.security.MessageDigest
146import javax.crypto.KeyGenerator
147import javax.crypto.SecretKey
148import javax.crypto.spec.IvParameterSpec
149
150
151class LoginActivity : AppCompatActivity() {
152
153 private val TAG = "LoginActivity"
154 //global variables
155 private var email: String? = null
156 private var password: String? = null
157 private val SIGNATURE: String = ""
158 //UI elements
159 private var tvForgotPassword: TextView? = null
160 private var etEmail: EditText? = null
161 private var etPassword: EditText? = null
162 private var btnLogin: Button? = null
163 private var btnCreateAccount: Button? = null
164 private var mProgressBar: ProgressDialog? = null
165 //Firebase references
166 private var mAuth: FirebaseAuth? = null
167
168 private var keyAES = generateSymmetricKey("keyAES")
169
170 override fun onCreate(savedInstanceState: Bundle?) {
171 super.onCreate(savedInstanceState)
172 setContentView(R.layout.activity_login)
173
174 if(!goodInstaller()){
175 AlertDialog.Builder(this)
176 .setTitle("ATTENTION")
177 .setMessage("Votre application n'a pas été installée par un programme reconnu.")
178 .setNeutralButton("Ok") { _, _ -> }
179 .create()
180 .show()
181 }
182
183 if(isEmulator()){
184 AlertDialog.Builder(this)
185 .setTitle("ATTENTION")
186 .setMessage("Votre application tourne sur un emulateur.")
187 .setNeutralButton("Ok") { _, _ -> }
188 .create()
189 .show()
190 }
191
192 if(!goodSignature()){
193 AlertDialog.Builder(this)
194 .setTitle("ATTENTION")
195 .setMessage("Votre application ne possède pas la signature du constructeur.")
196 .setNeutralButton("Ok") { _, _ -> }
197 .create()
198 .show()
199 }
200
201 initialise()
202
203 /*btn_addK.setOnClickListener {
204 generateSymmetricKey(et_key.text.toString())
205 }
206 */
207 }
208
209 override fun onResume() {
210 super.onResume()
211 btn_addK.setOnClickListener {
212 generateSymmetricKey(et_key.text.toString())
213 }
214 }
215
216 private fun initialise() {
217 etEmail = findViewById<View>(R.id.et_email) as EditText
218 etPassword = findViewById<View>(R.id.et_password) as EditText
219 btnLogin = findViewById<View>(R.id.btn_login) as Button
220 btnCreateAccount = findViewById<View>(R.id.btn_register_account) as Button
221 mProgressBar = ProgressDialog(this)
222 mAuth = FirebaseAuth.getInstance()
223 btnCreateAccount!!
224 .setOnClickListener { startActivity(Intent(this@LoginActivity,
225 CreateAccountActivity::class.java)) }
226 btnLogin!!.setOnClickListener { loginUser() }
227 }
228
229 private fun loginUser() {
230 email = etEmail?.text.toString()
231 password = etPassword?.text.toString()
232 if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)) {
233 mProgressBar!!.setMessage("Registering User...")
234 mProgressBar!!.show()
235 Log.d(TAG, "Logging in user.")
236 mAuth!!.signInWithEmailAndPassword(email!!, password!!)
237 .addOnCompleteListener(this) { task ->
238 mProgressBar!!.hide()
239 if (task.isSuccessful) {
240 // Sign in success, update UI with signed-in user's information
241 Log.d(TAG, "signInWithEmail:success")
242 updateUI()
243 } else {
244 // If sign in fails, display a message to the user.
245 Log.e(TAG, "signInWithEmail:failure", task.exception)
246 Toast.makeText(this@LoginActivity, "Authentication failed.",
247 Toast.LENGTH_SHORT).show()
248 }
249 }
250 } else {
251 Toast.makeText(this, "Enter all details", Toast.LENGTH_SHORT).show()
252 }
253 }
254
255 private fun updateUI() {
256 val intent = Intent(this@LoginActivity, HomeActivity::class.java)
257 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
258 intent.putExtra("KEY_AES", keyAES);
259 startActivity(intent)
260 finish()
261 }
262
263 fun generateSymmetricKey(keyAlias: String): Key {
264
265 val IV = "jdetestelekotlin"
266 val ivParameterSpec = IvParameterSpec(IV.toByteArray())
267
268
269 val keyStore = KeyStore.getInstance("AndroidKeyStore")
270 keyStore.load(null)
271 if (!keyStore.containsAlias(keyAlias)) {
272 val keyGenParameterSpec =
273 KeyGenParameterSpec.Builder(
274 keyAlias,
275 KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
276 )
277 .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
278 .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
279 .setKeySize(128)
280 .setRandomizedEncryptionRequired(false)
281 .build()
282 val keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
283 keyGenerator.init(keyGenParameterSpec)
284 return keyGenerator.generateKey()
285 }
286
287 else {
288 Log.d("LoginActiivty", "Non")
289
290 }
291 return keyStore.getKey(keyAlias, null)
292 }
293
294 fun loadSymmetricKey(keyAlias: String) : Key {
295 val keyStore = KeyStore.getInstance("AndroidKeyStore")
296 keyStore.load(null)
297
298 var secretKey: SecretKey?
299 secretKey = (keyStore.getEntry(keyAlias, null) as KeyStore.SecretKeyEntry).secretKey
300
301 return secretKey
302 }
303
304 private fun goodInstaller(): Boolean {
305 val installer: String? = this.packageManager.getInstallerPackageName(this.packageName)
306 return installer != null && installer.startsWith("com.android.vending")
307 }
308
309 private fun getCurrentSignature(): String? {
310 try {
311 val packageInfo: PackageInfo =
312 this.packageManager.getPackageInfo(this.packageName, PackageManager.GET_SIGNATURES)
313
314 for (signature in packageInfo.signatures) {
315 val md: MessageDigest = MessageDigest.getInstance("SHA-512")
316 md.update(signature.toByteArray())
317 val currentSignature: String = Base64.encodeToString(md.digest(), Base64.DEFAULT)
318
319 Log.d(
320 "REMOVEME",
321 "Include this string as a value for SIGNATURE:" + currentSignature
322 )
323
324 return currentSignature
325 }
326 } catch (e: Exception) {
327 e.stackTrace
328 }
329
330 return null
331 }
332
333 private fun goodSignature(): Boolean {
334 if (getCurrentSignature().equals(SIGNATURE)) {
335 return true
336 }
337 return false
338 }
339
340 private fun isEmulator(): Boolean {
341 return (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic")
342 || Build.FINGERPRINT.startsWith("generic")
343 || Build.FINGERPRINT.startsWith("unknown")
344 || Build.HARDWARE.contains("goldfish")
345 || Build.HARDWARE.contains("ranchu")
346 || Build.MODEL.contains("google_sdk")
347 || Build.MODEL.contains("Emulator")
348 || Build.MODEL.contains("Android SDK built for x86")
349 || Build.MANUFACTURER.contains("Genymotion")
350 || Build.PRODUCT.contains("sdk_google")
351 || Build.PRODUCT.contains("google_sdk")
352 || Build.PRODUCT.contains("sdk")
353 || Build.PRODUCT.contains("sdk_x86")
354 || Build.PRODUCT.contains("vbox86p")
355 || Build.PRODUCT.contains("emulator")
356 || Build.PRODUCT.contains("simulator"))
357 }
358}