예제 #1
1
        public int EncryptDataToStream(byte[] buffer, byte[] entropy, DataProtectionScope scope, Stream stream)
        {
            if (buffer.Length <= 0)
                throw new ArgumentException("Buffer");
            if (buffer == null)
                throw new ArgumentNullException("buffer");
            if (entropy.Length <= 0)
                throw new ArgumentException("Entropy");
            if (entropy == null)
                throw new ArgumentNullException("entropy");
            if (stream == null)
                throw new ArgumentNullException("stream");

            var length = 0;

            // Encrypt the data in memory. The result is stored in the same same array as the original data.
            var encrptedData = ProtectedData.Protect(buffer, entropy, scope);

            // Write the encrypted data to a stream.
            if (stream.CanWrite)
            {
                stream.Write(encrptedData, 0, encrptedData.Length);
                length = encrptedData.Length;
            }

            // Return the length that was written to the stream.
            return length;
        }
예제 #2
0
        public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtectionScope scope)
        {
            if (userData == null)
                throw new ArgumentNullException(nameof(userData));

            return ProtectOrUnprotect(userData, optionalEntropy, scope, protect: true);
        }
예제 #3
0
		/// <overloads>
		/// Reads an encrypted key from an input stream. This method is not intended to allow keys to be transferred
		/// from another machine.
		/// </overloads>
		/// <summary>
		/// Reads an encrypted key from an input stream. This method is not intended to allow keys to be transferred
		/// from another machine.
		/// </summary>
		/// <param name="inputStream"><see cref="Stream"/> from which DPAPI-protected key is to be read.</param>
		/// <param name="dpapiProtectionScope"><see cref="DataProtectionScope"/> used to protect the key on disk. </param>
		/// <returns>Key read from stream, encapsulated in a <see cref="ProtectedKey"></see>.</returns>
		public static ProtectedKey Read(Stream inputStream, DataProtectionScope dpapiProtectionScope)
		{
			IKeyReader reader = new KeyReaderWriter();
			ProtectedKey key = reader.Read(inputStream, dpapiProtectionScope);

			return key;
		}
예제 #4
0
        public static int EncryptDataToStream(byte[] Buffer, byte[] Entropy, DataProtectionScope Scope, Stream S)
        {
            if (Buffer.Length <= 0)
                throw new ArgumentException("Buffer");
            if (Buffer == null)
                throw new ArgumentNullException("Buffer");
            if (Entropy.Length <= 0)
                throw new ArgumentException("Entropy");
            if (Entropy == null)
                throw new ArgumentNullException("Entropy");
            if (S == null)
                throw new ArgumentNullException("S");

            int length = 0;

            // Encrypt the data in memory. The result is stored in the same same array as the original data.
            byte[] encrptedData = ProtectedData.Protect(Buffer, Entropy, Scope);

            // Write the encrypted data to a stream.
            if (S.CanWrite && encrptedData != null)
            {
                S.Write(encrptedData, 0, encrptedData.Length);

                length = encrptedData.Length;
            }

            // Return the length that was written to the stream. 
            return length;

        }
예제 #5
0
        private static byte[] ProtectOrUnprotect(byte[] inputData, byte[] optionalEntropy, DataProtectionScope scope, bool protect)
        {
            unsafe
            {
                fixed (byte* pInputData = inputData, pOptionalEntropy = optionalEntropy)
                {
                    DATA_BLOB userDataBlob = new DATA_BLOB((IntPtr)pInputData, (uint)(inputData.Length));
                    DATA_BLOB optionalEntropyBlob = default(DATA_BLOB);
                    if (optionalEntropy != null)
                    {
                        optionalEntropyBlob = new DATA_BLOB((IntPtr)pOptionalEntropy, (uint)(optionalEntropy.Length));
                    }

                    // For desktop compat, we ignore unknown bits in the "scope" value rather than throwing.
                    CryptProtectDataFlags flags = CryptProtectDataFlags.CRYPTPROTECT_UI_FORBIDDEN;
                    if (scope == DataProtectionScope.LocalMachine)
                    {
                        flags |= CryptProtectDataFlags.CRYPTPROTECT_LOCAL_MACHINE;
                    }

                    DATA_BLOB outputBlob = default(DATA_BLOB);
                    try
                    {
                        bool success = protect ?
                            Interop.Crypt32.CryptProtectData(ref userDataBlob, null, ref optionalEntropyBlob, IntPtr.Zero, IntPtr.Zero, flags, out outputBlob) :
                            Interop.Crypt32.CryptUnprotectData(ref userDataBlob, IntPtr.Zero, ref optionalEntropyBlob, IntPtr.Zero, IntPtr.Zero, flags, out outputBlob);
                        if (!success)
                        {
                            int lastWin32Error = Marshal.GetLastWin32Error();
                            if (protect && ErrorMayBeCausedByUnloadedProfile(lastWin32Error))
                                throw new CryptographicException(SR.Cryptography_DpApi_ProfileMayNotBeLoaded);
                            else
                                throw lastWin32Error.ToCryptographicException();
                        }

                        // In some cases, the API would fail due to OOM but simply return a null pointer.
                        if (outputBlob.pbData == IntPtr.Zero)
                            throw new OutOfMemoryException();

                        int length = (int)(outputBlob.cbData);
                        byte[] outputBytes = new byte[length];
                        Marshal.Copy(outputBlob.pbData, outputBytes, 0, length);
                        return outputBytes;
                    }
                    finally
                    {
                        if (outputBlob.pbData != IntPtr.Zero)
                        {
                            int length = (int)(outputBlob.cbData);
                            byte* pOutputData = (byte*)(outputBlob.pbData);
                            for (int i = 0; i < length; i++)
                            {
                                pOutputData[i] = 0;
                            }
                            Marshal.FreeHGlobal(outputBlob.pbData);
                        }
                    }
                }
            }
        }
