コード例 #1
0
 public static string Decrypt(byte[] encryptedData, string pw, string salt)
 {
     IBuffer pwBuffer     = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8);
     IBuffer saltBuffer   = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf16LE);
     IBuffer cipherBuffer = CryptographicBuffer.CreateFromByteArray(encryptedData);
     KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
     KeyDerivationParameters        pbkdf2Parms           = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000);
     CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer);
     IBuffer          keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32); CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer);
     IBuffer          saltMaterial             = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16);
     string           keyMaterialString        = CryptographicBuffer.EncodeToBase64String(keyMaterial);
     string           saltMaterialString       = CryptographicBuffer.EncodeToBase64String(saltMaterial);
     SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
     CryptographicKey symmKey      = symProvider.CreateSymmetricKey(keyMaterial);
     IBuffer          resultBuffer = CryptographicEngine.Decrypt(symmKey, cipherBuffer, saltMaterial);
     string           result       = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, resultBuffer); return(result);
 }
コード例 #2
0
        public void GenerateKey(string password, string salt, out Windows.Storage.Streams.IBuffer keyMaterial, out Windows.Storage.Streams.IBuffer iv)
        {
            IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf8);
            KeyDerivationParameters        keyParams = KeyDerivationParameters.BuildForSP800108(saltBuffer, GetNonce());
            KeyDerivationAlgorithmProvider kdf       = KeyDerivationAlgorithmProvider.OpenAlgorithm(Encryptor.Settings.KeyDerivationAlgorithm);
            IBuffer          passwordBuffer          = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
            CryptographicKey keyOriginal             = kdf.CreateKey(passwordBuffer);

            int     keySize    = 256;
            int     ivSize     = 128 / 8;
            uint    totalData  = (uint)(keySize + ivSize);
            IBuffer keyDerived = CryptographicEngine.DeriveKeyMaterial(keyOriginal, keyParams, totalData);

            byte[] keyMaterialBytes = keyDerived.ToArray();
            keyMaterial = WindowsRuntimeBuffer.Create(keyMaterialBytes, 0, keySize, keySize);
            iv          = WindowsRuntimeBuffer.Create(keyMaterialBytes, keySize, ivSize, ivSize);
        }
コード例 #3
0
ファイル: ES3Crypto.cs プロジェクト: frank731/topdown
        public override void Decrypt(Stream input, Stream output, string password, int bufferSize)
        {
#if NETFX_CORE
            var thisIV = new byte[ivSize];
            input.Read(thisIV, 0, ivSize);
            var iv = thisIV.AsBuffer();

            var pwBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);

            var keyDerivationProvider           = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
            KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(iv, pwIterations);
            // Create a key based on original key and derivation parameters.
            CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer);
            IBuffer          keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, keySize);

            var provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
            var key      = provider.CreateSymmetricKey(keyMaterial);

            // Get the input stream as an IBuffer.
            IBuffer msg;
            using (var ms = new MemoryStream())
            {
                input.CopyTo(ms);
                msg = ms.ToArray().AsBuffer();
            }

            var buffDecrypt = CryptographicEngine.Decrypt(key, msg, iv);

            output.Write(buffDecrypt.ToArray(), 0, (int)buffDecrypt.Length);
#else
            using (var alg = Aes.Create())
            {
                var thisIV = new byte[ivSize];
                input.Read(thisIV, 0, ivSize);
                alg.IV = thisIV;

                var key = new Rfc2898DeriveBytes(password, alg.IV, pwIterations);
                alg.Key = key.GetBytes(keySize);

                using (var decryptor = alg.CreateDecryptor())
                    using (var cryptoStream = new CryptoStream(input, decryptor, CryptoStreamMode.Read))
                        CopyStream(cryptoStream, output, bufferSize);
            }
#endif
            output.Position = 0;
        }
コード例 #4
0
        /**** Cryptography *****/

        public static string Hash(string data)
        {
            var bytes = Encoding.UTF8.GetBytes(data);

#if NETFX_CORE
            /*if (sha1 == null)
             *      sha1 = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha1);*/
            throw new NotImplementedException("WinRT...");
#else
            if (sha1 == null)
            {
                sha1 = Encryptor.Current.CreateHash();
            }
            var hash = sha1.Compute20(bytes);
            return(BytesToString(hash));
#endif
        }
コード例 #5
0
        private KeyMaterial(SecureString password, byte[] salt, int iterations)
        {
            if (iterations < 1000)
            {
                throw new SecurityException("The KDF iterations should not be lower than 1000");
            }

            if (password == null)
            {
                throw new ArgumentNullException(nameof(password));
            }

            if (salt == null)
            {
                throw new ArgumentNullException(nameof(salt));
            }

            // Possibly security critical
#if WINDOWS_UWP
            var passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password.GetString(), BinaryStringEncoding.Utf8);
            var saltBuffer     = CryptographicBuffer.CreateFromByteArray(salt);

            var keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
            var pbkdf2Parms           = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, (uint)iterations);

            var keyOriginal        = keyDerivationProvider.CreateKey(passwordBuffer);
            var keyMaterial        = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32);
            var derivedPasswordKey = keyDerivationProvider.CreateKey(passwordBuffer);
            this.key = keyMaterial.ToArray().ZipAsBytes();
            this.initialisationVector = keyMaterial.ToArray().GetBytes(16).ZipAsBytes();
#else
            using (Rfc2898DeriveBytes keyMaterial = new Rfc2898DeriveBytes(password.GetString(), salt, iterations))
            {
                this.key = keyMaterial.GetBytes(32).ZipAsBytes();
                keyMaterial.Reset();
                this.initialisationVector = keyMaterial.GetBytes(16).ZipAsBytes();
            }
