コード例 #1
0
        /// <summary>
        /// Symmetrically encrypts the specified buffer using a randomly generated key.
        /// </summary>
        /// <param name="data">The data to encrypt.</param>
        /// <param name="encryptionVariables">Optional encryption variables to use; or <c>null</c> to use randomly generated ones.</param>
        /// <returns>
        /// The result of the encryption.
        /// </returns>
        public override SymmetricEncryptionResult Encrypt(byte[] data, SymmetricEncryptionVariables encryptionVariables)
        {
            Requires.NotNull(data, "data");

            IBuffer plainTextBuffer = CryptographicBuffer.CreateFromByteArray(data);
            IBuffer symmetricKeyMaterial, ivBuffer;

            if (encryptionVariables == null)
            {
                symmetricKeyMaterial = CryptographicBuffer.GenerateRandom((uint)this.SymmetricEncryptionKeySize / 8);
                ivBuffer             = CryptographicBuffer.GenerateRandom(SymmetricAlgorithm.BlockLength);
            }
            else
            {
                Requires.Argument(encryptionVariables.Key.Length == this.SymmetricEncryptionKeySize / 8, "key", "Incorrect length.");
                Requires.Argument(encryptionVariables.IV.Length == this.SymmetricEncryptionBlockSize / 8, "iv", "Incorrect length.");
                symmetricKeyMaterial = CryptographicBuffer.CreateFromByteArray(encryptionVariables.Key);
                ivBuffer             = CryptographicBuffer.CreateFromByteArray(encryptionVariables.IV);
            }

            var symmetricKey     = SymmetricAlgorithm.CreateSymmetricKey(symmetricKeyMaterial);
            var cipherTextBuffer = CryptographicEngine.Encrypt(symmetricKey, plainTextBuffer, ivBuffer);

            return(new SymmetricEncryptionResult(
                       symmetricKeyMaterial.ToArray(),
                       ivBuffer.ToArray(),
                       cipherTextBuffer.ToArray()));
        }
コード例 #2
0
        /// <summary>
        /// Fills the specified buffer with cryptographically strong random generated data.
        /// </summary>
        /// <param name="buffer">The buffer to fill.</param>
        public override void FillCryptoRandomBuffer(byte[] buffer)
        {
            Requires.NotNull(buffer, "buffer");
            var windowsBuffer = CryptographicBuffer.GenerateRandom((uint)buffer.Length);

            Array.Copy(windowsBuffer.ToArray(), buffer, buffer.Length);
        }
コード例 #3
0
        public async Task <object> GenerateLocalPasswordAsync()
        {
            //var response = await _protoService.SendAsync(new GetTonWalletPasswordSalt());
            //if (response is TonWalletPasswordSalt passwordSalt)
            //{
            //    var passwordBuffer = CryptographicBuffer.GenerateRandom(64);
            //    var saltBuffer = CryptographicBuffer.GenerateRandom(32);

            //    CryptographicBuffer.CopyToByteArray(passwordBuffer, out byte[] password);
            //    CryptographicBuffer.CopyToByteArray(saltBuffer, out byte[] salt);

            //    System.Buffer.BlockCopy(passwordSalt.Salt.ToArray(), 0, password, 32, 32);

            //    return new ByteTuple(password, salt);
            //}
            //else if (response is Error error)
            //{
            //    return new Ton.Tonlib.Api.Error(error.Code, error.Message);
            //}

            //return null;

            var passwordBuffer = CryptographicBuffer.GenerateRandom(64);
            var saltBuffer     = CryptographicBuffer.GenerateRandom(32);

            CryptographicBuffer.CopyToByteArray(passwordBuffer, out byte[] password);
            CryptographicBuffer.CopyToByteArray(saltBuffer, out byte[] salt);

            return(new ByteTuple(password, salt));
        }
コード例 #4
0
        public MainPage()
        {
            this.InitializeComponent();
            Console.SetOut(new DebugWriter());

            TlsPskConnection.Seed(CryptographicBuffer.GenerateRandom(32).ToArray());
        }
