Skip to content Skip to sidebar Skip to footer

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(); privateKe

Solution 1:

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:

publicstaticvoidmain(String[] args)throws Exception {
    KeyPairGeneratorkpg= KeyPairGenerator.getInstance("RSA");
    Ciphercipher= Cipher.getInstance("RSA/ECB/PKCS1Padding");

    kpg.initialize(1024);
    KeyPairkeyPair= kpg.generateKeyPair();
    PrivateKeyprivKey= keyPair.getPrivate();
    PublicKeypubKey= keyPair.getPublic();

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

    Stringtest="My test string";
    StringciphertextFile="ciphertextRSA.txt";
    InputStreamfis=newByteArrayInputStream(test.getBytes("UTF-8"));

    FileOutputStreamfos=newFileOutputStream(ciphertextFile);
    CipherOutputStreamcos=newCipherOutputStream(fos, cipher);

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

    // DecryptStringcleartextAgainFile="cleartextAgainRSA.txt";

    cipher.init(Cipher.DECRYPT_MODE, privKey);

    fis = newFileInputStream(ciphertextFile);
    CipherInputStreamcis=newCipherInputStream(fis, cipher);
    fos = newFileOutputStream(cleartextAgainFile);

    while ((i = cis.read(block)) != -1) {
        fos.write(block, 0, i);
    }
    fos.close();
}

Post a Comment for "Rsa Encryption In Android"