0

I know very little about Encryption, but my goal is to essentially decrypt strings. I have been given the AES(128) key.

However, I must retrieve the IV from the Encrypted string, which is the first 16 bits.

Heres the doc for salesforce for more information (if what i explained was incorrect)

Encrypts the blob clearText using the specified algorithm and private key. Use this method when you want Salesforce to generate the initialization vector for you. It is stored as the first 128 bits (16 bytes) of the encrypted blob

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_restful_crypto.htm (encryptWithManagedIV)

For Retrieving the IV I've tried something like this (I don't believe it's right though):

public string retrieveIv()
        {
            string iv = "";
            string input = "bwZ6nKpBEsuAKM8lDTYH1Yl69KkHN1i3XehALbfgUqY=";
            byte[] bytesToEncode = Encoding.UTF8.GetBytes(input);

            for(int i = 0; i <= 15; i++){
                iv += bytesToEncode[i].ToString(); ;
            }

            return iv;
        }

(Just ignore the fact that the input is hardcoded and not parameterized; easier for testing purposes)

Then use the Best answer from this question to decrypt the string

Community
  • 1
  • 1
Adam Sweeney
  • 386
  • 3
  • 15

1 Answers1

3

The IV shouldn't be expressed as a string - it should be as a byte array, as per the AesManaged.IV property.

Also, using Encoding.UTF8 is almost certainly wrong. I suspect you want:

public static byte[] RetrieveIv(string encryptedBase64)
{
    // We don't need to base64-decode everything... just 16 bytes-worth
    encryptedBase64 = encryptedBase64.Substring(0, 24);

    // This will be 18 bytes long (4 characters per 3 bytes)
    byte[] encryptedBinary = Convert.FromBase64String(encryptedBase64);
    byte[] iv = new byte[16];

    Array.Copy(encryptedBinary, 0, iv, 0, 16);
    return iv;
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @Richard: You've got it the wrong way round: it takes 4 characters within base64 to store 3 bytes. Usually, encrypted data is converted to text using base64. A char is most certainly *not* equal to a byte. – Jon Skeet May 24 '12 at 19:02
  • @JonSkeet .. shouldn't that be? byte[] iv = new byte[15]; .. it needs to be 16 bytes array so if you put in 16, it will be 17 bytes array starting from 0, isn't? – Laurence Jun 27 '13 at 09:46
  • 1
    @LaurenceNyein: No, that's not how arrays in C# work. You ask for a 16 byte array, you get a 16 byte array. – Jon Skeet Jun 27 '13 at 09:47