Пример #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CryptographicKey" /> class.
        /// </summary>
        /// <param name="key">The WinRT cryptographic key.</param>
        /// <param name="symmetricAlgorithmProvider">The symmetric algorithm of the provider creating this key.</param>
        internal CryptographicKey(Platform.CryptographicKey key, SymmetricKeyAlgorithmProvider symmetricAlgorithmProvider)
        {
            Requires.NotNull(key, "key");

            this.key = key;
            this.symmetricAlgorithmProvider = symmetricAlgorithmProvider;
        }
Пример #2
0
        private byte[] DecryptDataV2(byte[] encryptedData, string pw, string salt)
        {
            try
            {
                var pwBuffer     = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8);
                var saltBuffer   = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf16LE);
                var cipherBuffer = CryptographicBuffer.CreateFromByteArray(encryptedData);

                // 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 keys – 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);

                var symmKey = symProvider.CreateSymmetricKey(keyMaterial);


                var resultBuffer = CryptographicEngine.Decrypt(symmKey, cipherBuffer, saltMaterial);

                var result = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, resultBuffer);

                var byteArray2 = Convert.FromBase64String(result);


                return(byteArray2);
            }
            catch (Exception ex)
            {
                _loggingService.WriteLine <App>(ex.Message, LogLevel.Error, ex);
                return(new byte[0]);
            }
        }
Пример #3
0
        private static String CipherDecryption(IBuffer buffEncrypt)
        {
            var strAlgName = SymmetricAlgorithmNames.AesCbcPkcs7;
            //UInt32 keyLength = 32;

            // Initialize the binary encoding value.
            var encoding = BinaryStringEncoding.Utf8;

            // Initialize the initialization vector.
            IBuffer iv = CryptographicBuffer.ConvertStringToBinary("1234567890123456", encoding);

            // Open a symmetric algorithm provider for the specified algorithm.
            SymmetricKeyAlgorithmProvider 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 ((buffEncrypt.Length % objAlg.BlockLength) != 0)
                {
                    throw new Exception("Message buffer length must be multiple of block length.");
                }
            }

            // Create a symmetric key.
            IBuffer keyMaterial = CryptographicBuffer.ConvertStringToBinary("12345678901234567890123456789012", encoding);
            var     key         = objAlg.CreateSymmetricKey(keyMaterial);

            // Declare a buffer to contain the decrypted data.
            IBuffer buffDecrypted;

            // The input key must be securely shared between the sender of the encrypted message
            // and the recipient. The initialization vector must also be shared but does not
            // need to be shared in a secure manner. If the sender encodes a message string
            // to a buffer, the binary encoding method must also be shared with the recipient.
            buffDecrypted = CryptographicEngine.Decrypt(key, buffEncrypt, iv);

            // Convert the decrypted buffer to a string (for display). If the sender created the
            // original message buffer from a string, the sender must tell the recipient what
            // BinaryStringEncoding value was used. Here, BinaryStringEncoding.Utf8 is used to
            // convert the message to a buffer before encryption and to convert the decrypted
            // buffer back to the original plaintext.
            String strDecrypted = CryptographicBuffer.ConvertBinaryToString(encoding, buffDecrypted);

            return(strDecrypted);
        }
Пример #4
0
 private async Task <string> EncryptStringHelper(string plainString, string key)
 {
     try
     {
         var hashKey         = GetMD5Hash(key);
         var decryptBuffer   = CryptographicBuffer.ConvertStringToBinary(plainString, BinaryStringEncoding.Utf16BE);
         var AES             = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
         var symmetricKey    = AES.CreateSymmetricKey(hashKey);
         var encryptedBuffer = CryptographicEngine.Encrypt(symmetricKey, decryptBuffer, null);
         var encryptedString = CryptographicBuffer.EncodeToBase64String(encryptedBuffer);
         return(encryptedString);
     }
     catch (Exception ex)
     {
         return("");
     }
 }