#endif

            this.salt = salt.ZipAsBytes();

            // Let us pin our variables so that the GC is not moving them around creating a lot of copies
            this.saltHandle = GCHandle.Alloc(this.salt, GCHandleType.Pinned);
            this.initialisationVectorHandle = GCHandle.Alloc(this.initialisationVector, GCHandleType.Pinned);
            this.keyHandle = GCHandle.Alloc(this.key, GCHandleType.Pinned);
        }
コード例 #6
0
        private IBuffer PBKDF2(IBuffer buffSecret, IBuffer buffSalt)
        {
            var algorithm        = KeyDerivationAlgorithmNames.Pbkdf2Sha256;
            var iterationCountIn = 100000u;
            var targetSize       = 32u;

            var provider     = KeyDerivationAlgorithmProvider.OpenAlgorithm(algorithm);
            var pbkdf2Params = KeyDerivationParameters.BuildForPbkdf2(buffSalt, iterationCountIn);
            var keyOriginal  = provider.CreateKey(buffSecret);

            var keyDerived = CryptographicEngine.DeriveKeyMaterial(
                keyOriginal,
                pbkdf2Params,
                targetSize
                );

            return(keyDerived);
        }
コード例 #7
0
ファイル: Encryptor.cs プロジェクト: jscarrott/secunote
        /// <summary>
        ///     Turns string password into a hash for use in AES
        ///     TODO remove magic numbers
        /// </summary>
        /// <param name="password"></param>
        public async Task CreateAesKey(string password)
        {
            var hashProvider   = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha512);
            var passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
            var salt           = await GetSalt();

            //var salt = await GenerateAndSaveSalt();

            var keyCreationParameters = KeyDerivationParameters.BuildForPbkdf2(salt, 1000);

            var originalKey = hashProvider.CreateKey(passwordBuffer);

            var hashedKeyMaterial = CryptographicEngine.DeriveKeyMaterial(originalKey, keyCreationParameters, 32);
            var aesProvider       = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesGcm);
            var key = aesProvider.CreateSymmetricKey(hashedKeyMaterial);

            aesKey = key;
        }
コード例 #8
0
        private string DecodeAES(string cipherText)
        {
            var pwBuffer     = CryptographicBuffer.ConvertStringToBinary(AES_KEY, BinaryStringEncoding.Utf8);
            var cipherBuffer = CryptographicBuffer.ConvertStringToBinary(cipherText, BinaryStringEncoding.Utf8);

            KeyDerivationAlgorithmProvider keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");

            var name = SymmetricAlgorithmNames.AesCbcPkcs7;

            SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(name);

            CryptographicKey symmKey = symProvider.CreateSymmetricKey(pwBuffer);

            var    resultBuffer = CryptographicEngine.Decrypt(symmKey, cipherBuffer, null);
            string result       = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, resultBuffer);

            return(result);
        }
コード例 #9
0
        public static string Decrypt(byte[] encryptval, string pw, string salt)
        {
            IBuffer pwBuffer     = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8);
            IBuffer saltBuffer   = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf16LE);
            IBuffer cipherBuffer = CryptographicBuffer.CreateFromByteArray(encryptval);
            KeyDerivationAlgorithmProvider key  = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
            KeyDerivationParameters        parm = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000);
            CryptographicKey ckey            = key.CreateKey(pwBuffer);
            IBuffer          keyMaterial     = CryptographicEngine.DeriveKeyMaterial(ckey, parm, 32);
            CryptographicKey dkey            = key.CreateKey(pwBuffer);
            IBuffer          saltMaterial    = CryptographicEngine.DeriveKeyMaterial(ckey, parm, 16);
            SymmetricKeyAlgorithmProvider sp = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
            CryptographicKey symmKey         = sp.CreateSymmetricKey(keyMaterial);
            IBuffer          resultBuffer    = CryptographicEngine.Decrypt(symmKey, cipherBuffer, saltMaterial);
            string           result          = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, resultBuffer);

            return(result);
        }
コード例 #10
0
    /// <summary>
    /// Шифрование текста
    /// </summary>
    /// <param name="SourceText">Исходный (открытый) текст</param>
    /// <param name="InputKey">Ключ шифрование</param>
    /// <param name="AlgorythmName">Имя алгоритма шифрования</param>
    /// <returns>Зашифрованный текст</returns>
    public string EncryptMode(string SourceText, string InputKey, string AlgorythmName, string IV, string KeySize)
    {
        SymmetricKeyAlgorithmProvider Algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(AlgorythmName);
        IBuffer KeyBuffer  = CryptographicBuffer.ConvertStringToBinary(InputKey, BinaryStringEncoding.Utf16LE);
        IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary("ll234hl@kljh5:Annc!6002mz", BinaryStringEncoding.Utf16LE);

        //CryptoKey = Algorithm.CreateSymmetricKey(KeyBuffer);

//#########################
        KeyDerivationAlgorithmProvider keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha512);

        KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 10000);

        CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(KeyBuffer);

        IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, Convert.ToUInt32(KeySize) / 8);

        //string test = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, keyMaterial);

        CryptoKey = Algorithm.CreateSymmetricKey(keyMaterial);
//###############

        // CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer);



        //Надо присваивать IV пользовательское значение или генерированное значение IV
        if (AlgorythmName.Contains("CBC"))
        {
            IVBuffer = CryptographicBuffer.ConvertStringToBinary(IV, BinaryStringEncoding.Utf16LE);
        }

        // Set the data to encrypt.
        SourceTextBuffer = CryptographicBuffer.ConvertStringToBinary(SourceText, BinaryStringEncoding.Utf16LE);

        // Encrypt
        EncryptBuffer = Windows.Security.Cryptography.Core.CryptographicEngine.Encrypt(CryptoKey, SourceTextBuffer, IVBuffer);
        //Convert to Base64
        EncryptTextOutput = CryptographicBuffer.EncodeToBase64String(EncryptBuffer);
        string test = CryptographicBuffer.EncodeToBase64String(keyMaterial);

        //return test;//
        return(EncryptTextOutput);
    }
