Android Open Source

 Open Source RSA Crypto

Android RSA Crypto

Here we have added to the project writing ciphertext to a file oflameron.txt and reading from a ciphertext file.

Layout file - in the previous post

MainActivity.java

 package org.o7planning.bincharbin;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Build;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;

import javax.crypto.Cipher;

public class MainActivity extends AppCompatActivity {
    //=====================================================
    //
    // RSA and Write encoded text to file and Read from file oflameron.txt
    //
    //=====================================================
    final static String LOG_TAG = "myLogs";
    public static String str=""; //File contents oflameron.txt
    public static String str2=""; //File contents oflameron.txt
    final static String FILENAME = "oflameron.txt";//File for writing encoded data
    public static String Content = "EditText Content";//String variable for text copy

    public static Key publicKey = null; //RSA
    public static Key privateKey = null; //RSA
    public static byte[] encodedBytes = null; //RSA
    public static byte[] decodedBytes = null; //RSA
    // Original text (RSA)
    public static String testText = "Open Source Java Project Valery Shmelev OFLAMERON";



    @RequiresApi(api = Build.VERSION_CODES.R)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);





        TextView originalTextView = (TextView) findViewById(R.id.TXTV);
        originalTextView.setText("[ORIGINAL]:\n" + testText + "\n");

        // ============================================================
        // Generate key pair for 1024-bit RSA encryption and decryption
        // ============================================================
        try {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
            kpg.initialize(1024);
            KeyPair kp = kpg.genKeyPair();
            publicKey = kp.getPublic();
            privateKey = kp.getPrivate();
        } catch (Exception e) {
            Log.e("Crypto", "== == RSA key pair error == ==");
        }
        // ============================================================

        // ============================================================
        // Code
        // ============================================================
        // Encode the original data with RSA private key
        try {
            Cipher c = Cipher.getInstance("RSA");
            c.init(Cipher.ENCRYPT_MODE, privateKey);
            encodedBytes = c.doFinal(testText.getBytes());
        } catch (Exception e) {
            Log.e("Crypto", "RSA encryption error");
        }
        TextView encodedTextView = (TextView)findViewById(R.id.textViewEncoded);
        encodedTextView.setText("[ENCODED]:\n" + Base64.encodeToString(encodedBytes, Base64.DEFAULT) + "\n");

        Save();  //Write Coded Text to file oflameron.txt     str
        //encodedBytes = Base64.decode(str, Base64.DEFAULT);
        encodedBytes = null;
        Load(); //Here we have erased the ciphertext from the variable encodedBytes. We have already written it to the file oflameron.txt in the module Save();. Now read and decode.
        // If you run the application, you will see that the original text is correctly decoded.
        // Those. we run the application and immediately encode the text and immediately decode it. Everything is working.

        // ============================================================
        // Decode
        // ============================================================
        // Decode the encoded data with RSA public key
         try {
            Cipher c = Cipher.getInstance("RSA");
            c.init(Cipher.DECRYPT_MODE, publicKey);
            decodedBytes = c.doFinal(encodedBytes);
        } catch (Exception e) {
            Log.e("Crypto", "RSA decryption error");
        }

        TextView decodedTextView = (TextView)findViewById(R.id.textViewDecoded);
        decodedTextView.setText("[DECODED]:\n" + new String(decodedBytes) + "\n");


    } //OnCreate

    //==========================================================
    // WRITE data to the oflameron.txt file
    //==========================================================
    @RequiresApi(api = Build.VERSION_CODES.R)
    public void Save() {
         str =  Base64.encodeToString(encodedBytes, Base64.DEFAULT);


        try {
            // The data is encoded. We tear off the stream for writing data to the file oflameron.txt
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                    openFileOutput(FILENAME, MODE_PRIVATE)));
            // We write data to the file oflameron.txt in the isolated memory area of this application
            // A file on a smartphone in the Device File Explorer folder /data/data/com.example.cryptonote/files/oflameron.txt
            Content = str; //Text to write to the oflameron.txt file from a variable str from EText
            bw.write(Content);
            // Closing the stream
            Log.d(LOG_TAG, "== == File Save == ==");
            bw.flush();
            bw.close();
            //Log.d(LOG_TAG, getStorageDirectory().toString());  //Write the name of the current foldergetStorageDirectory()



        } catch (FileNotFoundException e) {
            Log.d(LOG_TAG, "== == Err NO WRITE File == ==");
            e.printStackTrace();
        } catch (IOException e) {
            Log.d(LOG_TAG, "== == Err NO WRITE File == ==");
            e.printStackTrace();
        }
    }




    //==========================================================
    //   READ oflameron.txt file
    //==========================================================
    public void Load()  {


        try {//Read data file oflameron.txt
            // Opening a stream for reading
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    openFileInput(FILENAME)));
            // читаем содержимое
            while ((str = br.readLine()) != null) {
                str2 = str2 + str; //Save read data
                // CryptoNOTE (c) by Valery Shmelev https://www.linkedin.com/in/valery-shmelev-479206227/
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.d(LOG_TAG, "== == RSA Readed Coded text == ==" + str2);
        //encodedBytes = str2.getBytes("UTF-8");
        encodedBytes = Base64.decode(str2, Base64.DEFAULT);
    }




    }

 

When the application starts, the text from the variable is immediately encrypted, written to the file, read from the file, decoded and written to the lower text field

Now let's add a button to the markup. Disable automatic reading of the file. Clicking the button will read and decode the data from the file.

  

Open Source RSA Crypto

Comments

Popular posts from this blog

Android Source Code

CryptoNOTE with AES

Android Photo Registrar OFLAMERON