P4Connect.Secure.cs #1

  • //
  • guest/
  • anis_sg/
  • perforce_software/
  • p4connect/
  • src/
  • P4Connect/
  • P4Connect/
  • P4Connect.Secure.cs
  • View
  • Commits
  • Open Download .zip Download (2 KB)
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Security;


namespace P4Connect
{
	public class Secure
	{
		// An arbitrary string used to encrypt the password
		static byte[] _Entropy = System.Text.Encoding.Unicode.GetBytes("I like P4Connect and I want to use it");

		/// <summary>
		/// Encrypts a string
		/// </summary>
		public static string EncryptString(string aInput)
		{
			return EncryptSecureString(ToSecureString(aInput));
		}

		/// <summary>
		/// Decrypts a string
		/// </summary>
		public static string DecryptString(string aEncryptedString)
		{
			return ToInsecureString(DecryptSecureString(aEncryptedString));
		}


		// These methods were taken from http://weblogs.asp.net/jgalloway/archive/2008/04/13/encrypting-passwords-in-a-net-app-config-file.aspx
		static string EncryptSecureString(System.Security.SecureString input)
		{
			byte[] encryptedData = System.Security.Cryptography.ProtectedData.Protect(
				System.Text.Encoding.Unicode.GetBytes(ToInsecureString(input)),
				_Entropy,
				System.Security.Cryptography.DataProtectionScope.CurrentUser);
			return System.Convert.ToBase64String(encryptedData);
		}

		static SecureString DecryptSecureString(string encryptedData)
		{
			try
			{
				byte[] decryptedData = System.Security.Cryptography.ProtectedData.Unprotect(
					System.Convert.FromBase64String(encryptedData),
					_Entropy,
					System.Security.Cryptography.DataProtectionScope.CurrentUser);
				return ToSecureString(System.Text.Encoding.Unicode.GetString(decryptedData));
			}
			catch
			{
				return new SecureString();
			}
		}

		static SecureString ToSecureString(string input)
		{
            System.Console.WriteLine("ToSecureString: " + input);
			SecureString secure = new SecureString();
			foreach (char c in input)
			{
				secure.AppendChar(c);
			}
			secure.MakeReadOnly();
			return secure;
		}

		static string ToInsecureString(SecureString input)
		{
			string returnValue = string.Empty;
			System.IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
			try
			{
				returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
			}
			finally
			{
				System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
			}
			return returnValue;
		}
	}
}
# Change User Description Committed
#1 12954 anis_sg Populate -o //guest/perforce_software/p4connect/...
//guest/anis_sg/perforce_software/p4connect/....
//guest/perforce_software/p4connect/src/P4Connect/P4Connect/P4Connect.Secure.cs
#2 12512 Norman Morse Integrate from Dev branch, preparing for Beta3 release
#1 10940 Norman Morse Inital Workshop release of P4Connect.
Released under BSD-2 license