コード例 #11
0
        public static byte[] Encrypt(string plainText, string pw, string sult)
        {
            IBuffer pwBuffer    = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8);
            IBuffer sultBuffer  = CryptographicBuffer.ConvertStringToBinary(sult, BinaryStringEncoding.Utf16LE);
            IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf16LE);
            KeyDerivationAlgorithmProvider key  = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
            KeyDerivationParameters        parm = KeyDerivationParameters.BuildForPbkdf2(sultBuffer, 1000);
            CryptographicKey ckey            = key.CreateKey(pwBuffer);
            IBuffer          keyMaterial     = CryptographicEngine.DeriveKeyMaterial(ckey, parm, 32);
            CryptographicKey dkey            = key.CreateKey(pwBuffer);
            IBuffer          sulltMaterial   = CryptographicEngine.DeriveKeyMaterial(dkey, parm, 16);
            SymmetricKeyAlgorithmProvider sp = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
            CryptographicKey symKey          = sp.CreateSymmetricKey(keyMaterial);
            IBuffer          resultBuffer    = CryptographicEngine.Encrypt(symKey, plainBuffer, sulltMaterial);

            byte[] result;
            CryptographicBuffer.CopyToByteArray(resultBuffer, out result);
            return(result);
        }
コード例 #12
0
        private byte[] EncryptDataV2(byte[] bytes, string pw, string salt)
        {
            var base64Text = Convert.ToBase64String(bytes);


            var pwBuffer    = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8);
            var saltBuffer  = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf16LE);
            var plainBuffer = CryptographicBuffer.ConvertStringToBinary(base64Text, BinaryStringEncoding.Utf16LE);


            // Derive key material for password size 32 bytes for AES256 algorithm
            var keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha1);
            // using salt and 1000 iterations
            var pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000);

            // create a key based on original key and derivation parmaters
            var keyOriginal  = keyDerivationProvider.CreateKey(pwBuffer);
            var keyMaterial  = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32);
            var derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer);

            // derive buffer to be used for encryption salt from derived password key
            var saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16);

            // display the buffers – because KeyDerivationProvider always gets cleared after each use, they are very similar unforunately
            //var keyMaterialString = CryptographicBuffer.EncodeToBase64String(keyMaterial);
            //var saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial);

            var symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
            // create symmetric key from derived password key
            var symmKey = symProvider.CreateSymmetricKey(keyMaterial);

            // encrypt data buffer using symmetric key and derived salt material
            var resultBuffer = CryptographicEngine.Encrypt(symmKey, plainBuffer, saltMaterial);

            byte[] result;
            CryptographicBuffer.CopyToByteArray(resultBuffer, out result);
            if (result.Length > 1000000)
            {
                GC.Collect();
            }
            return(result);
        }
コード例 #13
0
        /// <summary>
        /// Generates an encryption key derived using a password, a random salt, and specified number of rounds of PBKDF2
        ///
        /// TODO: pass in password via SecureString?
        /// </summary>
        /// <param name="password"></param>
        /// <param name="salt"></param>
        /// <returns></returns>
        public static IBuffer GetEncryptionKey(string password, string salt)
        {
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentException("Password is empty");
            }
            if (salt == null || salt.Length == 0)
            {
                throw new ArgumentException("Salt is empty");
            }

            KeyDerivationAlgorithmProvider pbkdf2 = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha1);

            IBuffer          buffSecret = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
            CryptographicKey key        = pbkdf2.CreateKey(buffSecret);

            KeyDerivationParameters parameters = KeyDerivationParameters.BuildForPbkdf2(CryptographicBuffer.DecodeFromBase64String(salt), PBKDF2_ITERATIONS);

            return(CryptographicEngine.DeriveKeyMaterial(key, parameters, KEY_SIZE_BYTES));
        }
コード例 #14
0
ファイル: Encryptor.cs プロジェクト: thebChip/bchip
        private static void GenerateKeyMaterial(IBuffer passwordBuffer, IBuffer saltBuffer, uint iterationCount, out IBuffer keyMaterial, out IBuffer iv)
        {
            KeyDerivationParameters kdfParameters = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, iterationCount);

            // Get a KDF provider for PBKDF2, and store the source password in a Cryptographic Key
            KeyDerivationAlgorithmProvider kdf = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha256);
            CryptographicKey passwordSourceKey = kdf.CreateKey(passwordBuffer);

            // Generate key material from the source password, salt, and iteration count.  Only call DeriveKeyMaterial once,
            // since calling it twice will generate the same data for the key and IV.
            int     keySize         = 256 / 8;
            int     ivSize          = 128 / 8;
            uint    totalDataNeeded = (uint)(keySize + ivSize);
            IBuffer keyAndIv        = CryptographicEngine.DeriveKeyMaterial(passwordSourceKey, kdfParameters, totalDataNeeded);

            // Split the derived bytes into a seperate key and IV
            byte[] keyMaterialBytes = keyAndIv.ToArray();
            keyMaterial = WindowsRuntimeBuffer.Create(keyMaterialBytes, 0, keySize, keySize);
            iv          = WindowsRuntimeBuffer.Create(keyMaterialBytes, keySize, ivSize, ivSize);
        }