Пример #5
0
        /// <summary>
        /// Decrypts the specified input stream.
        /// </summary>
        /// <param name="input">The input stream.</param>
        /// <param name="masterKey">The master key.</param>
        /// <param name="masterSeed">The master seed.</param>
        /// <param name="encryptionIV">The encryption initialization vector.</param>
        /// <returns>The decrypted buffer.</returns>
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="input"/>, <paramref name="masterSeed"/>, <paramref name="masterKey"/>
        /// and <paramref name="encryptionIV"/> cannot be <c>null</c>.
        /// </exception>
        public static async Task <IInputStream> Decrypt(IRandomAccessStream input,
                                                        IBuffer masterKey, IBuffer masterSeed, IBuffer encryptionIV)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }
            if (masterSeed == null)
            {
                throw new ArgumentNullException("masterSeed");
            }
            if (masterKey == null)
            {
                throw new ArgumentNullException("masterKey");
            }
            if (encryptionIV == null)
            {
                throw new ArgumentNullException("encryptionIV");
            }

            var sha = HashAlgorithmProvider
                      .OpenAlgorithm(HashAlgorithmNames.Sha256)
                      .CreateHash();

            sha.Append(masterSeed);
            sha.Append(masterKey);

            var seed = sha.GetValueAndReset();
            var aes  = SymmetricKeyAlgorithmProvider
                       .OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7)
                       .CreateSymmetricKey(seed);

            var buffer = WindowsRuntimeBuffer.Create(
                (int)(input.Size - input.Position));

            buffer = await input.ReadAsync(buffer, buffer.Capacity);

            buffer = CryptographicEngine.Decrypt(aes, buffer, encryptionIV);

            var stream = new InMemoryRandomAccessStream();
            await stream.WriteAsync(buffer);

            stream.Seek(0);

            return(stream);
        }
Пример #6
0
        private static CryptographicKey getKey(SymmetricKeyAlgorithmProvider Algorithm)
        {
            IBuffer keymaterial = CryptographicBuffer.CreateFromByteArray(ByteUtils.getBytes(KEY.Substring(0, SIZE_IV)));

            CryptographicKey _key = null;

            try
            {
                _key = Algorithm.CreateSymmetricKey(keymaterial);
            }
            catch (ArgumentException ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }

            return(_key);
        }
Пример #7
0
        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;
        }
Пример #8
0
        /// <summary>
        /// déchiffré une chaine de caractère et en ressort une chaine de caractèr
        /// </summary>
        /// <param name="dataToDecrypt">la chaine à déchiffrer</param>
        /// <param name="password">le mot de passe</param>
        /// <param name="salt">la complexification du mot de passe</param>
        /// <returns>la chaine de caractère déchiffré</returns>
        public static string AesDecryptStringToString(string dataToDecrypt, string password, string salt)
        {
            IBuffer    aesKeyMaterial;
            IBuffer    iv;
            const uint iterationCount = 10000;

            GenerateKeyMaterial(password, salt, iterationCount, out aesKeyMaterial, out iv);
            var ciphertext = CryptographicBuffer.DecodeFromBase64String(dataToDecrypt);

            var symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
            var symmKey     = symProvider.CreateSymmetricKey(aesKeyMaterial);

            var resultBuffer   = CryptographicEngine.Decrypt(symmKey, ciphertext, iv);
            var decryptedArray = resultBuffer.ToArray();

            return(Encoding.UTF8.GetString(decryptedArray, 0, decryptedArray.Length));
        }
Пример #9
0
 public static string Decrypt(string cipherString, string key)
 {
     try
     {
         var     keyHash                   = GetMD5Hash(key);
         IBuffer toDecryptBuffer           = CryptographicBuffer.DecodeFromBase64String(cipherString);
         SymmetricKeyAlgorithmProvider aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
         var    symetricKey                = aes.CreateSymmetricKey(keyHash);
         var    buffDecrypted              = CryptographicEngine.Decrypt(symetricKey, toDecryptBuffer, null);
         string strDecrypted               = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffDecrypted);
         return(strDecrypted);
     }
     catch (Exception ex)
     {
         return(null);
     }
 }
Пример #10
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);
 }
