Skip to content

Commit

Permalink
Merge pull request #858 from opensrp/encrypt-file-example
Browse files Browse the repository at this point in the history
Encrypt file example
  • Loading branch information
hilpitome authored Sep 28, 2022
2 parents cc9dd87 + aa650e8 commit d1408d3
Show file tree
Hide file tree
Showing 7 changed files with 148 additions and 3 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,9 @@ _**void generateKey(String keyAlias)**_ For key generation using a Key Alias par

- NB: \* This class depends on `AndroidLegacyCryptography` class and the `AndroidMCryptography` class which both implement the above in different ways depending on the SDK version.
`AndroidLegacyCryptography` has method implementation that are used when the SDK version is less than API level 23

The sample app has examples of how these methods have been implemented. The code for it can be found in
the [MainActivity](https://github.com/opensrp/opensrp-client-core/blob/master/sample/src/main/java/org/smartregister/sample/MainActivity.java) class.

## 2. Data management

Expand Down
Binary file added opensrp-app/jacoco.exec
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,7 @@ public byte[] decrypt(byte[] encrypted, String keyAlias) {

Cipher c = Cipher.getInstance(AES_MODE);
c.init(Cipher.DECRYPT_MODE, getKey(keyAlias), new GCMParameterSpec(128, INITIALIZATION_VECTOR));
byte[] decodedBytes = c.doFinal(encrypted);
return decodedBytes;
return c.doFinal(encrypted);
} catch (Exception e) {

Timber.e(e);
Expand Down
94 changes: 93 additions & 1 deletion sample/src/main/java/org/smartregister/sample/MainActivity.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.smartregister.sample;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
Expand All @@ -9,9 +10,11 @@
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.ToggleButton;

import androidx.appcompat.widget.Toolbar;

Expand All @@ -20,23 +23,31 @@

import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.smartregister.cryptography.CryptographicHelper;
import org.smartregister.cursoradapter.SmartRegisterQueryBuilder;
import org.smartregister.sample.fragment.ReportFragment;
import org.smartregister.util.AppHealthUtils;
import org.smartregister.util.DateUtil;
import org.smartregister.util.LangUtils;
import org.smartregister.view.activity.MultiLanguageActivity;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import timber.log.Timber;

public class MainActivity extends MultiLanguageActivity {

DatePicker picker;
Button btnGet;
TextView tvw;

CryptographicHelper cryptographicHelper = null;
TextView encDecTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Expand All @@ -49,6 +60,7 @@ protected void onCreate(Bundle savedInstanceState) {
Activity activity = this;
tvw = (TextView) findViewById(R.id.textView1);
picker = (DatePicker) findViewById(R.id.datePicker1);
encDecTextView = (TextView) findViewById(R.id.encrypt_decrypt_tv);

picker.setMinDate(new LocalDate().minusYears(2).toDate().getTime());

Expand Down Expand Up @@ -140,6 +152,80 @@ public void onNothingSelected(AdapterView<?> parent) {
((TextView) findViewById(R.id.time)).setText(DateUtil.getDuration(new DateTime().minusYears(4).minusMonths(3).minusWeeks(2).minusDays(1)));

new AppHealthUtils(findViewById(R.id.show_sync_stats));

// File encryption example section
ToggleButton toggle = (ToggleButton) findViewById(R.id.encrypt_decrypt_toggle);
cryptographicHelper = CryptographicHelper.getInstance(this);
String filename = "test.txt";
String contents = getString(R.string.encrypt_decrypt_string);
// Create a file with the contents above
try (FileOutputStream fos = MainActivity.this.openFileOutput(filename, Context.MODE_PRIVATE)) {
fos.write(contents.getBytes());
fos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}


toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
String keyAlias = "sample";
// Get or create a key with the Alias name sample or create one if id does not exist
if(cryptographicHelper.getKey(keyAlias)==null)
{
cryptographicHelper.generateKey(keyAlias);
Timber.i("key with alias %s generated",keyAlias);
}

if (isChecked) {

try {
// read the text.txt while it is in plain text and write to file
FileInputStream inputStream = openFileInput(filename);
byte[] inputBytes = new byte[inputStream.available()];
inputStream.read(inputBytes);
byte[] encryptedContents = CryptographicHelper.encrypt(inputBytes, keyAlias);
FileOutputStream fileOutputStream = openFileOutput(filename, Context.MODE_PRIVATE);
Timber.i("encrypted stuff to write %S ",new String(encryptedContents));
encDecTextView.setText(new String(encryptedContents));
fileOutputStream.write((encryptedContents));
fileOutputStream.flush();


} catch (IOException e) {
e.printStackTrace();
}

} else {
try {
//
FileInputStream inputStream = openFileInput(filename);
byte[] inputBytes = new byte[inputStream.available()];
inputStream.read(inputBytes);
Timber.i("before decryption %s", new String(inputBytes));

byte[] decryptedStuff = CryptographicHelper.decrypt(inputBytes, keyAlias);
encDecTextView.setText(new String(decryptedStuff));
Timber.i("decrypted content %s", new String(decryptedStuff));

FileOutputStream fileOutputStream = openFileOutput(filename, Context.MODE_PRIVATE);
fileOutputStream.write((decryptedStuff));
fileOutputStream.flush();


} catch (IOException e) {
e.printStackTrace();
// Error occurred when opening raw file for reading.
}


}
}
});


}

@Override
Expand All @@ -166,4 +252,10 @@ public boolean onOptionsItemSelected(MenuItem item) {

return super.onOptionsItemSelected(item);
}

@Override
protected void onDestroy() {
super.onDestroy();
cryptographicHelper = null;
}
}
24 changes: 24 additions & 0 deletions sample/src/main/res/layout-v17/content_main.xml
Original file line number Diff line number Diff line change
Expand Up @@ -91,5 +91,29 @@
android:text="@string/sync_stats_label" />

</LinearLayout>
<LinearLayout
android:id="@+id/cryptography_layout"
android:layout_below="@+id/sync_stats_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true">
<TextView
android:id="@+id/encrypt_decrypt_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/encrypt_decrypt_string"
/>


<ToggleButton
android:id="@+id/encrypt_decrypt_toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="@string/encrypt"
android:textOn="@string/decrypt"
android:layout_marginLeft="100dp"/>
</LinearLayout>

</RelativeLayout>
24 changes: 24 additions & 0 deletions sample/src/main/res/layout/content_main.xml
Original file line number Diff line number Diff line change
Expand Up @@ -91,5 +91,29 @@
android:text="@string/sync_stats_label" />

</LinearLayout>
<LinearLayout
android:id="@+id/cryptography_layout"
android:layout_below="@+id/sync_stats_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true">
<TextView
android:id="@+id/encrypt_decrypt_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/encrypt_decrypt_string"
/>


<ToggleButton
android:id="@+id/encrypt_decrypt_toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="@string/encrypt"
android:textOn="@string/decrypt"
android:layout_marginLeft="100dp"/>
</LinearLayout>

</RelativeLayout>
3 changes: 3 additions & 0 deletions sample/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,7 @@
<string name="action_report_sample">Sample Reports</string>
<string name="action_sync_stats">Sync Statistics</string>
<string name="sync_stats_label">Show Sync Stats (Long Press for Dialog)</string>
<string name="encrypt_decrypt_string">Please encrypt or decrypt me by hitting clicking on the switch below</string>
<string name="encrypt">Encrypt</string>
<string name="decrypt">Decrypt</string>
</resources>

0 comments on commit d1408d3

Please sign in to comment.