Sample code for 30+ languages & platforms
Java Requires Chilkat v11.0.0+

RSA Encrypt Randomly Generated AES Key

See more RSA Examples

Demonstrates how to RSA encrypt a randomly generated AES key.

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.BinData;
import com.chilkatsoft.chilkat2.Cert;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Prng;
import com.chilkatsoft.chilkat2.PublicKey;
import com.chilkatsoft.chilkat2.Rsa;

public class ChilkatExample {

    public static void main(String[] args) {
        // 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).
        Prng prng = new Prng();
        BinData bdAesKey = new BinData();
        prng.genRandomBd(32, bdAesKey);

        // Use a public key from a certificate for RSA encryption.
        Cert cert = new Cert();

        try {
            cert.loadFromFile("qa_data/pem/mf_public_rsa.pem");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        PublicKey pubKey = new PublicKey();
        cert.getPublicKey(pubKey);

        Rsa rsa = new Rsa();
        try {
            rsa.usePublicKey(pubKey);

            // RSA encrypt our 32-byte AES key.
            // The contents of bdAesKey are replaced with result of the RSA encryption.
            rsa.encryptBd(bdAesKey, false);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

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

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