Set the Encryption Context ID in Script

A function, setContextID, is provided to set the encryption context ID of an encrypted field in script.

The argument to the function is the sys_id of the encryption context you wish to use. The following example creates records with an encrypted field, u_subspecies, encrypted by the "Species Security" encryption context.

Note: The user who runs this script must have access to the encryption context.
function encrypt() {
  var encryptionID = getEncryptionID("Species Security");
  if (encryptionID == "")
   createEncryptedRecord("Sumatran tiger", "Panthera", "tigris", "sumatrae", encryptionID);
   createEncryptedRecord("Bengal tiger", "Panthera", "tigris", "tigris", encryptionID);
   createEncryptedRecord("Siberian tiger", "Panthera", "tigris", "altaica", encryptionID);
function getEncryptionID(encryptionName) {
   var contextGR = new GlideRecord("sys_encryption_context");
   contextGR.addQuery("name", encryptionName);
   if (! {
      gs.log("*********** No such encryption context " + encryptionContextName);
      return "";
   return contextGR.getUniqueValue();
function createEncryptedRecord(commonName, genus, species, subspecies, encryptionID) { 
   var newRecord = new GlideRecord("u_species_encrypted");
   newRecord.u_common_name = commonName;
   newRecord.u_genus = genus;
   newRecord.u_species = species;
   // We have one encrypted field, u_subspecies. 
   newRecord.u_subspecies.setContextID(encryptionID); // use our encryption context for the field