예제 #6
0
        public static byte[] Unprotect(byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope)
        {
            if (encryptedData == null)
                throw new ArgumentNullException(nameof(encryptedData));

            return ProtectOrUnprotect(encryptedData, optionalEntropy, scope, protect: false);
        }
예제 #7
0
// FIXME	[DataProtectionPermission (SecurityAction.Demand, UnprotectData = true)]
		public static byte[] Unprotect (byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope) 
		{
			if (encryptedData == null)
				throw new ArgumentNullException ("encryptedData");

			// on Windows this is supported only under 2000 and later OS
			Check (scope);

			switch (impl) {
#if !MOBILE
			case DataProtectionImplementation.ManagedProtection:
				try {
					return ManagedProtection.Unprotect (encryptedData, optionalEntropy, scope);
				}
				catch (Exception e) {
					string msg = Locale.GetText ("Data unprotection failed.");
					throw new CryptographicException (msg, e);
				}
			case DataProtectionImplementation.Win32CryptoProtect:
				try {
					return NativeDapiProtection.Unprotect (encryptedData, optionalEntropy, scope);
				}
				catch (Exception e) {
					string msg = Locale.GetText ("Data unprotection failed.");
					throw new CryptographicException (msg, e);
				}
#endif
			default:
				throw new PlatformNotSupportedException ();
			}
		}
 /// <summary>
 /// <para>Initializes a new instance of <see cref="SymmetricAlgorithmProviderData"/> class.</para>
 /// </summary>
 /// <param name="name"><para>The name for the provider.</para></param>
 /// <param name="algorithmType"><para>The type name of the hash algorithm.</para></param>
 /// <param name="protectedKeyFilename">File name where key is stored</param>
 /// <param name="protectedKeyProtectionScope">DPAPI protection scope used to store key</param>
 public SymmetricAlgorithmProviderData(string name, Type algorithmType, string protectedKeyFilename, DataProtectionScope protectedKeyProtectionScope)
     : base(name, typeof(SymmetricAlgorithmProvider))
 {
     AlgorithmType = algorithmType;
     ProtectedKeyProtectionScope = protectedKeyProtectionScope;
     ProtectedKeyFilename = protectedKeyFilename;
 }
예제 #9
0
 ProtectedKey GenerateKey(KeyedHashAlgorithm algorithm, DataProtectionScope dataProtectionScope)
 {
     using (algorithm)
     {
         return ProtectedKey.CreateFromPlaintextKey(algorithm.Key, dataProtectionScope);
     }
 }
예제 #10
0
        public byte[] DecryptDataFromStream(byte[] entropy, DataProtectionScope scope, Stream stream, int length)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");
            if (length <= 0)
                throw new ArgumentException("Length");
            if (entropy == null)
                throw new ArgumentNullException("entropy");
            if (entropy.Length <= 0)
                throw new ArgumentException("Entropy");

            var inBuffer = new byte[length];
            byte[] outBuffer;

            // Read the encrypted data from a stream.
            if (stream.CanRead)
            {
                stream.Read(inBuffer, 0, length);
                outBuffer = ProtectedData.Unprotect(inBuffer, entropy, scope);
            }
            else
            {
                throw new IOException("Could not read the stream.");
            }

            // Return the length that was written to the stream.
            return outBuffer;
        }
		/// <summary>
		/// <para>Initialize a new instance of the <see cref="DpapiSymmetricCryptoProvider"/></para>
		/// </summary>
		/// <param name="scope"><para>One of the <see cref="DataProtectionScope"/> values.</para></param>
		/// <param name="entropy"><para>The entropy to salt the phrase.</para></param>
        /// <param name="instrumentationProvider">Instrumentation provider to use.</param>
		public DpapiSymmetricCryptoProvider(DataProtectionScope scope, byte[] entropy, ISymmetricAlgorithmInstrumentationProvider instrumentationProvider)
		{
            if (instrumentationProvider == null) throw new ArgumentNullException("instrumentationProvider");

			this.protectionScope = scope;
			this.entropy = entropy;
            this.instrumentationProvider = instrumentationProvider;
		}
 public static string Unprotect(string encryptedText, string optionalEntropy = null, DataProtectionScope scope = DataProtectionScope.CurrentUser)
 {
     if (encryptedText == null)
         return ""; // if there is no text, then return an empty string
     byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
     string clearString = GetUnprotectedStringFromBytes(encryptedBytes, optionalEntropy, scope);
     return clearString;
 }
 public static string GetUnprotectedStringFromBytes(byte[] encryptedBytes, string optionalEntropy = null, DataProtectionScope scope = DataProtectionScope.CurrentUser)
 {
     byte[] entropyBytes = string.IsNullOrEmpty(optionalEntropy)
         ? null
         : Encoding.UTF8.GetBytes(optionalEntropy);
     byte[] clearBytes = ProtectedData.Unprotect(encryptedBytes, entropyBytes, scope);
     return Encoding.UTF8.GetString(clearBytes);
 }
예제 #14
0
		public static byte[] Unprotect (byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope) 
		{
			if (encryptedData == null)
				throw new ArgumentNullException ("encryptedData");

			// on Windows this is supported only under 2000 and later OS
			throw new PlatformNotSupportedException ();
		}
예제 #15
0
        public static byte[] Protect(byte[] userData, byte[] optionalEntropy,
			DataProtectionScope scope)
        {
            byte[] pb = new byte[userData.Length];
            Array.Copy(userData, pb, userData.Length);
            ProtectedMemory.Protect(pb, MemoryProtectionScope.SameProcess);
            return pb;
        }
