Exemplo n.º 1
0
        private static void TestProtectedMemory2()
        {
            using ProtectedMemory protectedMemory = ProtectedMemory.Allocate(8);
            protectedMemory[0] = 0x1;
            PrintArray(protectedMemory.Read(0, 8));
            protectedMemory[1] = 0x3;
            PrintArray(protectedMemory.Read(0, 8));
            protectedMemory[2] = 0x3;
            PrintArray(protectedMemory.Read(0, 8));
            protectedMemory[3] = 0x7;
            PrintArray(protectedMemory.Read(0, 8));
            protectedMemory[0] = 0x8;
            Console.ReadLine();
            protectedMemory.Protect();
            Console.WriteLine("Protected!");
            Console.ReadLine();
            protectedMemory.Unprotect();
            Console.WriteLine("Unprotected!");
            Console.ReadLine();
            protectedMemory.Protect();
            Console.WriteLine("Protected!");
            byte[] bytes = new byte[8];
            Console.WriteLine("Trying to access protected memory (should fail)");
            Console.ReadLine();
#pragma warning disable CS0618 // Type or member is obsolete
            Marshal.Copy(protectedMemory.GetDirectHandle(), bytes, 0, bytes.Length);
#pragma warning restore CS0618 // Type or member is obsolete
            PrintArray(bytes);
        }