コード例 #15
0
        /// <summary>
        /// Derives a cryptographically strong key from the specified password.
        /// </summary>
        /// <param name="password">The user-supplied password.</param>
        /// <param name="salt">The salt.</param>
        /// <param name="iterations">The rounds of computation to use in deriving a stronger key. The larger this is, the longer attacks will take.</param>
        /// <param name="keySizeInBytes">The desired key size in bytes.</param>
        /// <returns>The generated key.</returns>
        public override byte[] DeriveKeyFromPassword(string password, byte[] salt, int iterations, int keySizeInBytes)
        {
            Requires.NotNullOrEmpty(password, "password");
            Requires.NotNull(salt, "salt");
            Requires.Range(iterations > 0, "iterations");
            Requires.Range(keySizeInBytes > 0, "keySizeInBytes");

            IBuffer passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
            IBuffer saltBuffer     = salt.ToBuffer();

            KeyDerivationAlgorithmProvider keyDerivationProvider =
                KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha1);
            KeyDerivationParameters pbkdf2Parms =
                KeyDerivationParameters.BuildForPbkdf2(saltBuffer, (uint)iterations);

            // create a key based on original key and derivation parameters
            CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(passwordBuffer);
            IBuffer          keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, (uint)keySizeInBytes);

            return(keyMaterial.ToArray());
        }
コード例 #16
0
        public void DeriveEncryptionKey(byte[] passphrase, byte[] salt, ref byte[] encryptionKey)
        {
            var tokenData = SettingsHelper.LoadSetting <TFTokenData>(Consts.SETTINGS_TOKEN_SECRET_KEY);

            IBuffer passphraseBuffer = CryptographicBuffer.CreateFromByteArray(passphrase);
            IBuffer hmacKeyBuffer    = CryptographicBuffer.CreateFromByteArray(tokenData.SecretKey);

            MacAlgorithmProvider hmacProvider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha1);
            CryptographicHash    saltHMAC     = hmacProvider.CreateHash(hmacKeyBuffer);
            IBuffer saltBuffer = saltHMAC.GetValueAndReset();

            KeyDerivationAlgorithmProvider pbkdf2Provider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
            KeyDerivationParameters        pbkdf2Parms    = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, (uint)NumberOfOterations);
            CryptographicKey pbkdf2Key = pbkdf2Provider.CreateKey(passphraseBuffer);

            IBuffer derivedKeyBuffer = CryptographicEngine.DeriveKeyMaterial(pbkdf2Key, pbkdf2Parms, (uint)encryptionKey.Length);

            byte[] derivedKeyBytes = derivedKeyBuffer.ToArray();
            Array.Copy(derivedKeyBytes, encryptionKey, encryptionKey.Length);
            Array.Clear(derivedKeyBytes, 0, derivedKeyBytes.Length);
        }
コード例 #17
0
        public IBuffer SampleDeriveKeyMaterialPbkdf(
            String strAlgName,
            UInt32 targetKeySize,
            UInt32 iterationCount)
        {
            // Open the specified algorithm.
            KeyDerivationAlgorithmProvider objKdfProv = KeyDerivationAlgorithmProvider.OpenAlgorithm(strAlgName);

            // Demonstrate how to retrieve the algorithm name.
            String strAlgUsed = objKdfProv.AlgorithmName;

            // Create a buffer that contains the secret used during derivation.
            String  strSecret  = "MyPassword";
            IBuffer buffSecret = CryptographicBuffer.ConvertStringToBinary(strSecret, BinaryStringEncoding.Utf8);

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

            // 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 keyMaterial = CryptographicEngine.DeriveKeyMaterial(
                keyOriginal,
                pbkdf2Params,
                targetKeySize);

            // Demonstrate checking the iteration count.
            UInt32 iterationCountOut = pbkdf2Params.IterationCount;

            // Demonstrate returning the derivation parameters to a buffer.
            IBuffer buffParams = pbkdf2Params.KdfGenericBinary;

            // return the KDF key material.
            return(keyMaterial);
        }
コード例 #18
0
        public static bool GetPBKDFDerivedKey(string password,
                                              byte[] salt,                 // length = 32 bytes (256 bits)
                                              out byte[] encryptionKeyOut) // length = 32 bytes (256 bits)
        {
            IBuffer saltBuffer = CryptographicBuffer.CreateFromByteArray(salt);
            KeyDerivationParameters kdfParameters = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 10000);  // 10000 iterations

            // Get a KDF provider for PBKDF2 and hash the source password to a Cryptographic Key using the SHA256 algorithm.
            // The generated key for the SHA256 algorithm is 256 bits (32 bytes) in length.
            KeyDerivationAlgorithmProvider kdf = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha256);
            IBuffer          passwordBuffer    = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
            CryptographicKey passwordSourceKey = kdf.CreateKey(passwordBuffer);

            // Generate key material from the source password, salt, and iteration count
            const int keySize = 256 / 8;  // 256 bits = 32 bytes
            IBuffer   key     = CryptographicEngine.DeriveKeyMaterial(passwordSourceKey, kdfParameters, keySize);

            // send the generated key back to the caller
            CryptographicBuffer.CopyToByteArray(key, out encryptionKeyOut);

            return(true);  // success
        }
コード例 #19
0
        private static byte[] DeriveKeyMaterial(CryptoPassword cp)
        {
            // Open the specified algorithm.
            var provider = KeyDerivationAlgorithmProvider.OpenAlgorithm(_keyDerivationAlgorithmName);

            // Create a buffer that contains the keyPhrase for use during derivation.
            IBuffer bufferedSecret = CryptographicBuffer.ConvertStringToBinary(cp.KeyPhrase, _encoding);

            // Restore salt bytes as buffer.
            var bufferedSalt = CryptographicBuffer.CreateFromByteArray(cp.Salt);

            // Create the required derivation parameters.
            var pbkdf2Parameter = KeyDerivationParameters.BuildForPbkdf2(bufferedSalt, _iterationCount);

            // Create a key from the buffered secret.
            var keyOriginal = provider.CreateKey(bufferedSecret);

            // Derive a key from the original created key and the derivation parameters.
            var keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parameter, _targetKeySize);

            return(CopyBufferToByteArray(keyMaterial));
        }