예제 #16
0
        public static string Protect(this string plainText, DataProtectionScope scope = DataProtectionScope.LocalMachine, byte[] entropy = null)
        {
            if (plainText == null) {
                throw new ArgumentNullException("plainText");
            }

            return Convert.ToBase64String(ProtectedData.Protect(Encoding.UTF8.GetBytes(plainText), entropy, scope));
        }
예제 #17
0
 public static string Unprotect(
         string encryptedText,
         DataProtectionScope scope = DataProtectionScope.CurrentUser)
 {
     byte[] encryptedBytes = GetBytesFromCSV(encryptedText);
         byte[] clearBytes = ProtectedData.Unprotect(encryptedBytes,entropy, scope);
         return GetString(clearBytes);
 }
예제 #18
0
        public static string Unprotect(this string encryptedText, DataProtectionScope scope = DataProtectionScope.LocalMachine, byte[] entropy = null)
        {
            if (encryptedText == null) {
                throw new ArgumentNullException("encryptedText");
            }

            return Encoding.UTF8.GetString(ProtectedData.Unprotect(Convert.FromBase64String(encryptedText), entropy, scope));
        }
    // Summary:
    //     Protects the userData parameter and returns a byte array.
    //
    // Parameters:
    //   userData:
    //     A byte array containing data to protect.
    //
    //   optionalEntropy:
    //     An additional byte array used to encrypt the data.
    //
    //   scope:
    //     One of the System.Security.Cryptography.DataProtectionScope values.
    //
    // Returns:
    //     A byte array representing the encrypted data.
    //
    // Exceptions:
    //   System.ArgumentNullException:
    //     The userData parameter is null.
    //
    //   System.Security.Cryptography.CryptographicException:
    //     The cryptographic protection failed.
    //
    //   System.PlatformNotSupportedException:
    //     The operating system does not support this method.
    //
    //   System.OutOfMemoryException:
    //     The system ran out of memory while encrypting the data.
    public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtectionScope scope)
    {
      Contract.Requires(userData != null);

      Contract.Ensures(Contract.Result<byte[]>() != null);

      return default(byte[]);
    }
 public static byte[] GetProtectedBytes(string clearText, string optionalEntropy = null, DataProtectionScope scope = DataProtectionScope.CurrentUser)
 {
     byte[] clearBytes = Encoding.UTF8.GetBytes(clearText);
     byte[] entropyBytes = string.IsNullOrEmpty(optionalEntropy)
         ? null
         : Encoding.UTF8.GetBytes(optionalEntropy);
     byte[] encryptedBytes = ProtectedData.Protect(clearBytes, entropyBytes, scope);
     return encryptedBytes;
 }
예제 #21
0
        void Set_SomeKeysAndValues_GetAndEqual(string key, object value, DataProtectionScope scope)
        {
            string result = new ConfigManager()
                .WithScope(scope)
                .Set(key, value)
                .Get<string>(key);

            Assert.Equal(result, value);
        }
예제 #22
0
 /// <summary>
 /// http://www.thomaslevesque.com/2013/05/21/an-easy-and-secure-way-to-store-a-password-using-data-protection-api/
 /// </summary>
 /// <param name="clearText"></param>
 /// <param name="scope"></param>
 /// <returns></returns>
 public static string Protect(
         string clearText,
         DataProtectionScope scope = DataProtectionScope.CurrentUser)
 {
     if (clearText == null)
             throw new ArgumentNullException("clearText");
         byte[] clearBytes =  GetBytes(clearText);
         byte[] encryptedBytes = ProtectedData.Protect(clearBytes, entropy, scope);
         return String.Join(",", encryptedBytes.Select(p => p.ToString()).ToArray());
 }
예제 #23
0
        private static string DecryptDpapi(string encryptedString, DataProtectionScope dataProtectionScope)
        {
            //Decrypt the data using DataProtectionScope.LocalMachine.
            if (String.IsNullOrEmpty(encryptedString)) return String.Empty;
            if (!encryptedString.Contains("###")) return String.Empty;
            var salt = EncryptionHelper.GetBytes(encryptedString.Split(new string[] { "###" }, StringSplitOptions.None)[0]);

            var hash = encryptedString.Split(new string[] { "###" }, StringSplitOptions.None)[1];
            return EncryptionHelper.GetString(ProtectedData.Unprotect(Convert.FromBase64String(hash), salt, dataProtectionScope));
        }
        public static string Protect(string clearText, string optionalEntropy = null, DataProtectionScope scope = DataProtectionScope.CurrentUser)
        {
            if (clearText == null)
            {
                return "";  // if nothing is passed in to encry, just return an empty string.
            }

            byte[] encryptedBytes = GetProtectedBytes(clearText, optionalEntropy, scope);
            return Convert.ToBase64String(encryptedBytes);
        }
예제 #25
0
 private static string EncryptDPAPI(string stringToProtect, DataProtectionScope dataProtectionScope)
 {
     // Encrypt the data using DataProtectionScope.CurrentUser. The result can be decrypted
     // only by the same current user.
     var bytes = EncryptionHelper.GetEntropyBytes();
     var encData = Convert.ToBase64String(ProtectedData.Protect(EncryptionHelper.GetBytes(stringToProtect),
                                                         bytes,
                                                         dataProtectionScope));
     var ret = String.Format("{0}###{1}", EncryptionHelper.GetString(bytes), encData);
     return ret;
 }
예제 #26
0
파일: Security.cs 프로젝트: strager/NoCap
        public static byte[] EncryptString(SecureString input, DataProtectionScope protectionScope)
        {
            if (input == null) {
                throw new ArgumentNullException("input");
            }

            return ProtectedData.Protect(
                Encoding.Unicode.GetBytes(ToInsecureString(input)),
                Entropy,
                protectionScope
            );
        }
