Android Open Source
RSA Java Crypto Project
MainActivity.java
Full working example. The markup is given in the previous post.
package org.o7planning.rsa;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Provider;
import java.security.Security;
import java.util.Iterator;
import java.util.TreeSet;
import javax.crypto.Cipher;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Original text
String testText = "Open Source Java Project";
TextView originalTextView = (TextView) findViewById(R.id.TXTV);
originalTextView.setText("[ORIGINAL]:\n" + testText + "\n");
// Generate key pair for 1024-bit RSA encryption and decryption
Key publicKey = null;
Key privateKey = null;
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");
}
// Encode the original data with RSA private key
byte[] encodedBytes = null;
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");
// Decode the encoded data with RSA public key
byte[] decodedBytes = null;
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");
}
}
(c( by Valery Shmelev https://www.linkedin.com/in/valery-shmelev-479206227/
Comments
Post a Comment