Пример #11
0
 private async Task <string> DecryptStringHelper(string encryptedString, string key)
 {
     try
     {
         var     hashKey         = GetMD5Hash(key);
         IBuffer decryptBuffer   = CryptographicBuffer.DecodeFromBase64String(encryptedString);
         var     AES             = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
         var     symmetricKey    = AES.CreateSymmetricKey(hashKey);
         var     decryptedBuffer = CryptographicEngine.Decrypt(symmetricKey, decryptBuffer, null);
         string  decryptedString = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decryptedBuffer);
         return(decryptedString);
     }
     catch (Exception ex)
     {
         return("");
     }
 }
Пример #12
0
        private static IBuffer CipherEncryption(String strMsg)
        {
            /////////////////////////////////////////////////////////////////////////////
            // Perform symmetric encryption and decryption.
            var strAlgName = SymmetricAlgorithmNames.AesCbcPkcs7;
            //UInt32 keyLength = 32;

            // Initialize the initialization vector.
            IBuffer iv = null;

            // Initialize the binary encoding value.
            var encoding = BinaryStringEncoding.Utf8;

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

            // Open a symmetric algorithm provider for the specified algorithm.
            SymmetricKeyAlgorithmProvider 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 ((buffMsg.Length % objAlg.BlockLength) != 0)
                {
                    throw new Exception("Message buffer length must be multiple of block length.");
                }
            }

            // Create a symmetric key.
            IBuffer keyMaterial = CryptographicBuffer.ConvertStringToBinary("12345678901234567890123456789012", encoding);
            var     key         = objAlg.CreateSymmetricKey(keyMaterial);

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

            // Encrypt the data and return.
            IBuffer buffEncrypt = CryptographicEngine.Encrypt(key, buffMsg, iv);

            return(buffEncrypt);
        }
Пример #13
0
        public async Task <bool> EncryptAsync(string publicKey, IList <byte> dataArray, IList <byte> localPassword)
        {
            IBuffer keyMaterial;

            //if (await KeyCredentialManager.IsSupportedAsync())
            //{
            //    var boh = await KeyCredentialManager.RequestCreateAsync(publicKey, KeyCredentialCreationOption.ReplaceExisting);
            //    if (boh.Status == KeyCredentialStatus.Success)
            //    {
            //        var boh2 = await boh.Credential.RequestSignAsync()
            //    }
            //}
            //else
            {
                var dialog = new SettingsPasscodeInputView();

                var confirm = await dialog.ShowQueuedAsync();

                if (confirm != ContentDialogResult.Primary)
                {
                    return(false);
                }

                var secret   = CryptographicBuffer.ConvertStringToBinary(dialog.Passcode, BinaryStringEncoding.Utf8);
                var salt     = CryptographicBuffer.GenerateRandom(32);
                var material = PBKDF2(secret, salt);

                var data = CryptographicBuffer.CreateFromByteArray(dataArray.ToArray());

                var objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
                var key    = objAlg.CreateSymmetricKey(material);

                var encrypt    = CryptographicEngine.Encrypt(key, data, null);
                var saltString = CryptographicBuffer.EncodeToHexString(salt);
                var dataString = CryptographicBuffer.EncodeToHexString(encrypt);

                var localPasswordBuffer = CryptographicBuffer.CreateFromByteArray(localPassword.ToArray());
                var localPasswordString = CryptographicBuffer.EncodeToHexString(localPasswordBuffer);

                var vault    = new PasswordVault();
                var password = $"{saltString};{dataString};{localPasswordString};{(dialog.IsSimple ? 1 : 2)}";
                vault.Add(new PasswordCredential($"{_session}", publicKey, password));
            }

            return(true);
        }