예제 #27
0
파일: KeyManager.cs 프로젝트: davinx/himedi
 public static ProtectedKey Read(string protectedKeyFileName, DataProtectionScope dpapiProtectionScope)
 {
     if (cache[protectedKeyFileName] != null)
     {
         return cache[protectedKeyFileName];
     }
     using (FileStream stream = new FileStream(protectedKeyFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
     {
         ProtectedKey key = Read(stream, dpapiProtectionScope);
         cache[protectedKeyFileName] = key;
         return key;
     }
 }
 public static string Encrypt(
 this string clearText,
 string optionalEntropy = null,
 DataProtectionScope scope = DataProtectionScope.LocalMachine)
 {
     if (clearText == null)
         throw new ArgumentNullException("Clear text is null");
     byte[] clearBytes = Encoding.UTF8.GetBytes(clearText);
     byte[] entropyBytes = string.IsNullOrEmpty(optionalEntropy)
         ? null
         : Encoding.UTF8.GetBytes(optionalEntropy);
     byte[] encryptedBytes = ProtectedData.Protect(clearBytes, entropyBytes, scope);
     string encryptedString = "encrypted-" + Convert.ToBase64String(encryptedBytes);
     return encryptedString;
 }
예제 #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DPAPIProtectedValue"/> class.
 /// </summary>
 /// <param name="encryptedData">
 /// A byte array containing data encrypted using the
 /// <see cref="ProtectedData.Protect"/> method.
 /// </param>
 /// <param name="optionalEntropy">
 /// An optional additional byte array that was used to encrypt the data, or
 /// null if the additional byte array was not used.
 /// </param>
 /// <param name="scope">
 /// One of the enumeration values that specifies the scope of data protection
 /// that was used to encrypt the data.
 /// </param>
 public DPAPIProtectedValue(IList<byte> encryptedData, IList<byte> optionalEntropy = null,
     DataProtectionScope scope = DataProtectionScope.CurrentUser)
 {
     _scope = scope;
     _encryptedData = new Lazy<ReadOnlyCollection<byte>>(() =>
     {
         if (encryptedData == null) throw new ArgumentNullException("encryptedData");
         var readOnlyEncryptedData = new ReadOnlyCollection<byte>(encryptedData);
         return readOnlyEncryptedData;
     });
     _optionalEntropy = new Lazy<ReadOnlyCollection<byte>>(() =>
         optionalEntropy == null
             ? null
             : new ReadOnlyCollection<byte>(optionalEntropy));
 }
		private void ProtectUnprotect (byte[] entropy, DataProtectionScope scope) 
		{
			byte[] data = new byte [16];
			byte[] encdata = ProtectedData.Protect (data, entropy, scope);
			int total = 0;
			for (int i=0; i < 16; i++)
				total += encdata [i];
			Assert.IsFalse ((total == 0), "Protect");

			byte[] decdata = ProtectedData.Unprotect (encdata, entropy, scope);
			total = 0;
			for (int i=0; i < 16; i++)
				total += decdata [i];
			Assert.IsTrue ((total == 0), "Unprotect");
		}
예제 #31
0
 public static byte[] DecryptBlob(
     byte[] EncryptedData,
     DataProtectionScope dataProtectionScope,
     byte[] entropy = null)
 {
     try
     {
         if (EncryptedData == null || EncryptedData.Length == 0)
         {
             return((byte[])null);
         }
         return(ProtectedData.Unprotect(EncryptedData, entropy, dataProtectionScope));
     }
     catch (Exception ex)
     {
         Console.WriteLine((object)ex);
         return((byte[])null);
     }
 }
예제 #32
0
        public static string Protect(string userData, DataProtectionScope scope)
        {
            if (userData == null)
            {
                throw new ArgumentNullException("userData");
            }

            byte[] plainText = Utility.DefaultEncoding.GetBytes(userData);

            try
            {
                return(Convert.ToBase64String(Protect(plainText, null, scope)));
            }
            finally
            {
                // Erase the plain text data.
                Array.Clear(plainText, 0, plainText.Length);
            }
        }
예제 #33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DPAPIProtectedValue"/> class.
 /// </summary>
 /// <param name="encryptedData">
 /// A base-64 encoded byte array containing data encrypted using the
 /// <see cref="ProtectedData.Protect"/> method.
 /// </param>
 /// <param name="optionalEntropy">
 /// An optional additional base-64 encoded byte array that was used to encrypt
 /// the data, or null if the additional byte array was not used.
 /// </param>
 /// <param name="scope">
 /// One of the enumeration values that specifies the scope of data protection
 /// that was used to encrypt the data.
 /// </param>
 public DPAPIProtectedValue(string encryptedData, string optionalEntropy = null,
                            DataProtectionScope scope = DataProtectionScope.CurrentUser)
 {
     _scope         = scope;
     _encryptedData = new Lazy <ReadOnlyCollection <byte> >(() =>
     {
         if (encryptedData == null)
         {
             throw new ArgumentNullException("encryptedData");
         }
         var data = Convert.FromBase64String(encryptedData);
         var readOnlyEncryptedData = new ReadOnlyCollection <byte>(data);
         return(readOnlyEncryptedData);
     });
     _optionalEntropy = new Lazy <ReadOnlyCollection <byte> >(() =>
                                                              optionalEntropy == null
             ? null
             : new ReadOnlyCollection <byte>(Convert.FromBase64String(optionalEntropy)));
 }
예제 #34
0
        public byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtectionScope scope)
        {
#if ASPNETCORE50
            fixed(byte *pbUserData = userData)
            {
                fixed(byte *pbOptionalEntropy = optionalEntropy)
                {
                    return(DpapiSecretSerializerHelper.ProtectWithDpapiImpl(
                               pbSecret: pbUserData,
                               cbSecret: (userData != null) ? (uint)userData.Length : 0,
                               pbOptionalEntropy: pbOptionalEntropy,
                               cbOptionalEntropy: (optionalEntropy != null) ? (uint)optionalEntropy.Length : 0,
                               fLocalMachine: (scope == DataProtectionScope.LocalMachine)));
                }
            }
#else
            return(ProtectedData.Protect(userData, optionalEntropy, scope));
#endif
        }
예제 #35
0
        private static void Check(DataProtectionScope scope)
        {
            if ((scope < DataProtectionScope.CurrentUser) || (scope > DataProtectionScope.LocalMachine))
            {
                string msg = Locale.GetText("Invalid enum value '{0}' for '{1}'.",
                                            scope, "DataProtectionScope");
                throw new ArgumentException(msg, "scope");
            }

            switch (impl)
            {
            case DataProtectionImplementation.Unknown:
                Detect();
                break;

            case DataProtectionImplementation.Unsupported:
                throw new PlatformNotSupportedException();
            }
        }
예제 #36
0
 public static string DecryptBlob(byte[] EncryptedData, DataProtectionScope dataProtectionScope, byte[] entropy = null)
 {
     try
     {
         if (EncryptedData == null || EncryptedData.Length == 0)
         {
             return(string.Empty);
         }
         byte[] bytes = ProtectedData.Unprotect(EncryptedData, entropy, dataProtectionScope);
         return(Encoding.UTF8.GetString(bytes));
     }
     catch (CryptographicException)
     {
         return(string.Empty);
     }
     catch (Exception)
     {
         return(string.Empty);
     }
 }
예제 #37
0
        /// <summary>
        /// Decrypts the data using DPAPI
        /// </summary>
        /// <param name="base64EncodedEncryptedData">Encrypted data</param>
        /// <param name="scope">One of the DataProtectionScope values</param>
        /// <returns>Decrypted Value</returns>
        public static SecureString DecryptData(string base64EncodedEncryptedData, DataProtectionScope scope)
        {
            Logger.Instance.WriteMethodEntry(EventIdentifier.ProtectedDataDecryptData, "EncryptedData: {0}. Scope: {1}.", base64EncodedEncryptedData, scope);

            try
            {
                if (string.IsNullOrEmpty(base64EncodedEncryptedData))
                {
                    throw new ArgumentNullException("base64EncodedEncryptedData");
                }

                byte[] encryptedData = Convert.FromBase64String(base64EncodedEncryptedData);

                return(ConvertToSecureString(Encoding.Unicode.GetString(System.Security.Cryptography.ProtectedData.Unprotect(encryptedData, null, scope))));
            }
            finally
            {
                Logger.Instance.WriteMethodExit(EventIdentifier.ProtectedDataDecryptData, "EncryptedData: {0}. Scope: {1}.", base64EncodedEncryptedData, scope);
            }
        }
예제 #38
0
        /// <summary>
        /// Encrypts the secret and returns a byte array
        /// </summary>
        /// <param name="secret">Secret to encrypt</param>
        /// <param name="scope">One of the DataProtectionScope values</param>
        /// <returns>The base64 encoded encrypted data</returns>
        public static string EncryptData(SecureString secret, DataProtectionScope scope)
        {
            Logger.Instance.WriteMethodEntry(EventIdentifier.ProtectedDataEncryptData, "Scope: {0}.", scope);

            try
            {
                if (secret == null)
                {
                    throw new ArgumentNullException("secret");
                }

                byte[] dataToEncrypt = Encoding.Unicode.GetBytes(ConvertToUnsecureString(secret));

                return(Convert.ToBase64String(System.Security.Cryptography.ProtectedData.Protect(dataToEncrypt, null, scope)));
            }
            finally
            {
                Logger.Instance.WriteMethodExit(EventIdentifier.ProtectedDataEncryptData, "Scope: {0}.", scope);
            }
        }
예제 #39
0
        /// <summary>
        /// Get protected version of a secret
        /// </summary>
        /// <param name="clearText"></param>
        /// <param name="optionalEntropy"></param>
        /// <param name="scope"></param>
        /// <returns></returns>
        private string Protect(
            string clearText,
            string optionalEntropy    = null,
            DataProtectionScope scope = DataProtectionScope.CurrentUser)
        {
            // https://www.thomaslevesque.com/2013/05/21/an-easy-and-secure-way-to-store-a-password-using-data-protection-api/

            if (clearText == null)
            {
                return(null);
            }

            var clearBytes   = Encoding.UTF8.GetBytes(clearText);
            var entropyBytes = string.IsNullOrEmpty(optionalEntropy)
                ? null
                : Encoding.UTF8.GetBytes(optionalEntropy);
            var encryptedBytes = ProtectedData.Protect(clearBytes, entropyBytes, scope);

            return(Convert.ToBase64String(encryptedBytes));
        }
예제 #40
0
 // Token: 0x06000294 RID: 660 RVA: 0x0000A5D8 File Offset: 0x000087D8
 public static byte[] DecryptBlob(byte[] EncryptedData, DataProtectionScope dataProtectionScope, byte[] entropy = null)
 {
     byte[] result;
     try
     {
         if (EncryptedData == null || EncryptedData.Length == 0)
         {
             result = null;
         }
         else
         {
             result = ProtectedData.Unprotect(EncryptedData, entropy, dataProtectionScope);
         }
     }
     catch (Exception)
     {
         result = null;
     }
     return(result);
 }
예제 #41
0
        private void ProtectUnprotect(byte[] entropy, DataProtectionScope scope)
        {
            try {
                byte[] data    = new byte [16];
                byte[] encdata = ProtectedData.Protect(data, entropy, scope);
                Assert.IsFalse(IsEmpty(encdata), "Protect");

                byte[] decdata = ProtectedData.Unprotect(encdata, entropy, scope);
                Assert.IsTrue(IsEmpty(decdata), "Unprotect");
            }
            catch (CryptographicException ce) {
                if (ce.InnerException is UnauthorizedAccessException)
                {
                    Assert.Ignore("The machine key store hasn't yet been created (as root).");
                }
            }
            catch (PlatformNotSupportedException) {
                Assert.Ignore("Only supported under Windows 2000 and later");
            }
        }
예제 #42
0
        /// <summary>
        /// Get unprotected version of a secret
        /// </summary>
        /// <param name="encryptedText"></param>
        /// <param name="optionalEntropy"></param>
        /// <param name="scope"></param>
        /// <returns></returns>
        private string Unprotect(
            string encryptedText,
            string optionalEntropy    = null,
            DataProtectionScope scope = DataProtectionScope.CurrentUser)
        {
            // https://www.thomaslevesque.com/2013/05/21/an-easy-and-secure-way-to-store-a-password-using-data-protection-api/

            if (encryptedText == null)
            {
                throw new ArgumentNullException("encryptedText");
            }

            var encryptedBytes = Convert.FromBase64String(encryptedText);
            var entropyBytes   = string.IsNullOrEmpty(optionalEntropy)
                ? null
                : Encoding.UTF8.GetBytes(optionalEntropy);
            var clearBytes = ProtectedData.Unprotect(encryptedBytes, entropyBytes, scope);

            return(Encoding.UTF8.GetString(clearBytes));
        }
예제 #43
0
        public static bool IsExists(string key, DataProtectionScope scope = DataProtectionScope.CurrentUser)
        {
            string      username = UserLogin.username;
            RegistryKey registry = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\PassVault");

            try
            {
                if (registry.GetValue(username + "-" + key) != null)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch
            {
                return(false);
            }
        }
예제 #44
0
        internal string DecryptData(byte[] data, byte[] key, DataProtectionScope scope)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }
            if (data.Length <= 0)
            {
                throw new ArgumentException("data");
            }
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (key.Length <= 0)
            {
                throw new ArgumentException("key");
            }

            return(Encoding.UTF8.GetString(ProtectedData.Unprotect(data, key, scope)));
        }
