Android RSA Crypto Code

 RSA Example

We use the following Java code to encode text "Open Source Java Projects OFLAMERON" using the RSA algorithm and its subsequent decoding

   // Original text
    String testText = "Open Source Java Projects OFLAMERON";
    TextView originalTextView = (TextView) findViewById(R.id.textViewOriginal);
    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); //1024 Key
        KeyPair kp = kpg.genKeyPair();
        publicKey = kp.getPublic(); //Public Key
        privateKey = kp.getPrivate(); //Private Key
    } 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");
 

Open Source Java Project OFLAMERON

 RSA Example

 

 

Comments

Popular posts from this blog

Android Photo Registrar OFLAMERON

Android Java Open Source

Czech Entropy