Android™
Android™
RSA Encrypt Randomly Generated AES Key
See more RSA Examples
Demonstrates how to RSA encrypt a randomly generated AES key.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;
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// First generate a 256-bit AES key (32 bytes).
CkPrng prng = new CkPrng();
CkBinData bdAesKey = new CkBinData();
success = prng.GenRandomBd(32,bdAesKey);
// Use a public key from a certificate for RSA encryption.
CkCert cert = new CkCert();
success = cert.LoadFromFile("qa_data/pem/mf_public_rsa.pem");
if (success == false) {
Log.i(TAG, cert.lastErrorText());
return;
}
CkPublicKey pubKey = new CkPublicKey();
cert.GetPublicKey(pubKey);
CkRsa rsa = new CkRsa();
success = rsa.UsePublicKey(pubKey);
if (success == false) {
Log.i(TAG, rsa.lastErrorText());
return;
}
// RSA encrypt our 32-byte AES key.
// The contents of bdAesKey are replaced with result of the RSA encryption.
success = rsa.EncryptBd(bdAesKey,false);
if (success == false) {
Log.i(TAG, rsa.lastErrorText());
return;
}
// Return the result as a base64 string
String encryptedAesKey = bdAesKey.getEncoded("base64");
Log.i(TAG, "encrypted AES key = " + encryptedAesKey);
}
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."
}
}