Пример #14
0
        /// <summary>
        /// Calculates the response by encrypting the challenge by using Triple DES (3DES).
        /// If the resulting values are the same, the authentication is successful.
        /// </summary>
        /// <param name="challenge">a block of challenge data generated by smart card using its admin key</param>
        /// <param name="adminkey">the admin key of the smart card, which is normally saved on the server side or management tool.</param>
        /// <returns>the response</returns>
        public static IBuffer CalculateResponse(IBuffer challenge, IBuffer adminkey)
        {
            if (challenge == null)
            {
                throw new ArgumentNullException("challenge");
            }
            if (adminkey == null)
            {
                throw new ArgumentNullException("adminkey");
            }

            SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.TripleDesCbc);
            var symmetricKey  = objAlg.CreateSymmetricKey(adminkey);
            var buffEncrypted = CryptographicEngine.Encrypt(symmetricKey, challenge, null);

            return(buffEncrypted);
        }
        /// <summary>
        /// Encrypt a string using dual encryption method. Returns an encrypted text.
        /// </summary>
        /// <param name="toEncrypt">String to be encrypted</param>
        /// <param name="key">Unique key for encryption/decryption</param>m>
        /// <param name="type"> Type of Hash function to be used. </param>
        /// <param name="hashKey"> optional key to be used with HMACSHA256 algorithm </param>
        /// <returns>Returns encrypted string.</returns>
        public static string Encrypt(string toEncrypt, string key, HashFunctionType type = HashFunctionType.MD5, byte[] hashKey = null)
        {
#if NETFX_CORE
            try
            {
                byte[] keyHash = Hash(key, type, hashKey);


                // Create a buffer that contains the encoded message to be encrypted.
                var toDecryptBuffer = CryptographicBuffer.ConvertStringToBinary(toEncrypt, BinaryStringEncoding.Utf8);

                // Open a symmetric algorithm provider for the specified algorithm.
                var aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);

                //Since all hashing functions have fixed length some algorithms do not suit to be used as key hashers
                //ie SHA1 will throw an error since its size is 160 bit while Aes requires 16 byte block size (or multiples of 16)
                if (keyHash.Length % aes.BlockLength != 0)
                {
                    //if SHA1 used for encryption please not its block size is 160 bit
                    throw new ArgumentException("Hash function hashed with invalid key block size: " + keyHash.Length);
                }
                // Create a symmetric key.
                var symetricKey = aes.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(keyHash));

                // The input key must be securely shared between the sender of the cryptic message
                // and the recipient. The initialization vector must also be shared but does not
                // need to be shared in a secure manner. If the sender encodes a message string
                // to a buffer, the binary encoding method must also be shared with the recipient.
                var buffEncrypted = CryptographicEngine.Encrypt(symetricKey, toDecryptBuffer, null);

                // Convert the encrypted buffer to a string (for display).
                // We are using Base64 to convert bytes to string since you might get unmatched characters
                // in the encrypted buffer that we cannot convert to string with UTF8.
                var strEncrypted = CryptographicBuffer.EncodeToBase64String(buffEncrypted);

                return(strEncrypted);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                throw new Exception("[EncryptionProvider] Error Encrypting a string");
            }
#else
            throw new System.PlatformNotSupportedException();
#endif
        }
Пример #16
0
        public static byte[] aesCtr(byte[] message, byte[] key, uint counter)
        {
            SymmetricKeyAlgorithmProvider objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
            IBuffer          buffKey             = CryptographicBuffer.CreateFromByteArray(key);
            CryptographicKey ckey = objAlg.CreateSymmetricKey(buffKey);

            byte[] ivBytes = new byte[16];
            ByteUtil.intToByteArray(ivBytes, 0, (int)counter);

            IBuffer buffPlaintext = CryptographicBuffer.CreateFromByteArray(message);
            IBuffer buffIV        = CryptographicBuffer.CreateFromByteArray(ivBytes);
            IBuffer buffEncrypt   = CryptographicEngine.Decrypt(ckey, buffPlaintext, buffIV);

            byte[] ret;
            CryptographicBuffer.CopyToByteArray(buffEncrypt, out ret);
            return(ret);
        }
