Hi all, I'm not sure what I'm doing wrong but I'm having trouble converting a ByteArray to a string. I've tried various methods and seem to fail in every one of them.
My code is taking a string and running it through HashBasedMessageAuthenticationCode which I think is going fine and in any case is certainly returning a Byte Array which I can print to console. If I convert this to String though, I seem to get a string of the Byte Array rather than a string with the values of the byte array. So rather than "ab" I'm getting "[26, 27]". I'm using this to create a SAS token for a web service.
I've struggled to find examples of any cryptography code in Monkey C so it's taken a while to get to this stage.
equivalent c# code which I'm trying to convert is:
TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
var week = 60 * 60 * 24 * 7;
var expiry = Convert.ToString((int)sinceEpoch.TotalSeconds + week);
string stringToSign = HttpUtility.UrlEncode(textBoxURL.Text) + "\n" + expiry;
HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(textBoxSASKey.Text));
var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
textBoxSASToken.Text = String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}", HttpUtility.UrlEncode(textBoxURL.Text), HttpUtility.UrlEncode(signature), expiry, textBoxSASKeyName.Text);
Monkey C code so far is:
var mySASKey = Application.Properties.getValue("eHSASKey");
var keyConvertOptions = {
:fromRepresentation => StringUtil.REPRESENTATION_STRING_PLAIN_TEXT,
:toRepresentation => StringUtil.REPRESENTATION_BYTE_ARRAY,
:encoding => StringUtil.CHAR_ENCODING_UTF8
};
//Convert SAS Key to Byte Array
var mySASKeyByteArray = StringUtil.convertEncodedString(mySASKey, keyConvertOptions);
//Set up string to convert
//current time
var UTCNow = Time.now().value();
//duration for key to last
var duration = 2678400; //month
var keyExpiry = (UTCNow + duration).toString();
var stringToConvert = Comm.encodeURL(url) + keyExpiry;
var bytesToConvert = StringUtil.convertEncodedString(stringToConvert, keyConvertOptions);
//Set up HMAC (HashBasedMessageAuthenticationCode)
var HMACOptions = {
:algorithm => Cryptography.HASH_SHA256,
:key => mySASKeyByteArray
};
var HMAC = new Cryptography.HashBasedMessageAuthenticationCode(HMACOptions);
//convert the string
HMAC.update(bytesToConvert);
var encryptedBytes = HMAC.digest();
System.println(encryptedBytes.toString());