title: Encrypt and decrypt with MachineKey in C#
body: <p>I'm trying to encrypt and decrypt Id with MachineKey.</p>
  
  <p>Here is my code that calls the encrypt and decrypt functions:</p>
  
  <pre><code> var encryptedId = Encryption.Protect(profileId.ToString(), UserId);
   var decryptedId = Encryption.UnProtect(encryptedId, UserId);
  </code></pre>
  
  <p>Here is the functions:</p>
  
  <pre><code>public static string Protect(string text, string purpose)
  {
      if(string.IsNullOrEmpty(text))
      {
          return string.Empty;
      }
  
      byte[] stream = Encoding.Unicode.GetBytes(text);
      byte[] encodedValues = MachineKey.Protect(stream, purpose);
      return HttpServerUtility.UrlTokenEncode(encodedValues);
  }
  
  public static string UnProtect(string text, string purpose)
  {
      if(string.IsNullOrEmpty(text))
      {
          return string.Empty;
      }
  
      byte[] stream = HttpServerUtility.UrlTokenDecode(text);
      byte[] decodedValues = MachineKey.Unprotect(stream, purpose);
      return Encoding.UTF8.GetString(decodedValues);
  }
  </code></pre>
  
  <p>The input to the <code>Protect</code> method is 15. This results that the encryptedId variable holds the following string: <code>6wOttbtJoVBV7PxhVWXGz4AQVYcuyHvTyJhAoPu4Okd2aKhhCGbKlK_T4q3GgirotfOZYZXke0pMdgwSmC5vxg2</code></p>
  
  <p>To encrypt this, I send this string as a parameter to the <code>UnProtect</code> method.
  The result of the decryption should be 15, but is instead: <code>1\05\0</code></p>
  
  <p>I can't understand why. I have tried to use only integers in this function, but I still have the same problem. The output of the decrypt differs.</p>