コード例 #5
0
ファイル: DataPadder.cs プロジェクト: BigFun123/Massive
        /// <inheritdoc />
        public override void ForwardProcessDataStream(Stream inStream, Stream outStream, Dictionary <string, string> options, out long writtenBytes)
        {
            if (options == null)
            {
                throw new ArgumentException("Options dictionary was null", "options");
            }
            else if (!options.ContainsKey(paddedSizeOptionName) || !options.ContainsKey(padTypeOptionName) || !options.ContainsKey(padExceptionOptionName))
            {
                throw new ArgumentException("Options dictionary did not contain the necessary padding options", "options");
            }

            int             paddingSize;
            DataPaddingType padType;
            bool            padException;

            if (!int.TryParse(options[paddedSizeOptionName], out paddingSize) || !bool.TryParse(options[padExceptionOptionName], out padException))
            {
                throw new ArgumentException("Options dictionary contained invalid options for DataPadder", "options");
            }

            try { padType = (DataPaddingType)Enum.Parse(typeof(DataPaddingType), options[padTypeOptionName]); }
            catch (ArgumentException) { throw new ArgumentException("Options dictionary contained invalid options for DataPadder", "options"); }

            if (padException && inStream.Length > paddingSize - 4)
            {
                throw new ArgumentException("Options dictionary contained invalid options for DataPadder. Not enough data padding was allowed", "options");
            }

            paddingSize = paddingSize - 4 - (int)inStream.Length;
            if (paddingSize < 0)
            {
                paddingSize = 0;
            }

            byte[] padData;

            if (padType == DataPaddingType.Random)
            {
#if NETFX_CORE
                CryptographicBuffer.CopyToByteArray(CryptographicBuffer.GenerateRandom((uint)paddingSize), out padData);
#else
                padData = new byte[paddingSize];
                rand.GetBytes(padData);
#endif
            }
            else
            {
                padData = new byte[paddingSize];
            }

            StreamTools.Write(inStream, 0, inStream.Length, outStream, 8192, double.MaxValue, int.MaxValue);

            if (paddingSize != 0)
            {
                outStream.Write(padData, 0, padData.Length);
            }

            outStream.Write(BitConverter.GetBytes(paddingSize + 4), 0, 4);
            writtenBytes = outStream.Position;
        }
コード例 #6
0
        /// <summary>
        /// 根据加密算法和长度生成一个对称密钥,现在尚不能导出密钥
        /// </summary>
        /// <param name="strAlgName">算法</param>
        /// <param name="keyLength">密钥长度</param>
        /// <returns></returns>
        public static CryptographicKey GenerateKey(string strAlgName, uint keyLength)
        {
            SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName);
            IBuffer keyMaterial = CryptographicBuffer.GenerateRandom(keyLength);

            return(objAlg.CreateSymmetricKey(keyMaterial));
        }
コード例 #7
0
ファイル: HMAC.cs プロジェクト: vaginessa/BookmarkBrowser
        public byte[] ComputeHash(byte[] buffer, int offset, int count)
        {
#if WINDOWS_STORE
            MacAlgorithmProvider provider = MacAlgorithmProvider.OpenAlgorithm(algorithmName);

            CryptographicKey hmacKey;
            if (Key != null)
            {
                hmacKey = provider.CreateKey(CryptographicBuffer.CreateFromByteArray(Key));
            }
            else
            {
                hmacKey = provider.CreateKey(CryptographicBuffer.GenerateRandom(provider.MacLength));
            }

            IBuffer hmacValue = CryptographicEngine.Sign(hmacKey, CryptographicBuffer.CreateFromByteArray(buffer));

            byte[] result;
            CryptographicBuffer.CopyToByteArray(hmacValue, out result);

            return(result);
#else
            return(hmac.ComputeHash(buffer, offset, count));
#endif
        }
コード例 #8
0
    /// <summary>
    /// Создает случайную последовательность размера lenght бит
    /// </summary>
    /// <param name="lenght">размер последовательности</param>
    /// <returns>Случайная последовательсноть</returns>
    public string Random(UInt32 lenght)
    {
        string RandTextOutput;

        RandTextOutput = CryptographicBuffer.EncodeToBase64String(CryptographicBuffer.GenerateRandom((lenght + 7) / 8));
        return(RandTextOutput);
    }