コード例 #20
0
        public static string Decrypt(string encryptedData)
        {
            //Chuyen password sang IBuffer theo dinh dang Utf8
            IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8);
            //Chuyen salt theo dinh dang Utf8
            IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf8);
            //Chuyen du lieu chuoi sang IBuffer de giai ma
            IBuffer cipherBuffer = CryptographicBuffer.DecodeFromBase64String(encryptedData);
            KeyDerivationAlgorithmProvider keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
            KeyDerivationParameters        pbkdf2Parms           = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000);
            CryptographicKey keyOriginal              = keyDerivationProvider.CreateKey(pwBuffer);
            IBuffer          keyMaterial              = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32);
            IBuffer          saltMaterial             = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 16);
            SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
            CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial);
            //Giai ma
            IBuffer resultBuffer = CryptographicEngine.Decrypt(symmKey, cipherBuffer, saltMaterial);
            //Chuyen tu dinh dang IBuffer ve chuoi ban dau
            string result = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, resultBuffer);

            return(result);
        }
コード例 #21
0
    public async static Task <byte[]> Encrypt(string filePath)
    {
        byte[] fileBytes = await FileManager.ReadBytesFromFile(filePath);

        IBuffer pwBuffer    = CryptographicBuffer.ConvertStringToBinary(key1, BinaryStringEncoding.Utf8);
        IBuffer saltBuffer  = CryptographicBuffer.ConvertStringToBinary(key2, BinaryStringEncoding.Utf16LE);
        IBuffer plainBuffer = CryptographicBuffer.CreateFromByteArray(fileBytes);

        // Derive key material for password size 32 bytes for AES256 algorithm
        KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
        // using salt and 1000 iterations
        KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000);

        // create a key based on original key and derivation parmaters
        CryptographicKey keyOriginal  = keyDerivationProvider.CreateKey(pwBuffer);
        IBuffer          keyMaterial  = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32);
        CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer);

        // derive buffer to be used for encryption salt from derived password key
        IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16);

        // display the buffers – because KeyDerivationProvider always gets cleared after each use, they are very similar unforunately
        string keyMaterialString  = CryptographicBuffer.EncodeToBase64String(keyMaterial);
        string saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial);

        SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
        // create symmetric key from derived password key
        CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial);

        // encrypt data buffer using symmetric key and derived salt material
        IBuffer resultBuffer = CryptographicEngine.Encrypt(symmKey, plainBuffer, saltMaterial);

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

        return(result);
    }
コード例 #22
0
    /// <summary>
    /// Дешифрования текст
    /// </summary>
    /// <param name="SourceText">Исходный (шифрованный) текст</param>
    /// <param name="InputKey">Ключ шифрования</param>
    /// <param name="AlgorytmName">Имя алгоритма дешифрования</param>
    ///
    /// <returns>Расшифрованный (открытый) текст</returns>
    public string DecrypMode(string SourceText, string InputKey, string AlgorytmName, string IV, string KeySize)
    {
        SymmetricKeyAlgorithmProvider Algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(AlgorytmName);
        IBuffer KeyBuffer  = CryptographicBuffer.ConvertStringToBinary(InputKey, BinaryStringEncoding.Utf16LE);
        IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary("ll234hl@kljh5:Annc!6002mz", BinaryStringEncoding.Utf16LE);
        //CryptoKey = Algorithm.CreateSymmetricKey(keymaterial);



        KeyDerivationAlgorithmProvider keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha512);

        KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 10000);

        CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(KeyBuffer);

        IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, Convert.ToUInt32(KeySize) / 8);

        //  string test= CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, keyMaterial);

        CryptoKey = Algorithm.CreateSymmetricKey(keyMaterial);



        if (AlgorytmName.Contains("CBC"))
        {
            IVBuffer = CryptographicBuffer.ConvertStringToBinary(IV, BinaryStringEncoding.Utf16LE);
        }
        // Set the data to encrypt.
        SourceTextBuffer = CryptographicBuffer.DecodeFromBase64String(SourceText);

        // Decrypt
        DecryptBuffer     = Windows.Security.Cryptography.Core.CryptographicEngine.Decrypt(CryptoKey, SourceTextBuffer, IVBuffer);
        DecryptTextOutput = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, DecryptBuffer);//Надо думать над реализацией Base64

        return(DecryptTextOutput);
    }
コード例 #23
0
        public static string Decrypt(string encryptedData, string pw, string iv)
        {
            try
            {
                IBuffer pwBuffer     = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8);
                IBuffer ivBuffer     = CryptographicBuffer.ConvertStringToBinary(iv, BinaryStringEncoding.Utf16LE);
                IBuffer cipherBuffer = CryptographicBuffer.DecodeFromBase64String(encryptedData);

                // Derive key material for password size 32 bytes for AES256 algorithm
                KeyDerivationAlgorithmProvider keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
                // using IV and 1000 iterations
                KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(ivBuffer, 1000);

                // create a key based on original key and derivation parmaters
                CryptographicKey keyOriginal  = keyDerivationProvider.CreateKey(pwBuffer);
                IBuffer          keyMaterial  = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32);
                CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer);

                // derive buffer to be used for encryption iv from derived password key
                IBuffer ivMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16);

                SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
                // create symmetric key from derived password material
                CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial);

                // decrypt data buffer using symmetric key and derived IV material
                IBuffer resultBuffer = CryptographicEngine.Decrypt(symmKey, cipherBuffer, ivMaterial);
                string  result       = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, resultBuffer);
                return(result);
            }
            catch (System.Exception)
            {
                System.Diagnostics.Debug.WriteLine("Failed to decrypt file. Throwing exception up the chain.");
                throw;
            }
        }
