Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSA encryption in Android

I am writing a program which employs RSA in Android. I have the following problem: I am getting the RSA keys:

KeyPair kp = kpg.genKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();

Using the encryption function to encrypt a test string:

String test ="test";
byte[] testbytes = test.getBytes();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherData = cipher.doFinal(testbytes);
String s = new String(cipherData);
Log.d("testbytes after encryption",s);

In the decryption function i am decrypting the data back to get the original string

Cipher cipher2 = Cipher.getInstance("RSA");
cipher2.init(Cipher.DECRYPT_MODE, privateKey);
byte[] plainData = cipher.doFinal(cipherData);
String p  = new String(plainData);
Log.d("decrypted data is:",p);

The data in 'p' printed out in the log does not match the original string "test" . Where am I going wrong in this?

like image 254
DaTaBomB Avatar asked Nov 25 '12 22:11

DaTaBomB


1 Answers

Here an example on how to do it, BUT in practice,

You can't really encrypt and decrypt whole files with just RSA. The RSA algorithm can only encrypt a single block, and it is rather slow for doing a whole file.
You can encrypt the file using 3DES or AES, and then encrypt the AES key using intended recipient's RSA public key.

Some code:

public static void main(String[] args) throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

    kpg.initialize(1024);
    KeyPair keyPair = kpg.generateKeyPair();
    PrivateKey privKey = keyPair.getPrivate();
    PublicKey pubKey = keyPair.getPublic();

    // Encrypt
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);

    String test = "My test string";
    String ciphertextFile = "ciphertextRSA.txt";
    InputStream fis = new ByteArrayInputStream(test.getBytes("UTF-8"));

    FileOutputStream fos = new FileOutputStream(ciphertextFile);
    CipherOutputStream cos = new CipherOutputStream(fos, cipher);

    byte[] block = new byte[32];
    int i;
    while ((i = fis.read(block)) != -1) {
        cos.write(block, 0, i);
    }
    cos.close();

    // Decrypt
    String cleartextAgainFile = "cleartextAgainRSA.txt";

    cipher.init(Cipher.DECRYPT_MODE, privKey);

    fis = new FileInputStream(ciphertextFile);
    CipherInputStream cis = new CipherInputStream(fis, cipher);
    fos = new FileOutputStream(cleartextAgainFile);

    while ((i = cis.read(block)) != -1) {
        fos.write(block, 0, i);
    }
    fos.close();
}
like image 89
Frank Avatar answered Sep 24 '22 04:09

Frank