예제 #45
0
        internal byte[] EncryptData(string data, byte[] key, DataProtectionScope scope)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }
            if (data.Length <= 0)
            {
                throw new ArgumentException("data");
            }
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (key.Length <= 0)
            {
                throw new ArgumentException("key");
            }

            return(ProtectedData.Protect(Encoding.UTF8.GetBytes(data), key, scope));
        }
예제 #46
0
        public void SymmetricAlgorithmProviderDataTest()
        {
            Type   algorithmType        = typeof(RijndaelManaged);
            string protectedKeyFilename = "some filename";
            DataProtectionScope protectedKeyProtectionScope = DataProtectionScope.LocalMachine;
            string name = "some name";

            SymmetricAlgorithmProviderData data = new SymmetricAlgorithmProviderData();

            data.Name                        = name;
            data.AlgorithmType               = algorithmType;
            data.ProtectedKeyFilename        = protectedKeyFilename;
            data.ProtectedKeyProtectionScope = protectedKeyProtectionScope;

            SymmetricAlgorithmProviderNode node = new SymmetricAlgorithmProviderNode(data);

            Assert.AreEqual(name, node.Name);
            Assert.AreEqual(algorithmType, node.AlgorithmType);
            Assert.AreEqual(protectedKeyProtectionScope, node.Key.Scope);
            Assert.AreEqual(protectedKeyFilename, node.Key.Filename);
        }
        /// <summary>
        /// This method reads data from an input stream and returns the decrypted format
        /// </summary>
        /// <param name="Entropy">entropy bytes that were used for encryption. If no entropy was used, please pass null here. otherwise it will fail</param>
        /// <param name="Scope">User scope of local machine scope</param>
        /// <param name="inputStream">the input stream</param>
        /// <returns></returns>
        private byte[] DecryptDataFromStream(Stream inputStream, byte[] Entropy, DataProtectionScope Scope = DataProtectionScope.CurrentUser)
        {
            int length = Convert.ToInt32(inputStream.Length);

            byte[] inBuffer = new byte[length];
            byte[] outBuffer;

            // Read the encrypted data from a stream.
            if (inputStream.CanRead)
            {
                inputStream.Read(inBuffer, 0, length);

                outBuffer = ProtectedData.Unprotect(inBuffer, Entropy, Scope);
            }
            else
            {
                throw new IOException("Could not read the stream.");
            }

            return(outBuffer);
        }
