Android™
Android™
Encrypt a JWE with a Recipient Public Key
See more JSON Web Encryption (JWE) Examples
Demonstrates Jwe.SetPublicKey, which sets the public key used to encrypt for a recipient. The example uses RSA-OAEP-256 key management with AES-256-GCM content encryption.
The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.
Background. In public-key JWE, the content-encryption key is wrapped for the recipient using their public key, so only the holder of the matching private key can decrypt.
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;
CkJwe jwe = new CkJwe();
// Protected header: RSA-OAEP-256 key management with AES-256-GCM content encryption.
CkJsonObject header = new CkJsonObject();
header.UpdateString("alg","RSA-OAEP-256");
header.UpdateString("enc","A256GCM");
success = jwe.SetProtectedHeader(header);
if (success == false) {
Log.i(TAG, jwe.lastErrorText());
return;
}
// The file path is relative to the application's current working directory. An absolute path
// may also be used. Supply the path appropriate to your own environment.
// Load the recipient's public key.
CkPublicKey pubKey = new CkPublicKey();
success = pubKey.LoadFromFile("qa_data/recipient_pubkey.pem");
if (success == false) {
Log.i(TAG, pubKey.lastErrorText());
return;
}
// Set the public key used to encrypt for recipient 0.
success = jwe.SetPublicKey(0,pubKey);
if (success == false) {
Log.i(TAG, jwe.lastErrorText());
return;
}
String jweCompact = jwe.encrypt("This is the secret content.","utf-8");
if (jwe.get_LastMethodSuccess() == false) {
Log.i(TAG, jwe.lastErrorText());
return;
}
Log.i(TAG, jweCompact);
}
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."
}
}