Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert NSData to base64encoded AND a byte array in C#

I'm implementing in-app purchasing for our iOS app for various auto-renewable subscriptions. When the payment is complete we need to send the transaction information to our server (cloud) to record the information so that we can verify the receipt on a set interval to make sure the subscription is valid, not cancelled/refunded, or renewed. We are going to make the JSON calls from the server on a set interval to do this via the in-app purchasing guide and our shared secret, have yet to get to that but before we do we need to have the relevant data from the purchase, i.e. the TransactionReceipt which is an NSData object.

We want to send two parameters to our web service for the TransactionReceipt (among other items such as the ProductID purchased, etc.). We want to send this as a base64encoded value which is what we believe needs to be sent in the JSON request for validation, so we'll store that in SQL Server.

HOw, using MonoTouch / C# can we convert the NSData "TransactionReceipt" to base64encoded and also a byte[]?

Thank you.

like image 536
Neal Avatar asked May 16 '12 16:05

Neal


People also ask

How to convert byte array to base-64 string?

You could use the String Convert. ToBase64String(byte[]) to encode the byte array into a base64 string, then Byte[] Convert. FromBase64String(string) to convert the resulting string back into a byte array.

Is byte array and Base64 same?

It provides exact same functions as java. util. Base64 . That's all about how to convert Byte Array to Base64 String in java.

How to convert ToBase64String?

ToBase64String(Byte[], Int32, Int32) Converts a subset of an array of 8-bit unsigned integers to its equivalent string representation that is encoded with base-64 digits. Parameters specify the subset as an offset in the input array, and the number of elements in the array to convert.

What is convert FromBase64String?

Converts the specified string, which encodes binary data as base-64 digits, to an equivalent 8-bit unsigned integer array. public: static cli::array <System::Byte> ^ FromBase64String(System::String ^ s);


1 Answers

There's two easy way to get data out of NSData, using a Stream or the Bytes and Length properties. The stream version would look like:

public byte[] ToByte (NSData data)
{
    MemoryStream ms = new MemoryStream ();
    data.AsStream ().CopyTo (ms);
    return ms.ToArray ();
}

the Bytes and Length version would be:

public byte[] ToByte (NSData data)
{
    byte[] result = new byte[data.Length];
    Marshal.Copy (data.Bytes, result, 0, (int) data.Length);
    return result;
}

Getting the base64 output string remains identical:

public string ToBase64String (NSData data)
{
    return Convert.ToBase64String (ToByte (data));
}
like image 111
poupou Avatar answered Sep 28 '22 00:09

poupou