question

key-holder avatar image
key-holder asked

WebException: Error writing request: The authentication or decryption has failed.

Hi, I use Unity version 5.5

I confirmed that the file upload was working last week, and I did not modify the script.

But now the file is not uploaded.

The upload was working a few days ago, but suddenly it did not work. And the next day, it worked again.

I do not know the cause. The same error always appears.

WebException: Error writing request: The authentication or decryption has failed. System.Net.WebConnectionStream.WriteHeaders () System.Net.WebConnectionStream.SetHeaders (System.Byte[] buffer) (wrapper remoting-invoke-with-check) System.Net.WebConnectionStream:SetHeaders (byte[]) System.Net.HttpWebRequest.SendRequestHeaders (Boolean propagate_error) UnityEngine.Debug:LogException(Exception) PlayFab.Internal.<MakeApiCall>c__AnonStorey1:<>m__0(String) (at Assets/PlayFabSdk/Shared/Internal/PlayFabHttp/PlayFabWWW.cs:137) PlayFab.Internal.<Post>c__Iterator0:MoveNext() (at Assets/PlayFabSdk/Shared/Internal/PlayFabHttp/PlayFabWWW.cs:199) UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)

using UnityEngine;
using System.Collections;
using System.IO;
using System.Net;
using System.Text;
using PlayFab;
using PlayFab.AdminModels;
using PlayFab.ClientModels;
using UnityEngine.UI;
using System;
using System.Collections.Generic;


/// <summary>
/// The out of the box WWW Unity3d class does not afford compatable PUT capability with AWS
/// This class provides a simple example for how to upload files to PlayFab's content service using .NET's built-in HttpWebRequest.
///
/// Scenario: I have a file (UB_Icon.png) located in my /Assets/StreamingAssets project folder that I need to upload to the PlayFab content service and download at a later time for use within my client.
/// </summary>
public class UploadToPlayFabContentService : MonoBehaviour {
	private SaveData sd;
	private Share_DynamicScroll ds;
	public ShareButton sb;
//	public GameObject waitPanel;
//	public GameObject PopUpCanvas;
	
	
	//private string testPngFileName = "testimg.png"; // The name of the file to send
	private string mineType = "image/png"; // The MIME type that corresponds to the file above
	public string contentKey = ""; // this is the location and 'identifier' for your uploaded file, you will need this key to access the file after uploading
	
	//private string assetPath = ""; // The assetPath where the file can be found (will varry depending on the platform)
	public Texture2D downloadedImage; // We are storing the downloaded file in a Texture2D as a simple example of the service
	private Texture2D uploadedImage;
	public bool isImageDownloaded = false;
	private bool isImageUploaded = false;
	
	public Text statusText;
	// Use this for initialization
	void Start () {
		sd = GameObject.Find("SaveAllData").GetComponent("SaveData") as SaveData;
		downloadedImage = sd.MainAvatarHeadTexture;
		uploadedImage = (Texture2D)Resources.Load("userImg");
		try{
			ds = GameObject.Find("Canvas").GetComponent("Share_DynamicScroll") as Share_DynamicScroll;
		}catch(Exception e){
			Debug.Log(e.ToString());
		}
	} 
/*	public void resetContentKey(){
		//Sign judgment
		if (sd.CustomAccountID != "") {
			contentKey = "UserFace/"+sd.userName+".png";
			uploadedImage = sd.MainAvatarHeadTexture;
			Debug.Log(contentKey);
		}
	} */
	public void resetDownContentKey(String name){
		if (name != "") {
//			ds.getContentKey(name);
			contentKey = name;
			Debug.Log(contentKey);
		}
	}
	