Пример #17
0
 public static string Encrypt(string toEncrypt, string key)
 {
     try
     {
         var keyHash         = GetMD5Hash(key);
         var toDecryptBuffer = CryptographicBuffer.ConvertStringToBinary(toEncrypt, BinaryStringEncoding.Utf8);
         var aes             = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
         var symetricKey     = aes.CreateSymmetricKey(keyHash);
         var buffEncrypted   = CryptographicEngine.Encrypt(symetricKey, toDecryptBuffer, null);
         var strEncrypted    = CryptographicBuffer.EncodeToBase64String(buffEncrypted);
         return(strEncrypted);
     }
     catch (Exception ex)
     {
         return(null);
     }
 }
        public static IBuffer CipherEncryption(
            string strMsg,
            string strAlgName,
            out BinaryStringEncoding encoding,
            out IBuffer iv,
            out CryptographicKey key,
            uint keyLength = 128)
        {
            iv       = null; // Initialize the initialization vector because some type encryptions do not need it.
            encoding = BinaryStringEncoding.Utf8;

            IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding);

            // 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 ((buffMsg.Length % objAlg.BlockLength) != 0)
                {
                    throw new Exception("Message buffer length must be multiple of block length.");
                }
            }

            // Create a symmetric key.
            // IBuffer keyMaterial = CryptographicBuffer.GenerateRandom(keyLength);     // drop it.
            IBuffer keyMaterial = CryptographicBuffer.CreateFromByteArray(CollForKeyAndIv);

            key = objAlg.CreateSymmetricKey(keyMaterial);

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

            // Encrypt the data and return.
            IBuffer buffEncrypt = CryptographicEngine.Encrypt(key, buffMsg, iv);

            return(buffEncrypt);
        }
Пример #19
0
        public static string encryptAES(string plainText, string key, ref string iv)
        {
            byte[] aesKeyBytes    = Encoding.UTF8.GetBytes(key);
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            if (iv == "")
            {
                iv = generateIV();
            }
            byte[] ivBytes = Convert.FromBase64String(iv);

            SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
            CryptographicKey AES             = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(aesKeyBytes));
            IBuffer          plainTextBuffer = CryptographicBuffer.CreateFromByteArray(plainTextBytes);
            IBuffer          ivBuffer        = CryptographicBuffer.CreateFromByteArray(ivBytes);

            return(CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(AES, plainTextBuffer, ivBuffer)));
        }
        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);
        }
Пример #21
0
        /// <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;
        }
Пример #22
0
        /// <summary>
        /// chiffre un tableau de byte et en ressort un tableau de byte
        /// </summary>
        /// <param name="dataToEncrypt">la donnée à chiffrer</param>
        /// <param name="password">le mot de passe</param>
        /// <param name="salt">la complexification du mot de passe</param>
        /// <returns>le résultat chiffré</returns>
        public static byte[] AesEncryptByteArrayToByteArray(byte[] dataToEncrypt, string password, string salt)
        {
            IBuffer    aesKeyMaterial;
            IBuffer    iv;
            const uint iterationCount = 10000;

            GenerateKeyMaterial(password, salt, iterationCount, out aesKeyMaterial, out iv);
            var plainText = CryptographicBuffer.CreateFromByteArray(dataToEncrypt);

            var symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
            var symmKey     = symProvider.CreateSymmetricKey(aesKeyMaterial);

            var encrypted = CryptographicEngine.Encrypt(symmKey, plainText, iv);

            byte[] retour;
            CryptographicBuffer.CopyToByteArray(encrypted, out retour);
            return(retour);
        }
Пример #23
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);
        }
Пример #24
0
        public static IBuffer Decrypt(byte[] data, string keyString)
        {
            SymmetricKeyAlgorithmProvider symmetricProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.Rc4);
            IBuffer          key    = CryptographicBuffer.DecodeFromBase64String(keyString);
            CryptographicKey cryKey = symmetricProvider.CreateSymmetricKey(key);
            IBuffer          buffer = CryptographicBuffer.CreateFromByteArray(data);

            try
            {
                var decrypted = CryptographicEngine.Decrypt(cryKey, buffer, null);
                buffer.AsStream().Dispose();
                return(decrypted);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
 public static string AESDecrypt(string key, string value)
 {
     try
     {
         IBuffer bufMsg     = CryptographicBuffer.DecodeFromBase64String(value);
         IBuffer bufKey     = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8);
         string  strAlgName = Windows.Security.Cryptography.Core.SymmetricAlgorithmNames.AesCbcPkcs7;
         SymmetricKeyAlgorithmProvider alg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName);
         CryptographicKey encryptKey       = alg.CreateSymmetricKey(bufKey);
         IBuffer          bufOutput        = CryptographicEngine.Decrypt(encryptKey, bufMsg, bufKey);
         string           output           = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, bufOutput);
         return(output);
     }
     catch
     {
         return(string.Empty);
     }
 }
