Android™
Android™
Export a Private Key as DER into a BinData
See more Private Key Examples
Demonstrates the Chilkat PrivateKey.GetPkcsBd method, which exports the key as DER into a BinData. The first argument selects PKCS #1 (true) versus PKCS #8 (false), the second is the password (empty for unencrypted), and the third is the BinData that receives the bytes.
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: This is the in-memory binary export — the raw DER bytes land in a
BinData ready to hash, encrypt, or hand to another API without a temporary file. One method covers several cases: the boolean picks the traditional (PKCS #1) versus modern (PKCS #8) structure, and a nonempty password produces an encrypted PKCS #8 export (with the cipher from Pkcs8EncryptAlg). Source any password securely.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;
}
// The key password is not hard-coded in a real application; obtain it from an interactive
// prompt, environment variable, or a secrets vault.
String password = "myKeyPassword";
// Export the key as DER into a BinData. The 1st argument selects PKCS #1 (true) versus PKCS #8
// (false); the 2nd is the password (empty string for an unencrypted export); the 3rd is the
// BinData that receives the DER bytes.
boolean usePkcs1 = false;
CkBinData bd = new CkBinData();
success = privKey.GetPkcsBd(usePkcs1,password,bd);
if (success == false) {
Log.i(TAG, privKey.lastErrorText());
return;
}
Log.i(TAG, "Exported " + String.valueOf(bd.get_NumBytes()) + " DER bytes.");
}
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."
}
}