I use the following code to generate a key and then use it to encrypt a simple string message. The output of the function Encrypt is an encrypted object. But I would rather convert this into binary digits (a long sequence of zeros and ones). Unfortunately, I am not able to do so. I tried to use the function IntegerDigits[] but that did not work. Thanks in advance!

key = GenerateSymmetricKey[];
message = "Hello world";
Encrypt[key, message]
  • $\begingroup$ Is this what you are after? Encrypt[key, message]["Data"] // Normal // IntegerDigits[#, 2, 8] & // Flatten $\endgroup$
    – Kuba
    Oct 21, 2017 at 10:44
  • $\begingroup$ Thanks for the prompt reply! Well, yes that is what I am after. But then after the conversion to binary digits, how may I take back those same digits and decrypt them? Apparently, the Decrypt[] function is also expecting an encrypted object, not a sequence of binary digits. $\endgroup$ Oct 21, 2017 at 11:57

1 Answer 1


I will turn Kuba's comment into an answer. The EncryptedObject you create using Encrypt contains the encrypted data and the initialization vector of the encryption method as a ByteArray. These can be turned into an array of digits using Normal and IntegerDigits.

key = GenerateSymmetricKey[];
message = "Hello world";
eobj = Encrypt[key, message];
bin = eobj["Data"] // Normal // IntegerDigits[#, 2, 8] & // Flatten;
initvec = 
  eobj["InitializationVector"] // Normal // IntegerDigits[#, 2, 8] & // Flatten;

Now you send bin and initvec to the receiver (or do what ever else you wanted to do with the binary digits). To decrypt the message you can create a new EncryptedObject and decrypt it:

eobj2 = EncryptedObject[Association[
     "Data" -> ByteArray[(FromDigits[#1, 2] & ) /@ ArrayReshape[bin, {16, 8}]], 
     "InitializationVector" -> ByteArray[(FromDigits[#1, 2] & ) /@ 
           ArrayReshape[initvec, {16, 8}]], 
     "OriginalForm" -> String]];
Decrypt[key, eobj2]

Note that I used ByteArray, FromDigits, and ArrayReshape to reverse Kuba's Normal, IntegerDigits and Flatten, respectively.

  • $\begingroup$ Thank you for your help! $\endgroup$ Oct 23, 2017 at 9:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.