コード例 #24
0
        private static CryptographicKey CreateDerivedKey(IBuffer bufferedKeyMaterial)
        {
            var provider = KeyDerivationAlgorithmProvider.OpenAlgorithm(_keyDerivationAlgorithmName);

            return(provider.CreateKey(bufferedKeyMaterial));
        }
コード例 #25
0
        } // VerifySignature()

        /// <summary>
        /// Generates the key exchange key and the public part of the ephemeral key
        /// using specified encoding parameters in the KDF (ECC only).
        /// </summary>
        /// <param name="encodingParms"></param>
        /// <param name="decryptKeyNameAlg"></param>
        /// <param name="ephemPub"></param>
        /// <returns>key exchange key blob</returns>
        public byte[] EcdhGetKeyExchangeKey(byte[] encodingParms, TpmAlgId decryptKeyNameAlg, out EccPoint ephemPub)
        {
            var eccParms = (EccParms)PublicParms.parameters;
            int keyBits  = RawEccKey.GetKeyLength(eccParms.curveID);

            byte[] keyExchangeKey = null;
            ephemPub = new EccPoint();

            // Make a new ephemeral key
            var     prov      = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(RawEccKey.GetEccAlg(PublicParms));
            var     ephKey    = prov.CreateKeyPair((uint)keyBits);
            IBuffer ephPubBuf = ephKey.ExportPublicKey(CryptographicPublicKeyBlobType.BCryptEccFullPublicKey);

            byte[] ephPub;
            CryptographicBuffer.CopyToByteArray(ephPubBuf, out ephPub);

            IBuffer otherPubBuf = Key.ExportPublicKey(CryptographicPublicKeyBlobType.BCryptEccFullPublicKey);

            byte[] otherPub;
            CryptographicBuffer.CopyToByteArray(otherPubBuf, out otherPub);

            byte[] herPubX, herPubY;
            RawEccKey.KeyInfoFromPublicBlob(otherPub, out herPubX, out herPubY);

            byte[] myPubX, myPubY;
            RawEccKey.KeyInfoFromPublicBlob(ephPub, out myPubX, out myPubY);

            byte[] otherInfo = Globs.Concatenate(new[] { encodingParms, myPubX, herPubX });

            // The TPM uses the following number of bytes from the KDF
            int bytesNeeded = CryptoLib.DigestSize(decryptKeyNameAlg);

            keyExchangeKey = new byte[bytesNeeded];

            for (int pos = 0, count = 1, bytesToCopy = 0;
                 pos < bytesNeeded;
                 ++count, pos += bytesToCopy)
            {
                byte[] secretPrepend = Marshaller.GetTpmRepresentation((UInt32)count);
                string algName;
                KeyDerivationParameters deriveParams;
                switch (decryptKeyNameAlg)
                {
                case TpmAlgId.Kdf1Sp800108:
                    algName      = KeyDerivationAlgorithmNames.Sp800108CtrHmacSha256;
                    deriveParams = KeyDerivationParameters.BuildForSP800108(CryptographicBuffer.CreateFromByteArray(secretPrepend), CryptographicBuffer.CreateFromByteArray(otherInfo));
                    break;

                case TpmAlgId.Kdf1Sp80056a:
                    algName      = KeyDerivationAlgorithmNames.Sp80056aConcatSha256;
                    deriveParams = KeyDerivationParameters.BuildForSP80056a(CryptographicBuffer.ConvertStringToBinary(algName, BinaryStringEncoding.Utf8),
                                                                            CryptographicBuffer.ConvertStringToBinary("TPM", BinaryStringEncoding.Utf8),
                                                                            CryptographicBuffer.CreateFromByteArray(secretPrepend),
                                                                            CryptographicBuffer.ConvertStringToBinary("", BinaryStringEncoding.Utf8),
                                                                            CryptographicBuffer.CreateFromByteArray(otherInfo));
                    break;

                case TpmAlgId.Kdf2:
                    algName      = KeyDerivationAlgorithmNames.Pbkdf2Sha256;
                    deriveParams = KeyDerivationParameters.BuildForPbkdf2(CryptographicBuffer.CreateFromByteArray(secretPrepend), 1000);
                    break;

                default:
                    Globs.Throw <ArgumentException>("wrong KDF name");
                    return(null);
                }
                KeyDerivationAlgorithmProvider deriveProv = KeyDerivationAlgorithmProvider.OpenAlgorithm(algName);
                IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(Key, deriveParams, (uint)keyBits);
                byte[]  fragment;
                CryptographicBuffer.CopyToByteArray(keyMaterial, out fragment);
                bytesToCopy = Math.Min(bytesNeeded - pos, fragment.Length);
                Array.Copy(fragment, 0, keyExchangeKey, pos, bytesToCopy);
            }
            ephemPub = new EccPoint(myPubX, myPubY);
            return(keyExchangeKey);
        }
