Sample code for 30+ languages & platforms
Android™

Generate an RSA Key and Export to XML

See more RSA Examples

Demonstrates how to generate an RSA key and export public/private to XML.

Chilkat Android™ Downloads

Android™
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean success = false;

    CkRsa rsa = new CkRsa();

    //  Generate a 2048-bit key.
    CkPrivateKey privKey = new CkPrivateKey();
    success = rsa.GenKey(2048,privKey);
    if (success == false) {
        Log.i(TAG, rsa.lastErrorText());
        return;
        }

    CkPublicKey pubKey = new CkPublicKey();
    privKey.ToPublicKey(pubKey);

    String privKeyXml = privKey.getXml();
    Log.i(TAG, privKeyXml);

    //  Sample output:

    //  <RSAKeyValue>
    //  	<Modulus>pvxYRzbV8Gru5/NNFQunXkLfhUW9W83/A+LtVD5jhV5oDZ5mv9R3BbfBE88UTqGjA1jZoFegprY3dGpm7Dl0PFqIYSwfE869Tx7OGzg+ocsM3klTBslxVftN4grJzovfWeUbi22JNbOEjuvI9548OmTnIHhYI9yhl54xyIHUIRWCa6nlPNfqqFD/tscmel+2AwWM5hhylse2Q3xg1Y3D3al3BckGGvrBGjKAFoN60+kmD0mnisy0zfHRAiHH8EsqSXASXjqRa6G60jj+tRrdY5AcOrtWe7tsoHE8txGI+xZQ6g3MWelyNM6Dnb324hid8rNxj33lFiqbOkQGPvE9fw==</Modulus>
    //  	<Exponent>AQAB</Exponent>
    //  	<D>fsydqC3+lJpOoblBrhp0VAKJwqSrXpv06pmVx+O8JJkEgFrpAP+wBZp8NbOIYxEgPLlqP/RqXE1/nJnzX6tdFTtV1hvv2VWisQLeVRMHlEogkmaxcjTjJ/w1LtEsXvgdeSCdIunhR/LyVKi8qTLx3xGh5CkeHNU7q2sHuI7Favy0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jTIFESgD0Cn5CKEIUpXIGntaNLLgDI=</InverseQ>
    //  </RSAKeyValue>

    String pubKeyXml = pubKey.getXml();
    Log.i(TAG, pubKeyXml);

    //  Sample output:
    //  <RSAPublicKey>
    //  	<Modulus>pvxYRzbV8Gru5/NNFQunXkLfhUW9W83/A+LtVD5jhV5oDZ5mv9R3BbfBE88UTqGjA1jZoFegprY3dGpm7Dl0PFqIYSwfE869Tx7OGzg+ocsM3klTBslxVftN4grJzovfWeUbi22JNbOEjuvI9548OmTnIHhYI9yhl54xyIHUIRWCa6nlPNfqqFD/tscmel+2AwWM5hhylse2Q3xg1Y3D3al3BckGGvrBGjKAFoN60+kmD0mnisy0zfHRAiHH8EsqSXASXjqRa6G60jj+tRrdY5AcOrtWe7tsoHE8txGI+xZQ6g3MWelyNM6Dnb324hid8rNxj33lFiqbOkQGPvE9fw==</Modulus>
    //  	<Exponent>AQAB</Exponent>
    //  </RSAPublicKey>

  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}