Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSA encrypt with base64 encoded public key in Android

Tags:

java

android

rsa

How to do RSA encryption of byte array with base-64 encoded public key?

After reading the couple of articles( of google search ) on how to do RSA encryption in Java, found the following snippet

public byte[] rsaEncrypt(byte[] data) {
  PublicKey pubKey = readKeyFromFile("/public.key");
  Cipher cipher = Cipher.getInstance("RSA");
  cipher.init(Cipher.ENCRYPT_MODE, pubKey);
  byte[] cipherData = cipher.doFinal(src);
  return cipherData;
}

I have public key as a base64 encoded string (126 characters), How do i create 'PublicKey' with the encoded string and use it with Cipher.

like image 260
Suresh Avatar asked Jun 02 '10 10:06

Suresh


2 Answers

Your base64 string is possibly an X509EncodedKeySpec. I can only guess. If so, you should base64 decode the string to obtain a byte []. Then construct an X509EncodedKeySpec from this byte []. Then create an instance of an RSA KeyFactory, and use the generatePublic() method of this KeyFactory to obtain a PublicKey. This public key can then be passed to Cipher.init().

Note: to perform base64 decoding use either the apache commons codec, or the Harder base64 decoder.

UPDATE March 8, 2017: In better-late-than-never news, Java 8 now includes a Base64 encoding/decoding class, java.util.Base64

like image 151
President James K. Polk Avatar answered Sep 25 '22 12:09

President James K. Polk


this is how you can generate Public and Private key pair below is the function to store them on hard dist

enter code here
public static void GenerateKeyPair()
{       
    try{
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(2048);
        KeyPair kp = kpg.genKeyPair();

        KeyFactory fact = KeyFactory.getInstance("RSA");
        RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(),
          RSAPublicKeySpec.class);
        RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(),
          RSAPrivateKeySpec.class);

        saveToFile("public.key", pub.getModulus(),
                  pub.getPublicExponent());
        saveToFile("private.key", priv.getModulus(),
                  priv.getPrivateExponent());
    }catch(Exception e){
        System.out.println(e.getMessage());
    }
}

public static void saveToFile(String fileName,
  BigInteger mod, BigInteger exp) throws Exception {
  ObjectOutputStream oout = new ObjectOutputStream(
    new BufferedOutputStream(new FileOutputStream(fileName)));
  try {
    oout.writeObject(mod);
    oout.writeObject(exp);
  } catch (Exception e) {
    throw new Exception("error", e);
  } finally {
    oout.close();
  }
}
like image 24
Alex Avatar answered Sep 24 '22 12:09

Alex