Пример #26
0
        public static string Decrypt(IBuffer data, string passPhrase)
        {
            IBuffer iv = null;

            //Create SymmetricKeyAlgorithmProvider
            var symetric = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);

            //Create hash for passPhrase to create symmetric Key
            IBuffer keyBuffer = Hash(passPhrase);
            //Create symmetric key
            CryptographicKey key = symetric.CreateSymmetricKey(keyBuffer);

            //Decrypt data
            IBuffer bufferDecrypted = CryptographicEngine.Decrypt(key, data, iv);

            //Convert binary to string
            return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, bufferDecrypted));
        }
Пример #27
0
        public static string Encrypt(string dataToEncrypt, string password, string salt)
        {
            // Generate a key and IV from the password and salt
            IBuffer aesKeyMaterial;
            IBuffer iv;
            uint iterationCount = 10000;
            GenerateKeyMaterial(password, salt, iterationCount, out aesKeyMaterial, out iv);

            IBuffer plainText = CryptographicBuffer.ConvertStringToBinary(dataToEncrypt, BinaryStringEncoding.Utf8);

            // Setup an AES key, using AES in CBC mode and applying PKCS#7 padding on the input
            SymmetricKeyAlgorithmProvider aesProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
            CryptographicKey aesKey = aesProvider.CreateSymmetricKey(aesKeyMaterial);

            // Encrypt the data and convert it to a Base64 string
            IBuffer encrypted = CryptographicEngine.Encrypt(aesKey, plainText, iv);
            return CryptographicBuffer.EncodeToBase64String(encrypted);
        }
Пример #28
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);
    }
Пример #29
0
        GetMasterKey(IBuffer seed, ulong rounds)
        {
            return(AsyncInfo.Run <IBuffer, uint>(
                       (token, progress) => Task.Run(() =>
            {
                var transforms = 0UL;
                var master = GetMasterKey();

                // AES - ECB
                var aes = SymmetricKeyAlgorithmProvider
                          .OpenAlgorithm(SymmetricAlgorithmNames.AesEcb);
                var key = aes.CreateSymmetricKey(seed);


                while (true)
                {
                    // Report progress
                    token.ThrowIfCancellationRequested();
                    progress.Report((uint)Math.Round(
                                        transforms * 100F / rounds));

                    for (var i = 0; i < 1000; i++)
                    {
                        // Transform master key
                        master = CryptographicEngine
                                 .Encrypt(key, master, null);

                        transforms++;
                        if (transforms < rounds)
                        {
                            continue;
                        }

                        // Completed
                        progress.Report(100);
                        master = HashAlgorithmProvider
                                 .OpenAlgorithm(HashAlgorithmNames.Sha256)
                                 .HashData(master);

                        return master;
                    }
                }
            }, token)));
        }
Пример #30
0
        public static byte[] Encrypt(string text, string passPhrase)
        {
            IBuffer iv = null;

            //Create SymmetricKeyAlgorithmProvider
            var symetric = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);

            //Create hash for passPhrase to create symmetric Key
            IBuffer keyBuffer = Hash(passPhrase);
            //Create symmetric key
            CryptographicKey key = symetric.CreateSymmetricKey(keyBuffer);

            //Convert texto to binary, for encrypt
            IBuffer data = CryptographicBuffer.ConvertStringToBinary(text, BinaryStringEncoding.Utf8);

            //Encrypt data
            //Encrypt method return IBuffer
            return(CryptographicEngine.Encrypt(key, data, iv).ToArray());
        }
        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);
        }
Пример #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CryptographicKey" /> class.
 /// </summary>
 /// <param name="key">The WinRT cryptographic key.</param>
 /// <param name="symmetricAlgorithmProvider">The symmetric algorithm of the provider creating this key.</param>
 /// <param name="canExportPrivateKey">
 /// A value indicating whether <see cref="Export(CryptographicPrivateKeyBlobType)"/>
 /// can be expected to work.
 /// </param>
 internal CryptographicKey(Platform.CryptographicKey key, SymmetricKeyAlgorithmProvider symmetricAlgorithmProvider, bool canExportPrivateKey)
     : this(key, canExportPrivateKey)
 {
     this.symmetricAlgorithmProvider = symmetricAlgorithmProvider;
 }