	private void UpdateStatus(string status)
	{
		if (statusText != null)
		{
			statusText.text = String.Format("Status: {0}", status);
		}
	}
	/// <summary>
	/// Gets the reletive file path; works acrocss Unity build targets (Web, iOS, Android, PC, Mac) 
	/// </summary>
	/// <returns> The assetPath where the file can be found (will varry depending on the platform) </returns>
	/*
   IEnumerator GetFilePath()
   {
      string streamingAssetPath = Application.streamingAssetsPath;
      string filePath = System.IO.Path.Combine(streamingAssetPath, testPngFileName);
      if (filePath.Contains("://")) 
      {
         WWW www = new WWW(filePath);
         yield return www;
         this.assetPath = www.text;
      } 
      else
      {
         this.assetPath = filePath;
      }
   }*/
	public string[] sharenamelist;
	public void GetContentListURL(){
		Debug.Log ("GetContentListURL");
		bool isdownlist = false;
		PlayFab.AdminModels.GetContentListRequest request = new PlayFab.AdminModels.GetContentListRequest ()
		{
			Prefix = ""//접두사. 지정된 접두어로 시작하는 키에 대한 응답을 제안한다.
		};
		
		PlayFabAdminAPI.GetContentList(request,(result) => {
			Debug.Log("GetContentListURL");
			Debug.Log(result.ItemCount);
			sharenamelist = new String[result.ItemCount];
			
			if ((result.ItemCount == 0))  // 공유된 파일이 존재하지 않을 때
			{
				Debug.Log("No cuntent");
				Transform noshared = GameObject.Find("Canvas").transform.FindChild("NoShare");
				noshared.gameObject.SetActive(true);
			}
			else
			{
				int i=0;
				foreach (var item in result.Contents)
				{
					sharenamelist[i] = item.Key;
					Debug.Log(item.Key);
					i++;
				}
				ds.resetList();
				ds.addNewList();
			}
		}, (error) => {
			Debug.Log("GetUserData Fail");
			Debug.Log(error.ErrorMessage);
		});
	}


	public void userUpload(Texture2D head, String name, int dance, int accessory){
		uploadedImage = head;
		try{
			this.isImageUploaded = false;
			//Debug.Log(string.Format("File: {0}",assetPath));
			GetContentUploadURL(head, contentKey);
		}catch(IOException e){
			//return false;
			string debuglog = e.StackTrace;
			Debug.Log (debuglog);
			Debug.Log("up false");
			UpdateStatus("up false");
		}
		
		//return this.isImageUploaded;
		Debug.Log("up " + isImageUploaded.ToString());
		UpdateStatus ("up " + isImageUploaded.ToString());
	}




	public void userDownload(String name){
		Debug.Log ("userDownload name : " + name);
		resetDownContentKey (name);
		this.isImageDownloaded = false;
		GetContentDownloadURL();
		//return downloadedImage;
		sd.MainAvatarHeadTexture = downloadedImage;
		//UpdateStatus("down "+isImageDownloaded.ToString());
	}






	/*
   void OnGUI()
   {
      if(GUI.Button(new Rect(Screen.width /2 - 100, Screen.height/2 - 50,200, 100), "TEST UPLOAD"))
      {
         this.isImageUploaded = false;
         this.isImageDownloaded = false;
         Debug.Log(string.Format("File: {0}",assetPath));
         GetContentUploadURL();
      }
      
      if(this.isImageUploaded == true)
      {
         if(this.isImageDownloaded == false)
         {
            if(GUI.Button(new Rect(Screen.width /2 - 100, Screen.height/2 + 50,200, 100), "TEST DOWNLOAD"))
            {
               GetContentDownloadURL();
            }
         }
         else
         {
            if(GUI.Button(new Rect(Screen.width /2 - 100, Screen.height/2 + 50,200, 100), this.downloadedImage))
            {
               Debug.Log("Demo Complete!");
            }
         }
      }
   }
*/
	
	/// <summary>
	/// Requests a remote endpoint for uploads from the PlaFab service.
	/// </summary>
	void GetContentUploadURL(Texture2D head, String name)
	{
		GetContentUploadUrlRequest request = new GetContentUploadUrlRequest();
		
		request.Key = this.contentKey; // folder location & file name to use on the remote server
		request.ContentType = this.mineType; // mime type to match the file
		
		PlayFabAdminAPI.GetContentUploadUrl(request, OnGetContentUploadURLSuccess, OnPlayFabError);
	}
	
	
	
	/// <summary>
	/// Called after a successful GetContentUploadUrl request
	/// </summary>
	/// <param name="result"> GetContentUploadUrlRequest details </param>
	void OnGetContentUploadURLSuccess(GetContentUploadUrlResult result)
	{
		Debug.Log(string.Format("Endpoint URL Recieved: {0}", result.URL));
		//byte[] fileContents = File.ReadAllBytes(assetPath);
		byte[] fileContents = uploadedImage.EncodeToPNG();
		Debug.Log ("endoce PNG");
		PutFile(result.URL, fileContents);
		Debug.Log ("PutFile");


	}
	
