Thursday, August 27, 2015

Encryption/Decryption in Android - Asymmetric

As previously explained about the Asymmetric encryption in the post here, lets look into implementing Asymmetric Encryption in Android.

Among the various asymmetric algorithms present, the most widely used algorithm is the RSA Algorithm.
Since this is asymmetric, we need to generate a public/private key pair and remember that public key is used for encryption, however private key is used for decryption.So whoever is  having "Public Key", can encrypt the message, but it can only be decrypted by the person who is having the "Private Key".

We need  following in order to perform encryption/decryption:-

a. KeyPair (java.security), which contains the Public/Private key pair
b.  KeyPairGenerator (java.security), to generate the KeyPair
c. Algorithm type:- to be used by KeyGenerator to generate SecretKey(RSA)
d. Key_Length :- The size of the key in bits


Generating a Public/Private KeyPair


KeyPair generateRSAKey() {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048) ;//key length as 2048 bit
return keyPairGenerator.generateKeyPair()
}

so Public key can be obtained by keyPair.getPublic();
and Private key by keyPair.getPrivate();
Again it is recommended to save the keys in encoded byte[] form using
keyPair.getPublic().getEncoded() -------------------Public Key
keyPair.getPrivate().getEncoded()-------------------Private Key


Regenerating the Keys from encoded byte[]


PublicKey decodePublicKey(byte[] encodedKey) {
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey) ;
KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 
return keyFactory.generatePublic(keySpec);
}

PublicKey decodePrivateKey(byte[] encodedKey) {
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey) ;
KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 
return keyFactory.generatePrivate(keySpec);
}

Encrypting Message using RSA Public Key


byte[] performRSAEncryption(PublicKey publicKey , byte[] message) {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE , publicKey);
return cipher.doFinal(message);


Decrypting Message using RSA Private Key


byte[] performRSADecryption(PrivateKey privateKey , byte[] message) {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE , publicKey);
return cipher.doFinal(message);
}

No comments:

Post a Comment