Android™
Android™
Get the Public Key from a Private Key
See more Private Key Examples
Demonstrates the Chilkat PrivateKey.ToPublicKey method, which extracts the public portion of the loaded private key into an independent PublicKey object. The only argument is the PublicKey that receives the copy.
Note: The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.
Background: A key pair's public half is derived from the private half, and this is how you obtain it — the public key you distribute for others to verify signatures or encrypt to you, while the private key stays secret. The resulting
PublicKey is an independent copy, so exporting or sharing it never risks exposing the private material. From there, export it as PEM, JWK, or XML as needed.Chilkat Android™ Downloads
// 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;
// Load a private key to export.
CkPrivateKey privKey = new CkPrivateKey();
success = privKey.LoadPemFile("qa_data/private.pem");
if (success == false) {
Log.i(TAG, privKey.lastErrorText());
return;
}
// Extract the public portion of the private key into an independent PublicKey object. The
// PublicKey is a separate copy, unaffected by later changes to the PrivateKey.
CkPublicKey pubKey = new CkPublicKey();
success = privKey.ToPublicKey(pubKey);
if (success == false) {
Log.i(TAG, privKey.lastErrorText());
return;
}
// The PublicKey can now be exported or shared -- for example as PEM. The argument prefers the
// traditional PKCS #1 PEM when a traditional representation exists.
boolean preferPkcs1 = true;
String pubPem = pubKey.getPem(preferPkcs1);
if (pubKey.get_LastMethodSuccess() == false) {
Log.i(TAG, pubKey.lastErrorText());
return;
}
Log.i(TAG, pubPem);
}
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."
}
}