コード例 #9
0
ファイル: ExtensionManager.cs プロジェクト: Losses/DarkPlayer
        internal static void GenerateEncryptionKey()
        {
            var randomData           = CryptographicBuffer.GenerateRandom(64);
            var randomDataSerialized = CryptographicBuffer.EncodeToHexString(randomData);

            SettingsManager.Instance.SetValue(randomDataSerialized, "EncryptionKey");
        }
コード例 #10
0
ファイル: EncryptionProvider.cs プロジェクト: hmaiga/PaZword
        public PasswordCredential GenerateSecretKeys()
        {
            string userName = CryptographicBuffer.EncodeToBase64String(CryptographicBuffer.GenerateRandom(_cryptingProvider.BlockLength));
            string password = CryptographicBuffer.EncodeToBase64String(CryptographicBuffer.GenerateRandom(IVLength));

            return(new PasswordCredential(PaZwordSecretKeysName, userName, password));
        }
コード例 #11
0
        private int RandomNumber(int max)
        {
            var b   = CryptographicBuffer.GenerateRandom(4).ToArray();
            var val = BitConverter.ToUInt32(b, 0);

            return((int)(val % max));
        }
コード例 #12
0
        /// <summary>
        /// Encrypt value using password.
        /// </summary>
        /// <param name="value">Value to encrypt.</param>
        /// <param name="key">Key that is used for encryption.</param>
        /// <returns>A buffer with the encrypted data is returned.</returns>
        public IBuffer Encrypt(string value, string key)
        {
            // Create a Sha256 from key.
            var     passwordBuffer = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8);
            var     hashProvider   = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256);
            IBuffer keyMaterial    = hashProvider.HashData(passwordBuffer);

            // Create an Aes256 with CBC and Pkcs7
            var aesProvider         = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
            CryptographicKey aesKey = aesProvider.CreateSymmetricKey(keyMaterial);

            // Create a random IV so the password can be used more than once.
            IBuffer iv = CryptographicBuffer.GenerateRandom(aesProvider.BlockLength);

            // Encrypt value.
            var     data      = CryptographicBuffer.ConvertStringToBinary(value, BinaryStringEncoding.Utf8);
            IBuffer encrypted = CryptographicEngine.Encrypt(aesKey, data, iv);

            // Insert random generated IV before encrypted message because it will be needed at decryption.
            IBuffer result = CryptographicBuffer.CreateFromByteArray(new byte[iv.Length + encrypted.Length]);

            iv.CopyTo(0, result, 0, iv.Length);
            encrypted.CopyTo(0, result, iv.Length, encrypted.Length);

            return(result);
        }
コード例 #13
0
 public TokenManager()
 {
     _lastSecretGeneration = DateTime.MinValue; //in order to force the update
     _hash           = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1).CreateHash();
     _secret         = CryptographicBuffer.GenerateRandom(10).ToArray();
     _previousSecret = CryptographicBuffer.GenerateRandom(10).ToArray();
 }
コード例 #14
0
        public static byte[] GenerateAESKey()
        {
            var buf = CryptographicBuffer.GenerateRandom(AESKeyLengthInBits / 8);

            CryptographicBuffer.CopyToByteArray(buf, out var ret);
            return(ret);
        }
コード例 #15
0
        public String SampleDeriveFromPbkdf(
            String strAlgName,
            UInt32 targetSize)
        {
            // Open the specified algorithm.
            KeyDerivationAlgorithmProvider objKdfProv = KeyDerivationAlgorithmProvider.OpenAlgorithm(strAlgName);

            // Create a buffer that contains the secret used during derivation.

            IBuffer buffSecret = CryptographicBuffer.ConvertStringToBinary(SampleConfiguration.strSecret, BinaryStringEncoding.Utf8);

            // Create a random salt value.
            IBuffer buffSalt = CryptographicBuffer.GenerateRandom(32);

            // Specify the number of iterations to be used during derivation.
            UInt32 iterationCount = 10000;

            // Create the derivation parameters.
            KeyDerivationParameters pbkdf2Params = KeyDerivationParameters.BuildForPbkdf2(buffSalt, iterationCount);

            // Create a key from the secret value.
            CryptographicKey keyOriginal = objKdfProv.CreateKey(buffSecret);

            // Derive a key based on the original key and the derivation parameters.
            IBuffer keyDerived = CryptographicEngine.DeriveKeyMaterial(
                keyOriginal,
                pbkdf2Params,
                targetSize);

            // Encode the key to a Base64 value (for display)
            String strKeyBase64 = CryptographicBuffer.EncodeToHexString(keyDerived);

            // Return the encoded string
            return(strKeyBase64);
        }