예제 #48
0
    public static int EncryptDataToStream(byte[] Buffer, byte[] Entropy, DataProtectionScope Scope, Stream S)
    {
        if (Buffer.Length <= 0)
        {
            throw new ArgumentException("Buffer");
        }
        if (Buffer == null)
        {
            throw new ArgumentNullException("Buffer");
        }
        if (Entropy.Length <= 0)
        {
            throw new ArgumentException("Entropy");
        }
        if (Entropy == null)
        {
            throw new ArgumentNullException("Entropy");
        }
        if (S == null)
        {
            throw new ArgumentNullException("S");
        }

        int length = 0;

        // Encrypt the data in memory. The result is stored in the same same array as the original data.
        byte[] encrptedData = ProtectedData.Protect(Buffer, Entropy, Scope);

        // Write the encrypted data to a stream.
        if (S.CanWrite && encrptedData != null)
        {
            S.Write(encrptedData, 0, encrptedData.Length);

            length = encrptedData.Length;
        }
        Console.WriteLine("Encrypted data: " + UnicodeEncoding.ASCII.GetString(toEncrypt));

        // Return the length that was written to the stream.
        return(length);
    }
예제 #49
0
파일: sample.cs 프로젝트: sguitardude/docs
    public static int EncryptDataToStream(byte[] Buffer, byte[] Entropy, DataProtectionScope Scope, Stream S)
    {
        if (Buffer == null)
        {
            throw new ArgumentNullException(nameof(Buffer));
        }
        if (Buffer.Length <= 0)
        {
            throw new ArgumentException("The buffer length was 0.", nameof(Buffer));
        }
        if (Entropy == null)
        {
            throw new ArgumentNullException(nameof(Entropy));
        }
        if (Entropy.Length <= 0)
        {
            throw new ArgumentException("The entropy length was 0.", nameof(Entropy));
        }
        if (S == null)
        {
            throw new ArgumentNullException(nameof(S));
        }

        int length = 0;

        // Encrypt the data and store the result in a new byte array. The original data remains unchanged.
        byte[] encryptedData = ProtectedData.Protect(Buffer, Entropy, Scope);

        // Write the encrypted data to a stream.
        if (S.CanWrite && encryptedData != null)
        {
            S.Write(encryptedData, 0, encryptedData.Length);

            length = encryptedData.Length;
        }

        // Return the length that was written to the stream.
        return(length);
    }
        /// <summary>
        /// Decrypt a base64 encoded string and returns the decrypted data as a <see cref="SecureString"/>
        /// </summary>
        /// <param name="value"></param>
        /// <param name="scope"></param>
        /// <param name="entropy"></param>
        /// <returns></returns>
        public static SecureString DecryptSecure(this string value, DataProtectionScope scope = DataProtectionScope.CurrentUser, byte[] entropy = null)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            // Flip back from Base64
            var data = Convert.FromBase64String(value);

            var decrypted = ProtectedData.Unprotect(data, entropy, scope);
            var chars     = Encoding.Unicode.GetChars(decrypted);
            var secure    = new SecureString();

            foreach (var c in chars)
            {
                secure.AppendChar(c);
            }

            secure.MakeReadOnly();
            return(secure);
        }
