Sample code for 30+ languages & platforms
Java

RSA Encrypt Randomly Generated AES Key

See more RSA Examples

Demonstrates how to RSA encrypt a randomly generated AES key.

Chilkat Java Downloads

Java
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    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) {
        System.out.println(cert.lastErrorText());
        return;
        }

    CkPublicKey pubKey = new CkPublicKey();
    cert.GetPublicKey(pubKey);

    CkRsa rsa = new CkRsa();
    success = rsa.UsePublicKey(pubKey);
    if (success == false) {
        System.out.println(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) {
        System.out.println(rsa.lastErrorText());
        return;
        }

    // Return the result as a base64 string
    String encryptedAesKey = bdAesKey.getEncoded("base64");

    System.out.println("encrypted AES key = " + encryptedAesKey);
  }
}