How to return encrypted stream in web api?

2019-08-26 19:49发布

I have a JSON string that I need to return it as an encrypted stream in web api in HttpResponseMessage. The client then receives the encrypted stream and decrypts it like this.

private string str(HttpWebResponse AStream)
{
    string result;
    using (Stream responseStream = AStream.GetResponseStream())
    {
        result = DecryptAesStream(responseStream, Key);
        return result;
    }
}

Do I need to encrypt the JSON string first, load it to a filestream but then how do I return it in HttpRepsonseMessage since it takes string as a content? Any hints what I need to do?

1条回答
姐就是有狂的资本
2楼-- · 2019-08-26 20:32

You can try something like this

        public byte[] GetEncryptedStream(string jsonData)
        {
            byte[] dataBytes = System.Text.Encoding.UTF8.GetBytes(jsonData);
            byte[] key = null;//GetKey() //I am assuming you arealy have your Key
            //Call your encrypt function below
            byte[] encryptedDataBytes = encrypt(dataBytes, key); // I am assuming your function returns byte array 
            return encryptedDataBytes;
        }

        public HttpResponseMessage GetHttpResponseMessage()
        {
            var result = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
            String jsonString = "your json data";
            byte[] data = GetEncryptedStream(jsonString);
            result.Content = new ByteArrayContent(data);
            return result;
        }
查看更多
登录 后发表回答