	/// <summary>
	/// Requests a remote endpoint for downloads from the PlaFab service.
	/// </summary>
	void GetContentDownloadURL()
	{
		/* Developer Note:
 To test this script in isolation ( i.e. running in a project without a login) 
 Use this is a shortcut for accessing client API calls
 */


		// PlayFabClientAPI.AuthKey = "Paste your valid AuthKey here (returned from any PlayFab login API call)";
		GetContentDownloadUrlRequest request = new GetContentDownloadUrlRequest ();
		request.Key = this.contentKey;
		PlayFabClientAPI.GetContentDownloadUrl (request, OnGetContentDownloadURLSuccess, OnPlayFabError);
	}


	/// <summary>
	/// Called after a successful GetContentUploadUrl request
	/// </summary>
	/// <param name="result"> GetContentUploadUrlRequest details </param>
	void OnGetContentDownloadURLSuccess(GetContentDownloadUrlResult result)
	{
		
		Debug.Log(string.Format("Endpoint URL Recieved: {0}", result.URL));
		StartCoroutine(GetFile(result.URL));
//		GetFile (result.URL);
		Debug.Log ("down success.....");


	}
	/// <summary>
	/// Called after a failed GetContentUploadUrl request
	/// </summary>
	/// <param name="result">Error details</param>
	void OnPlayFabError(PlayFabError error)
	{
		Debug.LogWarning(string.Format("ERROR: [{0}] -- {1}", error.Error, error.ErrorMessage));
	}
	
	/// <summary>
	/// Puts the file.
	/// </summary>
	/// <param name="postUrl">Remote URL to use (obtained from GetContentUploadUrl) </param>
	/// <param name="payload">The file to send converted to a byte[] </param>
	public void PutFile(string putURL, byte[] payload)
	{
		var request = (HttpWebRequest)WebRequest.Create(putURL);
		request.Method = "PUT";
		request.ContentType = this.mineType;
		if (payload != null)
		{
			Stream dataStream = request.GetRequestStream();
			dataStream.Write(payload, 0, payload.Length);
			dataStream.Close();
		}
		else
		{
			Debug.LogWarning(string.Format("ERROR: Byte arrry was empty or null"));
			return;
		}
		Debug.Log("Starting HTTP PUT...");
		HttpWebResponse response = (HttpWebResponse)request.GetResponse();
		if(response.StatusCode == HttpStatusCode.OK)
		{
			Debug.Log("...HTTP PUT Successful");
			this.isImageUploaded = true;
			sb.closePopup();
//			waitPanel.SetActive(false);
//			PopUpCanvas.SetActive(false);
		}
		else
		{
			Debug.LogWarning(string.Format("ERROR: [{0}] -- {1}", response.StatusCode, response.StatusDescription));
		}
	}
	/// <summary>
	/// Gets the file from the PlayFab content service.
	/// </summary>
	/// <param name="getURL">The URL location of the file</param>


	public IEnumerator GetFile(string getURL)
	{
		// Start a download of the given URL
		var www = new WWW(getURL);


		// wait until the download is done
		yield return www;
		Debug.Log("...HTTP GET Successful");


		this.downloadedImage.LoadImage(www.bytes);
		this.isImageDownloaded = true;
	}
}
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
brendan avatar image
brendan answered

Is this the same machine you were using in previous attempts? That error ("authentication or decryption has failed") is actually a system-level exception. It may indicate an issue with the local machine's certificates, though it's also possible this is simply a transient network issue. If you're getting this consistently, can you check to see if anything has changed in your network configuration - firewalls, ISP configuration changes, etc.?

4 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

key-holder avatar image key-holder commented ·

I always run the project on the same device. What does it mean indicate an issue with the local machine's certificates? I'm sorry, but I don't know about network configuration. How should I check?

0 Likes 0 ·
brendan avatar image brendan key-holder commented ·

Basically, it means that there may be something which has changed at a low level on your local network. The best way to track this down would likely be by getting a Wireshark capture of the communications. Since you'll want to have all the details of the packets, it would be best to follow the guidance in this doc: https://wiki.wireshark.org/SSL

0 Likes 0 ·
key-holder avatar image key-holder brendan commented ·

Thank you for your link. I did not understand because I was a beginner. sorry. Maybe could this be due to the difference in version of playfab?

0 Likes 0 ·
Show more comments

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.