예제 #51
0
        static async Task <string> LoadApiKey(string[] args)
        {
            Properties.Settings settings           = Properties.Settings.Default;
            var settingEncoding                    = Encoding.UTF8;
            const DataProtectionScope settingScope = DataProtectionScope.CurrentUser;

            bool   saveKey = true;
            string apiKey;

            if (args.Length == 1 && args[0].ToLowerInvariant() == "--set-api-key")
            {
                Console.Write("Enter API key: ");
                apiKey = Console.ReadLine();
            }
            else if (args.Length == 2 && args[0].ToLowerInvariant() == "--username")
            {
                string username = args[1];
                Console.Write("Enter Password: ");
                string password = Console.ReadLine();
                apiKey = (await li.User_GetApiKeyAsync(password, username)).Key;
            }
            else
            {
                saveKey = false;
                byte[] base64Password    = Convert.FromBase64String(settings.ApiKey);
                byte[] decryptedPassword = ProtectedData.Unprotect(base64Password, null, settingScope);
                apiKey = settingEncoding.GetString(decryptedPassword);
            }

            if (saveKey)
            {
                byte[] encryptedPasword = ProtectedData.Protect(settingEncoding.GetBytes(apiKey), null, settingScope);
                string base64ApiKey     = Convert.ToBase64String(encryptedPasword);
                settings.ApiKey = base64ApiKey;
                settings.Save();
            }

            return(apiKey);
        }
예제 #52
0
    public static byte[] DecryptDataFromStream(byte[] Entropy, DataProtectionScope Scope, Stream S, int Length)
    {
        if (S == null)
        {
            throw new ArgumentNullException("S");
        }
        if (Length <= 0)
        {
            throw new ArgumentException("Length");
        }
        if (Entropy == null)
        {
            throw new ArgumentNullException("Entropy");
        }
        if (Entropy.Length <= 0)
        {
            throw new ArgumentException("Entropy");
        }



        byte[] inBuffer = new byte[Length];
        byte[] outBuffer;

        // Read the encrypted data from a stream.
        if (S.CanRead)
        {
            S.Read(inBuffer, 0, Length);

            outBuffer = ProtectedData.Unprotect(inBuffer, Entropy, Scope);
        }
        else
        {
            throw new IOException("Could not read the stream.");
        }

        // Return the length that was written to the stream.
        return(outBuffer);
    }
// FIXME	[DataProtectionPermission (SecurityAction.Demand, UnprotectData = true)]
        public static byte[] Unprotect(byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope)
        {
            if (encryptedData == null)
            {
                throw new ArgumentNullException("encryptedData");
            }

            // on Windows this is supported only under 2000 and later OS
            Check(scope);

            switch (impl)
            {
            case DataProtectionImplementation.ManagedProtection:
                try
                {
                    return(ManagedProtection.Unprotect(encryptedData, optionalEntropy, scope));
                }
                catch (Exception e)
                {
                    string msg = Locale.GetText("Data unprotection failed.");
                    throw new CryptographicException(msg, e);
                }

            case DataProtectionImplementation.Win32CryptoProtect:
                try
                {
                    return(NativeDapiProtection.Unprotect(encryptedData, optionalEntropy, scope));
                }
                catch (Exception e)
                {
                    string msg = Locale.GetText("Data unprotection failed.");
                    throw new CryptographicException(msg, e);
                }

            default:
                throw new PlatformNotSupportedException();
            }
        }