Exemplo n.º 2
0
        private void Init(bool bEnableProtection, byte[] pbData)
        {
            if (pbData == null)
            {
                throw new ArgumentNullException("pbData");
            }

            m_bProtected = bEnableProtection;
            m_uDataLen   = (uint)pbData.Length;

            int nBlocks = (int)m_uDataLen / PmBlockSize;

            if ((nBlocks * PmBlockSize) < (int)m_uDataLen)
            {
                ++nBlocks;
            }
            Debug.Assert((nBlocks * PmBlockSize) >= (int)m_uDataLen);

            m_pbData = new byte[nBlocks * PmBlockSize];
            Array.Copy(pbData, m_pbData, (int)m_uDataLen);

            // Data size must be > 0, otherwise 'Protect' throws
            if (m_bProtected && m_bProtectionSupported && (m_uDataLen > 0))
            {
                ProtectedMemory.Protect(m_pbData, MemoryProtectionScope.SameProcess);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Initializes the state of Key Pair assuming the given Passphrase includes a higher then 100-bit
        /// entropy score using ZXCVBN analysis.  Returns false if the Passphrase does not pass this test, and the
        /// object is not initialized as a result.  Returns true with the Key Pair is ready for use.
        /// </summary>
        /// <param name="EMail"></param>
        /// <param name="Passphrase"></param>
        /// <returns>true if OK/Initialized, false if BAD PASSPHRASE</returns>
        public bool Initialize(string EMail, string Passphrase)
        {
            if (string.IsNullOrWhiteSpace(EMail))
            {
                throw new ArgumentNullException("EMail");
            }
            if (string.IsNullOrWhiteSpace(Passphrase))
            {
                throw new ArgumentNullException("Passphrase");
            }
            if ((int)ScorePotentialPassphrase(Passphrase).Entropy < 100)
            {
                return(false);
            }

            byte[] mangledPWD = Blake2S.ComputeHash(new UTF8Encoding().GetBytes(Passphrase.Trim()));
            _Secret         = SCrypt.ComputeDerivedKey(mangledPWD, new UTF8Encoding().GetBytes(EMail.Trim()), 131072, 8, 1, 1, 32);
            _SecretChecksum = ComputeChecksum(_Secret);

            _PublicID = GeneratePublicIDFromSecret(_Secret, out _PublicChecksum);
            //PROTECT MEMORY AFTER LAST USE OF _Secret
            ProtectedMemory.Protect(_Secret, MemoryProtectionScope.SameProcess);
            _Public = GetBytesFromPublicKey(_PublicID);
            return(true);
        }
Exemplo n.º 4
0
        private static void ScryptTests()
        {
            // Iterations:  65536
            // blockSize:   8
            // Threads:     1
            // SALT: TB5ny6LI9KywU3+TD5FdrNSsxYV2T+3qyxRwMieu7zQ=
            // HASH: +jsi778vVLkfYWp3dQDwW7g9/XMySal9lDoEQxvB6uc=

            byte[]          bytes           = Encoding.UTF8.GetBytes("ABCD");
            ProtectedMemory protectedMemory = ProtectedMemory.Allocate(bytes.Length);

            protectedMemory.Write(bytes, 0);
            // ScryptProtectedCryptoProvider scryptProtected2 = new ScryptProtectedCryptoProvider();
            // Console.WriteLine(scryptProtected2.ComputeHash(protectedMemory, Convert.FromBase64String("TB5ny6LI9KywU3+TD5FdrNSsxYV2T+3qyxRwMieu7zQ="), 65536, 8, 1, 32));
            byte[]          bytes2           = Encoding.UTF8.GetBytes("DCBA");
            ProtectedMemory protectedMemory2 = ProtectedMemory.Allocate(bytes.Length);

            protectedMemory2.Write(bytes2, 0);
            ScryptProtectedCryptoProvider scryptProtected = new ScryptProtectedCryptoProvider();
            string result = scryptProtected.ComputeHash(protectedMemory);

            Console.WriteLine(result);
            Console.WriteLine("Should be False:");
            Console.WriteLine(scryptProtected.Compare(protectedMemory2, result));
            Console.WriteLine("Should be True:");
            Console.WriteLine(scryptProtected.Compare(protectedMemory, result));
        }
Exemplo n.º 5
0
 protected byte[] DecryptPrivateKey(byte[] encryptedPrivateKey)
 {
     if (encryptedPrivateKey == null)
     {
         throw new ArgumentNullException(nameof(encryptedPrivateKey));
     }
     if (encryptedPrivateKey.Length != 96)
     {
         throw new ArgumentException();
     }
     ProtectedMemory.Unprotect(masterKey, MemoryProtectionScope.SameProcess);
     try
     {
         using (AesManaged aes = new AesManaged())
         {
             aes.Padding = PaddingMode.None;
             using (ICryptoTransform decryptor = aes.CreateDecryptor(masterKey, iv))
             {
                 return(decryptor.TransformFinalBlock(encryptedPrivateKey, 0, encryptedPrivateKey.Length));
             }
         }
     }
     finally
     {
         ProtectedMemory.Protect(masterKey, MemoryProtectionScope.SameProcess);
     }
 }
        /// <summary>
        /// Encrypts <see langword="byte"/>[] data using the Windows DPAPI ProtectedMemory class.
        /// </summary>
        /// <param name="data"> The <see langword="byte"/>[] data to encrypt. </param>
        /// <param name="entropy"> The additional entropy to apply to the encryption. </param>
        /// <returns> The encrypted <see langword="byte"/>[] data. </returns>
        protected override byte[] InternalEncrypt(byte[] data, byte[] entropy)
        {
            byte[] encryptedData = aes.Encrypt(data, entropy?.Length > 0 ? entropy : randomEntropy);
            ProtectedMemory.Protect(encryptedData, MemoryProtectionScope.SameProcess);

            return(encryptedData);
        }
Exemplo n.º 7
0
        private void Decrypt()
        {
            if (m_pbData.Length == 0)
            {
                return;
            }

            if (m_mp == PbMemProt.ProtectedMemory)
            {
                ProtectedMemory.Unprotect(m_pbData, MemoryProtectionScope.SameProcess);
            }
            else if (m_mp == PbMemProt.Salsa20)
            {
                Salsa20Cipher s = new Salsa20Cipher(g_pbKey32,
                                                    BitConverter.GetBytes(m_lID));
                s.Encrypt(m_pbData, m_pbData.Length, true);
                s.Dispose();
            }
            else if (m_mp == PbMemProt.ExtCrypt)
            {
                m_fExtCrypt(m_pbData, PbCryptFlags.Decrypt, m_lID);
            }
            else
            {
                Debug.Assert(m_mp == PbMemProt.None);
            }

            m_mp = PbMemProt.None;
        }
Exemplo n.º 8
0
 private byte[] getEncryptionKey()
 {
     byte[] key = new byte[encryptionKey.Length];
     Array.Copy(encryptionKey, key, encryptionKey.Length);
     ProtectedMemory.Unprotect(key, MemoryProtectionScope.SameProcess);
     return(key);
 }
Exemplo n.º 9
0
 private void _UnprotectKey()
 {
     if (!SodiumCore.IsRunningOnMono())
     {
         ProtectedMemory.Unprotect(_privateKey, MemoryProtectionScope.SameProcess);
     }
 }
Exemplo n.º 10
0
 private void _UnprotectKey()
 {
     if (!SodiumLibrary.IsRunningOnMono)
     {
         ProtectedMemory.Unprotect(this._privateKey, MemoryProtectionScope.SameProcess);
     }
 }
Exemplo n.º 11
0
        /// <summary>
        /// Get the protected data as a byte array. Please note that the returned
        /// byte array is not protected and can therefore been read by any other
        /// applications. Make sure that your clear it properly after usage.
        /// </summary>
        /// <returns>Unprotected byte array. This is always a copy of the internal
        /// protected data and can therefore be cleared safely.</returns>
        public byte[] ReadData()
        {
            if (m_xbEncrypted != null)
            {
                byte[] pb = m_xbEncrypted.ReadPlainText();
                SetData(pb);                 // Clear the XorredBuffer object

                return(pb ?? new byte[0]);
            }

            if (m_pbData.Length == 0)
            {
                return(new byte[0]);
            }

            if (m_bDoProtect && m_bProtectionSupported)
            {
                Debug.Assert((m_pbData.Length % 16) == 0);
                ProtectedMemory.Unprotect(m_pbData, MemoryProtectionScope.SameProcess);
            }

            byte[] pbReturn = new byte[m_uDataLen];
            if (m_uDataLen > 0)
            {
                Array.Copy(m_pbData, pbReturn, (int)m_uDataLen);
            }

            if (m_bDoProtect && m_bProtectionSupported)
            {
                ProtectedMemory.Protect(m_pbData, MemoryProtectionScope.SameProcess);
            }

            return(pbReturn);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Get a copy of the protected data as a byte array.
        /// Please note that the returned byte array is not protected and
        /// can therefore been read by any other application.
        /// Make sure that your clear it properly after usage.
        /// </summary>
        /// <returns>Unprotected byte array. This is always a copy of the internal
        /// protected data and can therefore be cleared safely.</returns>
        public byte[] ReadData()
        {
            if (m_uDataLen == 0)
            {
                return(new byte[0]);
            }

            byte[] pbReturn = new byte[m_uDataLen];

            if (m_bProtected && m_bProtectionSupported)
            {
                lock (m_objSync)
                {
                    ProtectedMemory.Unprotect(m_pbData, MemoryProtectionScope.SameProcess);
                    Array.Copy(m_pbData, pbReturn, (int)m_uDataLen);
                    ProtectedMemory.Protect(m_pbData, MemoryProtectionScope.SameProcess);
                }
            }
            else
            {
                Array.Copy(m_pbData, pbReturn, (int)m_uDataLen);
            }

            return(pbReturn);
        }
Exemplo n.º 13
0
        private void Decrypt()
        {
            if (passwordData.Length == 0)
            {
                return;
            }

            if (passwordMemoryProtection == PbMemProt.ProtectedMemory)
            {
                ProtectedMemory.Unprotect(passwordData, MemoryProtectionScope.SameProcess);
            }
            else if (passwordMemoryProtection == PbMemProt.Salsa20)
            {
                var cipher = new Salsa20Cipher(keyBytes32, BitConverter.GetBytes(longId));
                cipher.Encrypt(passwordData, passwordData.Length, true);
                cipher.Dispose();
            }
            else if (passwordMemoryProtection == PbMemProt.ExtCrypt)
            {
                m_fExtCrypt(passwordData, PbCryptFlags.Decrypt, longId);
            }
            else
            {
                Debug.Assert(passwordMemoryProtection == PbMemProt.None);
            }

            passwordMemoryProtection = PbMemProt.None;
        }
Exemplo n.º 14
0
        /// <summary>
        /// Provide toggling of memory protection for instances of SecretSplittingProvider
        /// </summary>
        /// <param name="instance"></param>
        public static void ToggleMemoryProtection(SecretSplittingProvider instance)
        {
            if (!instance.IsSecretMessageProtected)
            {
                try
                {
                    ProtectedMemory.Protect(instance.SecretMessage, MemoryProtectionScope.SameProcess);
                    ProtectedMemory.Protect(instance.R, MemoryProtectionScope.SameProcess);
                    ProtectedMemory.Protect(instance.S, MemoryProtectionScope.SameProcess);

                    instance.IsSecretMessageProtected = true;
                }
                catch (CryptographicException exception)
                {
                    Console.WriteLine(exception.Message);
                }
            }
            else
            {
                try
                {
                    ProtectedMemory.Unprotect(instance.SecretMessage, MemoryProtectionScope.SameProcess);
                    ProtectedMemory.Unprotect(instance.R, MemoryProtectionScope.SameProcess);
                    ProtectedMemory.Unprotect(instance.S, MemoryProtectionScope.SameProcess);

                    instance.IsSecretMessageProtected = false;
                }
                catch (CryptographicException exception)
                {
                    Console.WriteLine(exception.Message);
                }
            }
        }
Exemplo n.º 15
0
        private static unsafe void Pbkdf2HmacSha256(ProtectedMemory password, byte *salt, int saltLength, long c, int dkLen, byte *result)
        {
            if (c < 1)
            {
                throw new ArgumentException("The count " + nameof(c) + " cannot be less than 1!");
            }
            const int digestLength     = 0x20;
            int       blockCount       = (int)Math.Ceiling((double)dkLen / digestLength);
            int       saltBufferLength = saltLength + sizeof(int);
            IntPtr    hSaltBuffer      = Marshal.AllocHGlobal(saltBufferLength);
            byte *    saltBuffer       = (byte *)hSaltBuffer;

            Unsafe.CopyBlock(saltBuffer, salt, (uint)saltLength);

            for (int i = 1; i <= blockCount; i++)
            {
                MarshalExtensions.WriteInt32BigEndian(saltBuffer + saltLength, i);
                Sha256ProtectedCryptoProvider sha256 = new Sha256ProtectedCryptoProvider();
                (IntPtr hU, _) = sha256.ComputeHmacUnsafe(password, saltBuffer, saltBufferLength);
                Unsafe.CopyBlock(result + ((i - 1) * digestLength), (void *)hU, digestLength);
                MarshalExtensions.ZeroFree(hU, digestLength);

                for (long j = 1; j < c; j++)
                {
                    (IntPtr hUi, _) = sha256.ComputeHmacUnsafe(password, saltBuffer, digestLength);
                    byte *ui = (byte *)hUi;
                    for (int k = 0; k < digestLength; k++)
                    {
                        (result + ((i - 1) * digestLength))[k] ^= ui[k];
                    }
                    MarshalExtensions.ZeroFree(hUi, digestLength);
                }
            }
            MarshalExtensions.ZeroFree(hSaltBuffer, saltBufferLength);
        }
Exemplo n.º 16
0
 internal AesState(ProtectedMemory key, byte[] iv)
 {
     protectedRoundKey = ProtectedMemory.Allocate(KeyExpSize);
     this.iv           = new byte[16];
     Buffer.BlockCopy(iv, 0, this.iv, 0, 16);
     KeyExpansion(key);
 }
Exemplo n.º 17
0
        // This function produces Nb(Nr+1) round keys. The round keys are used in each round to decrypt the states.
        private unsafe void KeyExpansion(ProtectedMemory protectedKey)
        {
            IntPtr hBuffer = Marshal.AllocHGlobal(4);
            byte * buffer  = (byte *)hBuffer;

            using ProtectedMemoryAccess roundKeyAccess = new ProtectedMemoryAccess(protectedRoundKey);
            uint *roundKey = (uint *)roundKeyAccess.Handle;

            using (ProtectedMemoryAccess keyAccess = new ProtectedMemoryAccess(protectedKey))
            {
                uint *key = (uint *)keyAccess.Handle;
                // The first round key is the key itself.
                for (int i = 0; i < Nk; i++)
                {
                    roundKey[i] = key[i];
                }
            }
            for (int i = Nk; i < Nb * (Nr + 1); i++)
            {
                *(uint *)buffer = roundKey[i - 1];
                if ((i & 0x7) == 0) // if (i % 8 == 0)
                {
                    RotateWord(buffer);
                    SubWord(buffer);
                    buffer[0] ^= RoundConstants[i / Nk];
                }
                if ((i & 0x7) == 0x4) // if (i % 8 == 4)
                {
                    SubWord(buffer);
                }
                roundKey[i] = roundKey[i - Nk] ^ buffer[0];
            }
            Marshal.FreeHGlobal(hBuffer);
        }
Exemplo n.º 18
0
 public static void EncryptByteArray(ref byte[] byteArray)
 {
     try
     {
         if (Globals.MemoryEncryption == true && byteArray != null)
         {
             if (Constants.RunningOnMono == false)
             {
                 // Windows
                 ProtectedMemory.Protect(byteArray, MemoryProtectionScope.SameProcess);
             }
             else if (Constants.RunningOnMono == true)
             {
                 // Linux & macOS
                 byteArray = SealedPublicKeyBox.Create(byteArray, _keyPair.PublicKey);
             }
         }
     }
     catch (Exception ex) when(ExceptionFilters.MemoryEncryptionExceptions(ex))
     {
         Globals.MemoryEncryption = false;
         Settings.SaveSettings();
         Logging.LogException(ex.ToString(), Logging.Severity.Bug);
         DisplayMessage.ErrorMessageBox(ex.GetType().Name, "Memory encryption has been disabled due to an exception. This is a bug - please report it.");
     }
 }
Exemplo n.º 19
0
        internal unsafe void AesCbcDecryptBuffer(ProtectedMemory protectedBuffer)
        {
            IntPtr hIvBuffer = Marshal.AllocHGlobal(AesBlockLength);
            byte * ivBuffer  = (byte *)hIvBuffer;

            using ProtectedMemoryAccess access         = new ProtectedMemoryAccess(protectedBuffer);
            using ProtectedMemoryAccess roundKeyAccess = new ProtectedMemoryAccess(protectedRoundKey);
            byte *buffer   = (byte *)access.Handle;
            byte *roundKey = (byte *)roundKeyAccess.Handle;
            State state    = new State(buffer);

            fixed(byte *originalIv = iv)
            {
                byte *iv = originalIv;

                for (int i = 0; i < protectedBuffer.ContentLength; i += AesBlockLength)
                {
                    Unsafe.CopyBlock(ivBuffer, state.Buffer, AesBlockLength);
                    InverseCipher(state, roundKey);
                    XorWithIv(state.Buffer, iv);
                    Unsafe.CopyBlock(iv, ivBuffer, AesBlockLength);
                    state.Buffer += AesBlockLength;
                }
            }

            Marshal.FreeHGlobal(hIvBuffer);
        }
 /// <summary>
 /// Provides toggling of memory protection for the byte[] passed in
 /// </summary>
 /// <param name="toProtectBytes"></param>
 /// <param name="flag"></param>
 private static void ToggleMemoryProtect(byte[] toProtectBytes, ref bool flag)
 {
     if (!flag)
     {
         try
         {
             ProtectedMemory.Protect(toProtectBytes, MemoryProtectionScope.SameProcess);
             flag = true;
         }
         catch (CryptographicException exception)
         {
             Console.WriteLine(exception.Message);
         }
     }
     else
     {
         try
         {
             ProtectedMemory.Unprotect(toProtectBytes, MemoryProtectionScope.SameProcess);
             flag = false;
         }
         catch (CryptographicException exception)
         {
             Console.WriteLine(exception.Message);
         }
     }
 }
Exemplo n.º 21
0
        private unsafe IntPtr Digest(ProtectedMemory protectedMemory)
        {
            Init(protectedMemory.ContentLength, out int contentLength, out int blockCount, out int allocatedSize, out IntPtr hMessageBuffer);
            byte *messageBuffer = (byte *)hMessageBuffer;

            using (ProtectedMemoryAccess access = new ProtectedMemoryAccess(protectedMemory))
            {
                if ((contentLength & 1) == 1)
                {
                    byte *pProtectedMemory = (byte *)access.Handle;
                    for (int i = 0; i < contentLength; i++)
                    {
                        messageBuffer[i] = pProtectedMemory[i];
                    }
                }
                else
                {
                    ushort *pProtectedMemory = (ushort *)access.Handle;
                    ushort *pMessageBuffer   = (ushort *)hMessageBuffer;
                    for (int i = 0; i < (contentLength / 2); i++)
                    {
                        pMessageBuffer[i] = pProtectedMemory[i];
                    }
                }
            }
            // append padding
            messageBuffer[contentLength] = 0x80;
            return(Compute(hMessageBuffer, allocatedSize, contentLength, blockCount));
        }
Exemplo n.º 22
0
        public ProtectedMemory GetProtectedUtf8Bytes()
        {
            ProtectedMemory result = ProtectedMemory.Allocate(protectedMemory.ContentLength);

            protectedMemory.CopyTo(0, result, 0, protectedMemory.ContentLength);
            return(result);
        }
Exemplo n.º 23
0
        public KeyPair(byte[] privateKey)
        {
            if (privateKey.Length != 32 && privateKey.Length != 96 && privateKey.Length != 104)
            {
                throw new ArgumentException();
            }
            this.PrivateKey = new byte[32];
            //Console.WriteLine("PrivateKey: ");
            //Console.WriteLine(privateKey.ToHexString());
            // 复制私钥
            Buffer.BlockCopy(privateKey, privateKey.Length - 32, PrivateKey, 0, 32);
            if (privateKey.Length == 32)
            {
                this.PublicKey = Cryptography.ECC.ECCurve.Secp256r1.G * privateKey;
            }
            else
            {
                this.PublicKey = Cryptography.ECC.ECPoint.FromBytes(privateKey, Cryptography.ECC.ECCurve.Secp256r1);
            }
            // 公钥和ECPoint互转
            //Console.WriteLine($"ECPoint: {Cryptography.ECC.ECPoint.Parse(this.ToString(), Cryptography.ECC.ECCurve.Secp256r1).ToString()}");
#if NET47
            ProtectedMemory.Protect(PrivateKey, MemoryProtectionScope.SameProcess);
#endif
        }
Exemplo n.º 24
0
        private void Decrypt()
        {
            if (m_pbData.Length == 0)
            {
                return;
            }

            if (m_mp == PbMemProt.ProtectedMemory)
            {
                ProtectedMemory.Unprotect(m_pbData, MemoryProtectionScope.SameProcess);
            }
            else if (m_mp == PbMemProt.ChaCha20)
            {
                byte[] pbIV = new byte[12];
                MemUtil.UInt64ToBytesEx((ulong)m_lID, pbIV, 4);
                using (ChaCha20Cipher c = new ChaCha20Cipher(g_pbKey32, pbIV, true))
                {
                    c.Decrypt(m_pbData, 0, m_pbData.Length);
                }
            }
            else if (m_mp == PbMemProt.ExtCrypt)
            {
                m_fExtCrypt(m_pbData, PbCryptFlags.Decrypt, m_lID);
            }
            else
            {
                Debug.Assert(m_mp == PbMemProt.None);
            }

            m_mp = PbMemProt.None;
        }
Exemplo n.º 25
0
        /// <summary>
        /// Set protected data. This function also clears the internal
        /// <c>XorredBuffer</c> object.
        /// </summary>
        /// <param name="pbNew">Data to store in the protected object. The input
        /// byte array will not be modified, the data is copied to an internal
        /// buffer of the protected object. This parameter must not be <c>null</c>;
        /// if you want to clear the object, call the <c>Clear</c> member
        /// function.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the input
        /// parameter is <c>null</c>.</exception>
        public void SetData(byte[] pbNew)
        {
            this.Clear();

            Debug.Assert(pbNew != null);
            if (pbNew == null)
            {
                throw new ArgumentNullException("pbNew");
            }

            m_uDataLen = (uint)pbNew.Length;

            if (m_bDoProtect && m_bProtectionSupported)
            {
                int nAllocatedMem = (((int)m_uDataLen / 16) + 1) * 16;
                m_pbData = new byte[nAllocatedMem];
                Array.Clear(m_pbData, nAllocatedMem - 16, 16);
                Array.Copy(pbNew, m_pbData, (int)m_uDataLen);

                ProtectedMemory.Protect(m_pbData, MemoryProtectionScope.SameProcess);
            }
            else             // !m_bDoProtect
            {
                m_pbData = new byte[m_uDataLen];
                pbNew.CopyTo(m_pbData, 0);
            }
        }
Exemplo n.º 26
0
        public KeyPair(byte[] privateKey, KeyType version = KeyType.Transparent)
        {
            this.nVersion = version;

            if (version == KeyType.Transparent)
            {
                if (privateKey.Length != 32 && privateKey.Length != 96 && privateKey.Length != 104)
                {
                    throw new ArgumentException();
                }

                this.PrivateKey = new byte[32];
                Buffer.BlockCopy(privateKey, privateKey.Length - 32, PrivateKey, 0, 32);

                if (privateKey.Length == 32)
                {
                    this.PublicKey = Cryptography.ECC.ECCurve.Secp256r1.G * privateKey;
                }
                else
                {
                    this.PublicKey = Cryptography.ECC.ECPoint.FromBytes(privateKey, Cryptography.ECC.ECCurve.Secp256r1);
                }

                this.PublicKeyHash = PublicKey.EncodePoint(true).ToScriptHash();
#if NET461
                ProtectedMemory.Protect(PrivateKey, MemoryProtectionScope.SameProcess);
#endif
            }
            else if (version == KeyType.Anonymous)
            {
                if (privateKey.Length != 32 && privateKey.Length != 96 && privateKey.Length != 104)
                {
                    throw new ArgumentException();
                }

                this.PrivateKey = new byte[32];
                Buffer.BlockCopy(privateKey, privateKey.Length - 32, PrivateKey, 0, 32);

                if (PrivateKey[31] > 0x10 && PrivateKey.Length != 32)
                {
                    throw new ArgumentException();
                }

                if (privateKey.Length == 32)
                {
                    this.PublicKey = Cryptography.ECC.ECCurve.Secp256r1.G * privateKey;
                }
                else
                {
                    this.PublicKey = Cryptography.ECC.ECPoint.FromBytes(privateKey, Cryptography.ECC.ECCurve.Secp256r1);
                }

                this.PublicKeyHash = PublicKey.EncodePoint(true).ToScriptHash();

#if NET461
                ProtectedMemory.Protect(PrivateKey, MemoryProtectionScope.SameProcess);
#endif
            }
        }
Exemplo n.º 27
0
        private void Encrypt()
        {
            Debug.Assert(m_mp == PbMemProt.None);

            // Nothing to do if caller didn't request protection
            if (!m_bProtected)
            {
                return;
            }

            // ProtectedMemory.Protect throws for data size == 0
            if (m_pbData.Length == 0)
            {
                return;
            }

            PbCryptDelegate f = g_fExtCrypt;

            if (f != null)
            {
                f(m_pbData, PbCryptFlags.Encrypt, m_lID);

                m_fExtCrypt = f;
                m_mp        = PbMemProt.ExtCrypt;
                return;
            }

            if (ProtectedBinary.ProtectedMemorySupported)
            {
#if NETSTANDARD2_0
                m_pbData = CryptoUtil.ProtectData(m_pbData, null, DataProtectionScope.CurrentUser);
#else
                ProtectedMemory.Protect(m_pbData, MemoryProtectionScope.SameProcess);
#endif

                m_mp = PbMemProt.ProtectedMemory;
                return;
            }

            byte[] pbKey32 = g_pbKey32;
            if (pbKey32 == null)
            {
                pbKey32 = CryptoRandom.Instance.GetRandomBytes(32);

                byte[] pbUpd = Interlocked.Exchange <byte[]>(ref g_pbKey32, pbKey32);
                if (pbUpd != null)
                {
                    pbKey32 = pbUpd;
                }
            }

            byte[] pbIV = new byte[12];
            MemUtil.UInt64ToBytesEx((ulong)m_lID, pbIV, 4);
            using (ChaCha20Cipher c = new ChaCha20Cipher(pbKey32, pbIV, true))
            {
                c.Encrypt(m_pbData, 0, m_pbData.Length);
            }
            m_mp = PbMemProt.ChaCha20;
        }
Exemplo n.º 28
0
 // This method will demand CryptographicPermissionFlags.Encrypt = true
 private void ProtectMemory()
 {
     if (m_length == 0)
     {
         return;
     }
     ProtectedMemory.Protect(m_buffer, MemoryProtectionScope.SameProcess);
 }
Exemplo n.º 29
0
 void IDisposable.Dispose()
 {
     if (--counts[memory] == 0)
     {
         counts.Remove(memory);
         ProtectedMemory.Protect(memory, scope);
     }
 }
Exemplo n.º 30
0
 public WalletEntry(byte[] privateKey, ECPoint publicKey, UInt160 publicKeyHash, bool compressed)
 {
     this.PrivateKey    = privateKey;
     this.PublicKey     = publicKey;
     this.PublicKeyHash = publicKeyHash;
     this.Compressed    = compressed;
     ProtectedMemory.Protect(privateKey, MemoryProtectionScope.SameProcess);
 }