How to convert a memory block to a string?

Hello all,

I am trying to encrypt a string, then from the memory block output the encrypted string to a String.

This is the code that I have been working with. Can anyone please tell me where I’m messing up?

Thanks!
Tim

Dim AuthToken As String = trim(fldAuthToken.Text)

Dim L As Integer = Len(AuthToken)
Dim msg As New MemoryBlock(L)  //(14)
msg.StringValue(0, L) = AuthToken   //kMessage

// Encrypt msg using the publicKey
Dim encryptedData As MemoryBlock = Crypto.RSAEncrypt(msg, publicKey)

// If encryptedData <> Nil Then MsgBox("Successfully encrypted.")

// Dim EncryptedToken As String = encryptedData.

Dim s As String = encryptedData.StringValue   // .StringValue(0, L)
// Dim s As String = decryptedData.StringValue(0, L))

Are you trying to change the data type of the variable to String, or to encode the binary data as printable text?

The difference between Crypto and other environments is that Crypto retuns the raw bytes, where most other enviros expect the bytes to be encoded as Andrew hinted at. Before you can exchange the string with a website or compare it to a value you get from the outside, you will need to encode it and possibly even format it.

1 Like

Agree with @Tim_Hare , you probably need to base64 encode it afterwards:

s = EncodeBase64(s,0) // 0 prevents line wrap

Because you can convert between String and MemoryBlock through simple assignment, your original code can be simplified to this:

Dim s As String = Crypto.RSAEncrypt(AuthToken, publicKey)

If there is a problem encrypting, you will get a CryptoException, so the whole thing including the suggestions above could look like this:

Dim AuthToken As String = trim(fldAuthToken.Text)

Dim s As String
Try
  s = Crypto.RSAEncrypt(AuthToken, publicKey)
  Return EncodeBase64(s, 0)
Catch err As CryptoException
  // Deal with it
End Try

Thank you all.

Much appreciated. I have another question on Crypto but will start a new thread.

Tim