コード例 #26
0
        public static byte[] CipherEncryption(
            string plainText,
            string password,
            bool lightFlag)
        {
            int hashIterCnt = HASH_ITER_COUNT;

            if (lightFlag)
            {
                hashIterCnt = HASH_ITER_COUNT_LIGHT;
            }

            uint pbkdf2IterCnt = PBKDF2_ITER_COUNT;

            if (lightFlag)
            {
                pbkdf2IterCnt = PBKDF2_ITER_COUNT_LIGHT;
            }

            // Convert to password string to UTF-8 encoded binary data.
            IBuffer utf8Password = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);

            // Generate hash value of password string.
            IBuffer           salt1   = CryptographicBuffer.GenerateRandom(32);
            CryptographicHash hashObj =
                HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha512).CreateHash();

            hashObj.Append(salt1);
            hashObj.Append(utf8Password);
            IBuffer buffHash1 = hashObj.GetValueAndReset();

            for (int i = 0; i < hashIterCnt; i++)
            {
                hashObj.Append(buffHash1);
                buffHash1 = hashObj.GetValueAndReset();
            }

            // Generate one-time password
            SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
            IBuffer oneTimePass = CryptographicBuffer.GenerateRandom(64);

            // encrypt one-time password by specified password string
            IBuffer          salt2      = CryptographicBuffer.GenerateRandom(32);
            CryptographicKey derviedKey =
                objAlg.CreateSymmetricKey(
                    CryptographicEngine.DeriveKeyMaterial(
                        KeyDerivationAlgorithmProvider.OpenAlgorithm(
                            KeyDerivationAlgorithmNames.Pbkdf2Sha256
                            ).CreateKey(utf8Password),
                        KeyDerivationParameters.BuildForPbkdf2(salt2, pbkdf2IterCnt),
                        32
                        )
                    );
            IBuffer iv2 = CryptographicBuffer.GenerateRandom(objAlg.BlockLength);
            IBuffer encryptOneTimePass = CryptographicEngine.Encrypt(derviedKey, oneTimePass, iv2);

            // Encrypt the data
            IBuffer iv3         = CryptographicBuffer.GenerateRandom(objAlg.BlockLength);
            IBuffer encryptData = null;
            uint    encDataLen  = 0;

            if (!String.IsNullOrEmpty(plainText))
            {
                IBuffer dataBuffer = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf8);
                encryptData = CryptographicEngine.Encrypt(objAlg.CreateSymmetricKey(oneTimePass), dataBuffer, iv3);
                encDataLen  = encryptData.Length;
            }

            // Append all of data
            byte[] retval =
                new byte[
                    146 +
                    (int)objAlg.BlockLength +
                    (int)objAlg.BlockLength +
                    encryptOneTimePass.Length +
                    encDataLen
                ];
            int pos = 0;

            if (lightFlag)
            {
                Random r = new Random();
                for (int i = pos; i < pos + 8; i++)
                {
                    retval[i] = (byte)r.Next(0, 255);
                }
            }
            else
            {
                Array.Copy(Encoding.GetEncoding("ASCII").GetBytes("GomaShio"), 0, retval, pos, 8);
            }
            pos += 8;
            Array.Copy(new byte[2] {
                0, 0
            }, 0, retval, pos, 2);
            pos += 2;
            Array.Copy(salt1.ToArray(), 0, retval, pos, 32);
            pos += 32;
            Array.Copy(buffHash1.ToArray(), 0, retval, pos, 64);
            pos += 64;
            Array.Copy(salt2.ToArray(), 0, retval, pos, 32);
            pos += 32;
            Array.Copy(iv2.ToArray(), 0, retval, pos, objAlg.BlockLength);
            pos += (int)objAlg.BlockLength;
            Array.Copy(BitConverter.GetBytes(encryptOneTimePass.Length), 0, retval, pos, 4);
            pos += 4;
            Array.Copy(encryptOneTimePass.ToArray(), 0, retval, pos, encryptOneTimePass.Length);
            pos += (int)encryptOneTimePass.Length;
            Array.Copy(iv3.ToArray(), 0, retval, pos, objAlg.BlockLength);
            pos += (int)objAlg.BlockLength;
            Array.Copy(BitConverter.GetBytes(encDataLen), 0, retval, pos, 4);
            pos += 4;
            if (null != encryptData)
            {
                Array.Copy(encryptData.ToArray(), 0, retval, pos, encryptData.Length);
            }

            return(retval);
        }
