Wednesday, July 20, 2011

RSA java encrypt, decrypt

Following code can be used to encrypt, decrypt string using RSA encryption.

NOTE :- Apache Commons Codec used for encode string to base64.

import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;

import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;

public class MainClass {

    public static void main(String[] args) throws Exception {
        byte[] expBytes = Base64.decodeBase64("AQAB");
        byte[] modBytes = Base64.decodeBase64("nzLiZDSiu484r5NcBQN3rNP3x5aqY3Eq6CkQDwuilTzd5ZNdTcTxw7C1JQ9ih27Vq4RU9NYgi9oOUTVQ2gkqP1OJA9aawjCRwMJ7PRyKlBEpsdE/wFtu9/1ciGRtWSyACr2jTASZPQa+aHQh2qziacWd+iVmGIq0+l11nGG/GYU=");
        byte[] dBytes = Base64.decodeBase64("nyF45NssUzkdW3t7/tLxfENBKTN0TARh9ECfebqSoIR/9awxFrynQYnP+CSBw4jJcjHLzhR/4etsZkZZ9Cg3HhPA5pjVcI5kJct4kLjWM+ejZliZoV/KvpJN261VKKLTJMX64UeMiLAlb7mUNoNqKztgflxz5Dbad5hemvgwg50=");

        BigInteger modules = new BigInteger(1, modBytes);
        BigInteger exponent = new BigInteger(1, expBytes);
        BigInteger d = new BigInteger(1, dBytes);

        KeyFactory factory = KeyFactory.getInstance("RSA");
        Cipher cipher = Cipher.getInstance("RSA");
        String input = "test";

        RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(modules, exponent);
        PublicKey pubKey = factory.generatePublic(pubSpec);
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] encrypted = cipher.doFinal(input.getBytes("UTF-8"));
        System.out.println(encrypted);
        System.out.println("encrypted: " + new String(encrypted));

        RSAPrivateKeySpec privSpec = new RSAPrivateKeySpec(modules, d);
        PrivateKey privKey = factory.generatePrivate(privSpec);
        cipher.init(Cipher.DECRYPT_MODE, privKey);
        byte[] decrypted = cipher.doFinal(encrypted);
        System.out.println("decrypted: " + new String(decrypted));
    }
}

No comments:

Post a Comment