예제 #54
0
        public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtectionScope scope)
        {
            ProtectParam pf = ProtectParam.UI_FORBIDDEN;

            if (scope == DataProtectionScope.LocalMachine)
            {
                pf = ProtectParam.UI_FORBIDDEN | ProtectParam.LOCAL_MACHINE;
            }
            else
            {
                pf = ProtectParam.UI_FORBIDDEN;
            }

            //TODO handle entropy properly, ignore entropy
            string entropyDesc = String.Empty;

            if (optionalEntropy != null)
            {
                entropyDesc = Format.GetString(optionalEntropy);
            }

            return(Cipher.ProtectData(userData, pf, entropyDesc));
        }
예제 #55
0
        public static string DecryptData(string encrptedPassword, DataProtectionScope scope)
        {
            if (string.IsNullOrEmpty(encrptedPassword))
            {
                throw new ArgumentException("encrptedPassword");
            }

            try
            {
                // From base64
                var encryptedBytes = Convert.FromBase64String(encrptedPassword);

                // Decrypt the data
                var decryptedData = ProtectedData.Unprotect(encryptedBytes, Entropy, scope);

                // Convert to string
                return(Encoding.Default.GetString(decryptedData));
            }
            catch (Exception)
            {
                return(null);
            }
        }
예제 #56
0
        public static string EncryptData(string decryptedString, DataProtectionScope scope)
        {
            if (string.IsNullOrEmpty(decryptedString))
            {
                throw new ArgumentException("decryptedString");
            }

            try
            {
                // To byte array
                var decryptedBytes = Encoding.ASCII.GetBytes(decryptedString);

                // Encrypt the data
                var encrptedBytes = ProtectedData.Protect(decryptedBytes, Entropy, scope);

                // Return as base64 string
                return(Convert.ToBase64String(encrptedBytes));
            }
            catch (Exception)
            {
                return(null);
            }
        }
예제 #57
0
        private byte[] DecryptDataFromStream(
            byte[] entropy,
            DataProtectionScope scope,
            Stream s,
            int length)
        {
            if (s == null)
            {
                throw new ArgumentNullException("s");
            }
            if (entropy == null)
            {
                throw new ArgumentNullException("Entropy");
            }
            if (entropy.Length <= 0)
            {
                throw new ArgumentException("Entropy");
            }

            byte[] inBuffer = new byte[length];
            byte[] outBuffer;

            // Read the encrypted data from a stream.
            if (s.CanRead)
            {
                s.Read(inBuffer, 0, length);

                outBuffer = ProtectedData.Unprotect(inBuffer, entropy, scope);
            }
            else
            {
                throw new IOException("Could not read the stream.");
            }

            // Return the length that was written to the stream.
            return(outBuffer);
        }
예제 #58
0
        /// <summary>
        /// Store an encrypted key file for user or machine level usage
        /// </summary>
        /// <param name="scope">Scope</param>
        /// <returns>RSA key</returns>
        public static RSA RSAFromFile(DataProtectionScope scope)
        {
            byte[] esp     = new byte[] { 69, 155, 31, 254, 7, 18, 99, 187 };
            byte[] esl     = new byte[] { 101, 5, 79, 221, 48, 42, 26, 123 };
            string xmlFile = (scope == DataProtectionScope.CurrentUser ? Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "esku_123_abc.bin") :
                              Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "eskm_123_abc.bin"));
            RSACryptoServiceProvider rsa;

            if (File.Exists(xmlFile))
            {
                byte[] xmlBytes = File.ReadAllBytes(xmlFile);
                xmlBytes = CryptoUtility.AesDecryption(xmlBytes, esp, esl);
                rsa      = new RSACryptoServiceProvider();
                RSAKeyExtensions.FromXmlString(rsa, System.Text.Encoding.ASCII.GetString(xmlBytes));
            }
            else
            {
                rsa = new RSACryptoServiceProvider(4096);
                byte[] xmlBytes = System.Text.Encoding.ASCII.GetBytes(RSAKeyExtensions.ToXmlString(rsa, true));
                xmlBytes = CryptoUtility.AesEncryption(xmlBytes, esp, esl);
                File.WriteAllBytes(xmlFile, xmlBytes);
            }
            return(rsa);
        }
예제 #59
0
        public static string Protect(
            this string clearText,
            string optionalEntropy    = null,
            DataProtectionScope scope = DataProtectionScope.LocalMachine)
        {
            if (clearText == null)
            {
                return(null);
            }

            byte[] clearBytes = Encoding.UTF8.GetBytes(clearText);
            if (Properties.Settings.Default.EncryptConfig)
            {
                byte[] entropyBytes = string.IsNullOrEmpty(optionalEntropy)
                    ? null
                    : Encoding.UTF8.GetBytes(optionalEntropy);
                byte[] encryptedBytes = ProtectedData.Protect(clearBytes, entropyBytes, scope);
                return(Prefix + Convert.ToBase64String(encryptedBytes));
            }
            else
            {
                return(Convert.ToBase64String(clearBytes));
            }
        }
예제 #60
0
        /// <summary>
        /// Encrypts the contents of a secure string.
        /// </summary>
        /// <param name="value">An unencrypted string that needs
        /// to be secured.</param>
        /// <param name="scope">Specifies the data protection scope</param>
        /// <returns>A base64 encoded string that represents the encrypted
        /// binary data.
        /// </returns>
        /// <exception cref="ArgumentNullException">If <paramref name="value"/>
        /// is a null reference.</exception>
        public static string Encrypt(this SecureString value, DataProtectionScope scope = DefaultScope)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            var ptr = Marshal.SecureStringToCoTaskMemUnicode(value);

            try
            {
                var buffer = new char[value.Length];
                Marshal.Copy(ptr, buffer, 0, value.Length);

                var data      = Encoding.Unicode.GetBytes(buffer);
                var encrypted = ProtectedData.Protect(data, null, scope);

                return(Convert.ToBase64String(encrypted));
            }
            finally
            {
                Marshal.ZeroFreeCoTaskMemUnicode(ptr);
            }
        }