コード例 #27
0
        public static bool CipherDecryption(
            byte[] encData,
            string password,
            out string plainText,
            out bool passwordError,
            bool lightFlag)
        {
            int hashIterCnt = HASH_ITER_COUNT;

            if (lightFlag)
            {
                hashIterCnt = HASH_ITER_COUNT_LIGHT;
            }

            uint pbkdf2IterCnt = PBKDF2_ITER_COUNT;

            if (lightFlag)
            {
                pbkdf2IterCnt = PBKDF2_ITER_COUNT_LIGHT;
            }

            plainText     = "";
            passwordError = false;

            CryptographicHash hashObj =
                HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha512).CreateHash();
            SymmetricKeyAlgorithmProvider objAlg =
                SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);

            if (encData.Length < 146 + (objAlg.BlockLength * 2))
            {
                return(false);
            }

            byte[] MagicBytes = new byte[8];
            byte[] Version    = new byte[2];
            byte[] solt1      = new byte[32];
            byte[] hash       = new byte[64];
            byte[] solt2      = new byte[32];
            byte[] iv2        = new byte[objAlg.BlockLength];
            byte[] iv3        = new byte[objAlg.BlockLength];

            // Split encripted data
            int pos = 0;

            Array.Copy(encData, pos, MagicBytes, 0, 8);
            pos += 8;

            Array.Copy(encData, pos, Version, 0, 2);
            pos += 2;

            Array.Copy(encData, pos, solt1, 0, 32);
            pos += 32;

            Array.Copy(encData, pos, hash, 0, 64);
            pos += 64;

            Array.Copy(encData, pos, solt2, 0, 32);
            pos += 32;

            Array.Copy(encData, pos, iv2, 0, objAlg.BlockLength);
            pos += (int)objAlg.BlockLength;

            int oneTimePassLength = BitConverter.ToInt32(encData, pos);

            pos += 4;
            if (encData.Length < pos + oneTimePassLength)
            {
                return(false);
            }

            byte[] oneTimePass = new byte[oneTimePassLength];
            Array.Copy(encData, pos, oneTimePass, 0, oneTimePassLength);
            pos += oneTimePassLength;
            if (encData.Length < pos + objAlg.BlockLength)
            {
                return(false);
            }

            Array.Copy(encData, pos, iv3, 0, objAlg.BlockLength);
            pos += (int)objAlg.BlockLength;
            if (encData.Length < pos + 4)
            {
                return(false);
            }

            int encDataSubLength = BitConverter.ToInt32(encData, pos);

            pos += 4;
            if (encData.Length < pos + encDataSubLength)
            {
                return(false);
            }

            byte[] encDataSub = new byte[encDataSubLength];
            if (encDataSubLength > 0)
            {
                Array.Copy(encData, pos, encDataSub, 0, encDataSubLength);
            }

            // Check magic bytes and version.
            if (!lightFlag)
            {
                if (!Enumerable.SequenceEqual(MagicBytes, Encoding.GetEncoding("ASCII").GetBytes("GomaShio")))
                {
                    return(false);
                }
            }
            if (!Enumerable.SequenceEqual(Version, new byte[2] {
                0, 0
            }))
            {
                return(false);
            }

            // Check password
            IBuffer utf8Password = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
            IBuffer salt1        = solt1.AsBuffer();

            hashObj.Append(salt1);
            hashObj.Append(utf8Password);
            IBuffer buffHash1 = hashObj.GetValueAndReset();

            for (int i = 0; i < hashIterCnt; i++)
            {
                hashObj.Append(buffHash1);
                buffHash1 = hashObj.GetValueAndReset();
            }
            if (!Enumerable.SequenceEqual(hash, buffHash1.ToArray()))
            {
                passwordError = true;
                return(false);
            }

            // Decrypt one-time password by specified password string
            CryptographicKey derviedKey =
                objAlg.CreateSymmetricKey(
                    CryptographicEngine.DeriveKeyMaterial(
                        KeyDerivationAlgorithmProvider.OpenAlgorithm(
                            KeyDerivationAlgorithmNames.Pbkdf2Sha256
                            ).CreateKey(utf8Password),
                        KeyDerivationParameters.BuildForPbkdf2(solt2.AsBuffer(), pbkdf2IterCnt),
                        32
                        )
                    );
            IBuffer plainOneTimePass = CryptographicEngine.Decrypt(derviedKey, oneTimePass.AsBuffer(), iv2.AsBuffer());

            // Decrypt the data
            if (encDataSubLength > 0)
            {
                IBuffer decriptIBuffer =
                    CryptographicEngine.Decrypt(
                        objAlg.CreateSymmetricKey(plainOneTimePass),
                        encDataSub.AsBuffer(),
                        iv3.AsBuffer()
                        );
                plainText = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decriptIBuffer);
            }
            else
            {
                plainText = "";
            }

            return(true);
        }
コード例 #28
0
        /// <inheritdoc />
        public override void ForwardProcessDataStream(System.IO.Stream inStream, System.IO.Stream outStream, Dictionary <string, string> options, out long writtenBytes)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            else if (!options.ContainsKey(PasswordOption))
            {
                throw new ArgumentException("Options must contain encryption key", "options");
            }

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

#if NETFX_CORE
            inStream.Seek(0, 0);
            outStream.Seek(0, 0);

            IBuffer pwBuffer   = CryptographicBuffer.ConvertStringToBinary(options[PasswordOption], BinaryStringEncoding.Utf8);
            IBuffer saltBuffer = CryptographicBuffer.CreateFromByteArray(SALT);

            // Derive key material for password size 32 bytes for AES256 algorithm
            KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
            // using salt and 1000 iterations
            KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000);

            // create a key based on original key and derivation parmaters
            CryptographicKey keyOriginal  = keyDerivationProvider.CreateKey(pwBuffer);
            IBuffer          keyMaterial  = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32);
            CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer);

            // derive buffer to be used for encryption salt from derived password key
            IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16);

            // display the buffers - because KeyDerivationProvider always gets cleared after each use, they are very similar unforunately
            string keyMaterialString  = CryptographicBuffer.EncodeToBase64String(keyMaterial);
            string saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial);

            SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
            // create symmetric key from derived password key
            CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial);

            using (MemoryStream ms = new MemoryStream())
            {
                inStream.CopyTo(ms);
                // encrypt data buffer using symmetric key and derived salt material
                IBuffer resultBuffer = CryptographicEngine.Encrypt(symmKey, WindowsRuntimeBufferExtensions.GetWindowsRuntimeBuffer(ms), saltMaterial);
                resultBuffer.AsStream().CopyTo(outStream);
                writtenBytes = outStream.Position;
            }
#else
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(options[PasswordOption], SALT);
            var key = pdb.GetBytes(32);
            pdb.Reset();
            var iv = pdb.GetBytes(16);

            using (var transform = encrypter.CreateEncryptor(key, iv))
            {
                using (MemoryStream internalStream = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(internalStream, transform, CryptoStreamMode.Write))
                    {
                        StreamTools.Write(inStream, csEncrypt);
                        inStream.Flush();
                        csEncrypt.FlushFinalBlock();

                        internalStream.Seek(0, 0);
                        StreamTools.Write(internalStream, outStream);
                        writtenBytes = outStream.Position;
                    }
                }
            }
#endif
        }