3

I have an MVC application and an API, I need to pass a custom credential object from the MVC app to the API for each request. I would like to encrypt the Credentials object and send that in the header of the request to the API.

How can I do that?

I have found tons of articles on how to encrypt a string but none on encrypting an object in a format other than XML.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
RSH
  • 373
  • 1
  • 5
  • 17
  • 1
    Have you thought about using a secure socket (https, etc.) that will encrypt everything for you? If memory serves me right the header is also encrypted on such calls. – Martin Noreke Apr 28 '15 at 16:54
  • You can try using `NewtonSoft.Json` to serialize your object into JSON and then send across any API you want and Deserialize in the API code. – Dhrumil Apr 28 '15 at 16:55
  • @MartinNoreke's answer would be the best if the API supports HTTPS If you do not want to send over HTTPS and if you have control over the work of the API, working with a public/private key pair should do the trick (serialize you object to JSON then encrypt the string using the public key, send to your API, decrypt using the private key, deserialize) – Irwene Apr 28 '15 at 17:44
  • If you have control over the api, consider making a challenge/response handshake that returns an hmac. That way the password is not sent over the network. The hmac ensures the process is only done once per session. – Mattias Åslund Apr 28 '15 at 17:52

3 Answers3

1

Your requirements aren't completely clear, but it sounds like they might be met by JSON Web Tokens. There are a number of libraries for different platforms that will handle the necessary cryptography for you. With JWT, the focus is on the authentication and integrity of the token, rather than secrecy.

If you want to implement your own method, follow the tutorials for encrypting a character string, because JSON is a character string.

erickson
  • 265,237
  • 58
  • 395
  • 493
0
  1. Make your credentials object Serializable.
  2. Serialize your object into a string as described here.
  3. Encrypt the string.

If you insist to use JSON serialization you can use this or this examples.

Community
  • 1
  • 1
motcke
  • 438
  • 6
  • 17
0

The key here is simply to convert your object to a string. As you said you've seen examples of that (encrypting strings). Use json.Net's DeserializeObject method to produce a string, encrypt that string, then just use the add method here; https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers%28v=vs.110%29.aspx to append it to the headers collection.

On the back end you just decrypt, deserialize and move forward.

Note that as pointed out in the comments using something like HTTPS is preferred. Why encrypt yourself then send HTTP when you can use a protocol that does it for you instead?

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115