コード例 #16
0
        public static string InitializeEncryptionKey()
        {
            var randomBuffer = CryptographicBuffer.GenerateRandom(24);

            // IBuffer to String
            return(CryptographicBuffer.EncodeToBase64String(randomBuffer));
        }
コード例 #17
0
        public void AddNonce()
        {
            var    buffer    = CryptographicBuffer.GenerateRandom(10);
            string randomHex = CryptographicBuffer.EncodeToHexString(buffer);

            Add("nonce", randomHex);
        }
コード例 #18
0
        private CryptographicKey GenerateSymmetricKey()
        {
            String algName = AlgorithmNames.SelectionBoxItem.ToString();
            UInt32 keySize = UInt32.Parse(KeySizes.SelectionBoxItem.ToString());

            CryptographicKey key;
            // Create an SymmetricKeyAlgorithmProvider object for the algorithm specified on input.
            SymmetricKeyAlgorithmProvider Algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(algName);

            EncryptDecryptText.Text += "*** Sample Encryption Algorithm\n";
            EncryptDecryptText.Text += "    Algorithm Name: " + Algorithm.AlgorithmName + "\n";
            EncryptDecryptText.Text += "    Key Size: " + keySize + "\n";
            EncryptDecryptText.Text += "    Block length: " + Algorithm.BlockLength + "\n";

            // Generate a symmetric key.
            IBuffer keymaterial = CryptographicBuffer.GenerateRandom((keySize + 7) / 8);

            try
            {
                key = Algorithm.CreateSymmetricKey(keymaterial);
            }
            catch (ArgumentException ex)
            {
                EncryptDecryptText.Text += ex.Message + "\n";
                EncryptDecryptText.Text += "An invalid key size was specified for the given algorithm.";
                return(null);
            }
            return(key);
        }
コード例 #19
0
        void CreateHMAC(String strMsg, String strAlgName, out IBuffer buffMsg, out CryptographicKey hmacKey, out IBuffer buffHMAC)
        {
            // Create a MacAlgorithmProvider object for the specified algorithm.
            MacAlgorithmProvider objMacProv = MacAlgorithmProvider.OpenAlgorithm(strAlgName);

            // Demonstrate how to retrieve the name of the algorithm used.
            String strNameUsed = objMacProv.AlgorithmName;

            // Create a buffer that contains the message to be signed.
            BinaryStringEncoding encoding = BinaryStringEncoding.Utf8;

            buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding);

            // Create a key to be signed with the message.
            IBuffer buffKeyMaterial = CryptographicBuffer.GenerateRandom(objMacProv.MacLength);

            hmacKey = objMacProv.CreateKey(buffKeyMaterial);

            // Sign the key and message together.
            buffHMAC = CryptographicEngine.Sign(hmacKey, buffMsg);

            // Verify that the HMAC length is correct for the selected algorithm
            if (buffHMAC.Length != objMacProv.MacLength)
            {
                throw new Exception("Error computing digest");
            }
        }
コード例 #20
0
        public async Task Should_produce_read_bytes_hash(int bufferSize)
        {
            var data = CryptographicBuffer.GenerateRandom(2048);

            var expected = HashAlgorithmProvider
                           .OpenAlgorithm(HashAlgorithmNames.Sha256)
                           .HashData(data);

            using (var file = new InMemoryRandomAccessStream())
            {
                await file.WriteAsync(data);

                file.Seek(0);

                var buffer = WindowsRuntimeBuffer.Create(bufferSize);

                using (var hashed = new HashedInputStream(file))
                {
                    for (var i = 0; i < 8; i++)
                    {
                        await hashed.ReadAsync(
                            buffer, buffer.Capacity);
                    }

                    var hash = hashed.GetHashAndReset();
                    Assert.Equal(expected.ToArray(), hash.ToArray());
                }
            }
        }
コード例 #21
0
        public static IBuffer Encrypt(IBuffer data,
                                      CryptographicKey key,
                                      out IBuffer iv,
                                      String AlgorithmName = null)
        {
            //declares
            var strAlgName = AlgorithmName != null ? AlgorithmName : DefaultAlgorithm;

            iv = null;

            // Open a symmetric algorithm provider for the specified algorithm.
            var objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName);

            // Determine whether the message length is a multiple of the block length.
            // This is not necessary for PKCS #7 algorithms which automatically pad the
            // message to an appropriate length.
            if (!strAlgName.Contains("PKCS7"))
            {
                if ((data.Length % objAlg.BlockLength) != 0)
                {
                    throw new Exception("Message buffer length must be multiple of block length.");
                }
            }

            // CBC algorithms require an initialization vector. Here, a random
            // number is used for the vector.
            if (strAlgName.Contains("CBC"))
            {
                iv = CryptographicBuffer.GenerateRandom(objAlg.BlockLength);
            }

            // Encrypt the data and return.
            return(CryptographicEngine.Encrypt(key, data, iv));
        }
コード例 #22
0
        public SymmetricKeyEncryptor CreateEncryptor()
        {
            if (disposed)
            {
                throw new ObjectDisposedException("DES");
            }

            var buffer = CryptographicBuffer.CreateFromByteArray(Key);
            SymmetricKeyAlgorithmProvider algorithm;
            CryptographicKey key;
            string           algorithmName;
            IBuffer          iv = null;

            switch (Mode)
            {
            case CipherMode.CBC: algorithmName = SymmetricAlgorithmNames.DesCbc; break;

            case CipherMode.ECB: algorithmName = SymmetricAlgorithmNames.DesEcb; break;

            default: throw new IndexOutOfRangeException("Mode");
            }

            algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(algorithmName);
            key       = algorithm.CreateSymmetricKey(buffer);

            if (Mode == CipherMode.CBC)
            {
                iv = CryptographicBuffer.GenerateRandom(algorithm.BlockLength);
            }

            return(new SymmetricKeyEncryptor(algorithm, key, iv));
        }
コード例 #23
0
 /// <summary>
 /// Generate a cryptographically secure random number
 /// </summary>
 /// <param name="length">Length of the desired number in bytes</param>
 /// <returns></returns>
 public static byte[] GenerateRandomBytes(uint length)
 {
     IBuffer buffer = CryptographicBuffer.GenerateRandom(length);
     byte[] rand = new byte[length];
     CryptographicBuffer.CopyToByteArray(buffer, out rand);
     return rand;
 }
コード例 #24
0
ファイル: Messages.xaml.cs プロジェクト: nevver/ChronosClient
        // Encryption and authentication method for recipient
        private void AuthenticatedEncryptionRecipient(
            String strMsg,
            String strAlgName,
            UInt32 keyLength)
        {
            // Open a SymmetricKeyAlgorithmProvider object for the specified algorithm.
            SymmetricKeyAlgorithmProvider objAlgProv = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName);

            // Create a buffer that contains the data to be encrypted.
            IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding);

            // Generate a symmetric key.
            keyMaterialRecipient       = CryptographicBuffer.GenerateRandom(keyLength);
            keyMaterialStringRecipient = CryptographicBuffer.EncodeToBase64String(keyMaterialRecipient);
            keyRecipient = objAlgProv.CreateSymmetricKey(keyMaterialRecipient);

            // Generate a new nonce value.
            buffNonceRecipient = GetNonce();

            // Encrypt and authenticate the message.
            EncryptedAndAuthenticatedData objEncrypted = CryptographicEngine.EncryptAndAuthenticate(
                keyRecipient,
                buffMsg,
                buffNonceRecipient,
                null);

            encryptedMessageDataRecipient       = objEncrypted.EncryptedData;
            authenticationTagRecipient          = objEncrypted.AuthenticationTag;
            encryptedMessageDataStringRecipient = CryptographicBuffer.EncodeToBase64String(encryptedMessageDataRecipient);
            authenticationTagStringRecipient    = CryptographicBuffer.EncodeToBase64String(authenticationTagRecipient);
            nonceStringRecipient = CryptographicBuffer.EncodeToBase64String(buffNonceRecipient);
        }
コード例 #25
0
        public void VerifyHeaders_should_detect_empty_document()
        {
            var doc  = new XDocument();
            var hash = CryptographicBuffer.GenerateRandom(32);

            Assert.False(FileFormat.VerifyHeaders(hash, doc));
        }
コード例 #26
0
ファイル: CryptoUtils.cs プロジェクト: UWPX/UWPX-Client
        //--------------------------------------------------------Attributes:-----------------------------------------------------------------\\
        #region --Attributes--


        #endregion
        //--------------------------------------------------------Constructor:----------------------------------------------------------------\\
        #region --Constructors--


        #endregion
        //--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\
        #region --Set-, Get- Methods--


        #endregion
        //--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\
        #region --Misc Methods (Public)--
        public static byte[] NextBytesSecureRandom(uint length)
        {
            Windows.Storage.Streams.IBuffer buf = CryptographicBuffer.GenerateRandom(length);
            byte[] bytes = new byte[length];
            CryptographicBuffer.CopyToByteArray(buf, out bytes);
            return(bytes);
        }
コード例 #27
0
        /**
         * Genera un string plano con dos secciones, una random y la contraseña MD5
         * complementada con una APP_KEY obtenida desde las propiedades de la aplicación.
         * Contraseñas vacías no son permitidas.
         *
         * @param password
         * @return texto plano con hash
         * @throws java.lang.Exception */
        public static string GetHash(string password)
        {
            IBuffer salt    = CryptographicBuffer.GenerateRandom(SALT_LEN);
            string  APP_KEY = "srgw4g347weh578ber67nw6cw45rgEtq35QGW";

            return(CryptographicBuffer.EncodeToBase64String(salt) + "$" + Hash(password, APP_KEY));
        }
コード例 #28
0
        public virtual void NextBytes(byte[] bytes, int start, int len)
        {
            if (start < 0)
            {
                throw new ArgumentException("Start offset cannot be negative", "start");
            }
            if (bytes.Length < (start + len))
            {
                throw new ArgumentException("Byte array too small for requested offset and length");
            }

            if (bytes.Length == len && start == 0)
            {
                NextBytes(bytes);
            }
            else
            {
#if NETFX_CORE
                byte[] tmpBuf = null;
                var    buffer = CryptographicBuffer.GenerateRandom((uint)bytes.Length);
                CryptographicBuffer.CopyToByteArray(buffer, out tmpBuf);
#else
                byte[] tmpBuf = new byte[len];
                NextBytes(tmpBuf);
#endif
                Array.Copy(tmpBuf, 0, bytes, start, len);
            }
        }
コード例 #29
0
        private static byte[] CreateCryptoRandomByteArray(int byteLength)
        {
            byte[]  arr;
            IBuffer buffer = CryptographicBuffer.GenerateRandom((uint)byteLength);

            CryptographicBuffer.CopyToByteArray(buffer, out arr);
            return(arr);
        }
コード例 #30
0
        /// <summary>
        /// Calculates a Curve25519 signature.
        /// </summary>
        /// <param name="privateKey">The private Curve25519 key to create the signature with.</param>
        /// <param name="message">The message to sign.</param>
        /// <returns>64 byte signature</returns>
        public byte[] calculateSignature(byte[] privateKey, byte[] message)
        {
            byte[]  random;
            IBuffer rnd = CryptographicBuffer.GenerateRandom(64);

            CryptographicBuffer.CopyToByteArray(rnd, out random);
            return(provider.calculateSignature(random, privateKey, message));
        }