コード例 #1
0
        public IBuffer Decrypt(IBuffer toDecryptBuffer, string key)
        {
            try
            {
                // Get the MD5 key hash (you can as well use the binary of the key string)
                var keyHash = GetMD5Hash(key);

                // Create a buffer that contains the encoded message to be decrypted.


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

                // Create a symmetric key.
                var symetricKey = aes.CreateSymmetricKey(keyHash);

                IBuffer buffDecrypted = CryptographicEngine.Decrypt(symetricKey, toDecryptBuffer, null);

                return(buffDecrypted);
            }
            catch (Exception)
            {
                throw;
            }
        }
コード例 #2
0
        public Task <byte[]> AesDecryptAsync(byte[] data, byte[] iv, byte[] key)
        {
            var provider  = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
            var cryptoKey = provider.CreateSymmetricKey(key);

            return(Task.FromResult(CryptographicEngine.Decrypt(cryptoKey, data, iv)));
        }
コード例 #3
0
        internal static string DecryptThisCipher(string input, string pass)
        {
            SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
            CryptographicKey      AES;
            HashAlgorithmProvider HAP      = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            CryptographicHash     Hash_AES = HAP.CreateHash();

            string decrypted = "";

            try
            {
                byte[] hash = new byte[32];
                Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(pass)));
                byte[] temp;
                CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);

                Array.Copy(temp, 0, hash, 0, 16);
                Array.Copy(temp, 0, hash, 15, 16);

                AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));

                IBuffer Buffer = CryptographicBuffer.DecodeFromBase64String(input);
                byte[]  Decrypted;
                CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(AES, Buffer, null), out Decrypted);
                decrypted = Encoding.UTF8.GetString(Decrypted, 0, Decrypted.Length);

                return(decrypted);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return(null);
            }
        }
コード例 #4
0
        private string AesDecrypt(string encryptionKey, string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return(value);
            }

            IBuffer passwordBuffer = CryptographicBuffer.ConvertStringToBinary(encryptionKey, BinaryStringEncoding.Utf8);
            IBuffer saltBuffer     = CryptographicBuffer.CreateFromByteArray(new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });

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

            CryptographicKey keyOriginal  = keyDerivationProvider.CreateKey(passwordBuffer);
            IBuffer          keyMaterial  = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32);
            CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(passwordBuffer);

            IBuffer ivBuffer = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16);

            SymmetricKeyAlgorithmProvider aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);

            CryptographicKey aesKey = aes.CreateSymmetricKey(keyMaterial);

            IBuffer decryptedContentBuffer = CryptographicEngine.Decrypt(aesKey, CryptographicBuffer.DecodeFromBase64String(value), ivBuffer);

            return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decryptedContentBuffer));
        }
コード例 #5
0
        public static string AesDecrypt(this byte[] encrypted, string password, string salt)
        {
            IBuffer pwBuffer     = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
            IBuffer saltBuffer   = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf16LE);
            IBuffer cipherBuffer = CryptographicBuffer.CreateFromByteArray(encrypted);

            // 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 keys – 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 material
            CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial);

            // encrypt data buffer using symmetric key and derived salt material
            IBuffer resultBuffer = CryptographicEngine.Decrypt(symmKey, cipherBuffer, saltMaterial);
            string  result       = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, resultBuffer);

            return(result);
        }
コード例 #6
0
        public static byte[] AES_Decrypt(byte[] input, byte[] pass)
        {
            SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
            CryptographicKey      AES;
            HashAlgorithmProvider HAP      = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            CryptographicHash     Hash_AES = HAP.CreateHash();

            //string decrypted = "";
            //try
            //{
            byte[] hash = new byte[32];
            Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(pass));
            byte[] temp;
            CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);

            Array.Copy(temp, 0, hash, 0, 16);    //key1
            Array.Copy(temp, 0, hash, 15, 16);   //key2

            AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));
            //IBuffer Buffer = CryptographicBuffer.DecodeFromBase64String(input);
            IBuffer Buffer = CryptographicBuffer.CreateFromByteArray(input);

            byte[] Decrypted;
            CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(AES, Buffer, null), out Decrypted);
            //decrypted = System.Text.Encoding.UTF8.GetString(Decrypted, 0, Decrypted.Length);

            return(Decrypted);
            //}
            //catch (Exception ex)
            //{
            //    return null;
            //}
        }
コード例 #7
0
ファイル: Messages.xaml.cs プロジェクト: nevver/ChronosClient
        // method to decrypt ciphertext of AES key
        public async void asymmetricDecryptAESKeySender(
            String strAsymmetricAlgName,
            IBuffer buffEncryptedAESKey)
        {
            // Open the algorithm provider for the specified asymmetric algorithm.
            AsymmetricKeyAlgorithmProvider objAsymmAlgProv = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(strAsymmetricAlgName);

            CryptographicKey pair = objAsymmAlgProv.ImportKeyPair(DataContainer.senderKeyPair);

            try
            {
                // Use the private key embedded in the key pair to decrypt the session key.
                keyMaterialSender = CryptographicEngine.Decrypt(pair, buffEncryptedAESKey, null);
            }
            catch (System.ArgumentException ar)
            {
                Debug.WriteLine(ar.ToString());
                var dialog = new MessageDialog("Error: Key Mismatch. Unable to display new messages.");
                await dialog.ShowAsync();

                // CoreApplication.Exit();
            }


            //convert to string
            keyMaterialStringSender = CryptographicBuffer.EncodeToBase64String(keyMaterialSender);
        }
コード例 #8
0
        /***
         * This function decrypts the encrypted text to plain text using the key
         * provided. You'll have to use the same key which you used during
         * encryption
         *
         * @param _encryptedText
         *            Encrypted/Cipher text to be decrypted
         * @param _key
         *            Encryption key which you used during encryption
         */

        private string encryptDecrypt(string _inputText, string _encryptionKey, EncryptMode _mode, string _initVector)
        {
            SymmetricKeyAlgorithmProvider aesCbcPkcs7 = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);

            // Creata a 16 byte initialization vector
            IBuffer iv = CryptographicBuffer.ConvertStringToBinary(_initVector, BinaryStringEncoding.Utf8);

            // Create an AES 128-bit (16 byte) key
            IBuffer          keyMaterial = CryptographicBuffer.ConvertStringToBinary(_encryptionKey, BinaryStringEncoding.Utf8);
            CryptographicKey key         = aesCbcPkcs7.CreateSymmetricKey(keyMaterial);

            if (_mode.Equals(EncryptMode.ENCRYPT))
            {
                // Encrypt the data
                IBuffer plainText      = CryptographicBuffer.ConvertStringToBinary(_inputText, BinaryStringEncoding.Utf8);
                IBuffer cipherText     = CryptographicEngine.Encrypt(key, plainText, iv);
                string  strEncrypted64 = CryptographicBuffer.EncodeToBase64String(cipherText);
                return(strEncrypted64);
            }
            else
            {
                // Decrypt the data
                IBuffer cipherText    = CryptographicBuffer.DecodeFromBase64String(_inputText);
                IBuffer decryptedText = CryptographicEngine.Decrypt(key, cipherText, iv);
                return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decryptedText));
            }
        }
コード例 #9
0
        async public void Decrypt()
        {
            CryptographicKey cryptographicKey = null;
            FileOpenPicker   fileOpenPicker   = new FileOpenPicker();

            fileOpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            fileOpenPicker.FileTypeFilter.Add("*");
            StorageFile file = await fileOpenPicker.PickSingleFileAsync();

            IBuffer bufferPrivateKey = await FileIO.ReadBufferAsync(file);

            AsymmetricKeyAlgorithmProvider provider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);

            try { cryptographicKey = provider.ImportKeyPair(bufferPrivateKey); }
            catch (Exception er) {
            }


            try { decryptedkey = CryptographicEngine.Decrypt(cryptographicKey, buffEncryptedSessionKey, null); }

            catch (Exception er)
            {
                ContentDialog contentDialog = new ContentDialog();
                contentDialog.Title           = "Wrong private key";
                contentDialog.Content         = "Try another private key";
                contentDialog.CloseButtonText = "Ok";

                await contentDialog.ShowAsync();
            }



            T8.Text = "Decrypted Key Base64: " + CryptographicBuffer.EncodeToBase64String(decryptedkey);
            T9.Text = "Decrypted Key BaseHex: " + CryptographicBuffer.EncodeToHexString(decryptedkey);
        }
コード例 #10
0
ファイル: RSAConvert.cs プロジェクト: ViperL/UWP
        /// <summary>
        /// WPRT的RSA私钥解密
        /// </summary>
        /// <param name="rawData"></param>
        /// <returns></returns>
        public static string PrivateDecrypt(string rawData)
        {
            try
            {
                /*将文本转换成IBuffer*/
                IBuffer bufferRawData = CryptographicBuffer.ConvertStringToBinary(rawData, BinaryStringEncoding.Utf8);

                /*加密算法提供程序*/
                AsymmetricKeyAlgorithmProvider provider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm
                                                              (AsymmetricAlgorithmNames.RsaPkcs1);

                /*导入私钥*/
                string           PRIVATE_KEY = "MIICXAIBAAKBgQCJIYvV7IEzHOm4vdgu8RWc9it09ggXCKNAMEtcQM4kXT1mQyEnbEeGVYOyJWTd2jVhpToxMQ4r9p9EKd1bMClAA/KhUjQC/l9YdS3MFAZC65V47Bx6CTad4bZo1E1D6x1rOjQe4lANxWnApwY4QPYGFxEmQD3yNyErh38VlNL2GQIDAQABAoGAFxGmpZFI1uFpTCPbx2HVQfeDrgRprf5NAFJfiyB3zVRGLPrkC+7CRY4DPqfdxRidXFTgakAXYzv05RGp5FpAxf1GBAR6HQxVcntBpNqJUo2UBP+IrXgPFDPdodAl9SWgaHKwc79pCARVdJutm86kRRsy5rjcWpR8HQCYWzk/lmUCQQDcRnenz6CAhMvztS04APlly3uhvLGIVsXkGdsmv7JltRvFmZ/1MqpvAbC6WrzFMlWeFgYz6EyBiqfH6m4CbdJbAkEAn18K40E3r9WzPlbhIAEs2SiY68iZGCmzR/0n6PR48NtFSGsSDRIR632oeftBPfN7W4+kUIehL2gt9RgnRH8bmwJBAJMYK4dQSyoHg/q2nf+sBt9HRsP2sccNyxBLg+EYWhU5H9aQhBTFRLLkOhP3y98TgcETjAjVs2E+KlSB4/yTQckCQH4axVG23CptDQyp0C7z3xnh7sa7DrC45lxzK25Aa6YhyruXxUvEXZuZ7YK/1gsAKz7y9RCnkVoitCK4vvGLJjsCQBbzsW7HwZVe5RMiRsjxX7v0Ng4NnM85tnX0GUmkpuixOpfcq3PsZo7ujcBvJ5IJvbXo4QuuIRKSmxItHI26tkI=";
                CryptographicKey privateKey  = provider.ImportKeyPair(CryptographicBuffer.DecodeFromBase64String(PRIVATE_KEY));

                //解密
                IBuffer result = CryptographicEngine.Decrypt(privateKey, bufferRawData, null);
                byte[]  res;
                CryptographicBuffer.CopyToByteArray(result, out res);
                return(Encoding.UTF8.GetString(res, 0, res.Length));
            }
            catch (Exception)
            {
                return(rawData);
            }
        }
コード例 #11
0
 /// <summary>
 /// Aes解密函数
 /// </summary>
 /// <param name="str">密文</param>
 /// <param name="key">密钥</param>
 /// <returns>解密结果</returns>
 public static string DecryptString(string str, string key)
 {
     if (string.IsNullOrEmpty(str))
     {
         return(null);
     }
     if (string.IsNullOrEmpty(key))
     {
         return(null);
     }
     if (key.Length != 32)
     {
         return(null);
     }
     try
     {
         SymmetricKeyAlgorithmProvider provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
         IBuffer          buffDecrypt           = CryptographicBuffer.DecodeFromBase64String(str);
         IBuffer          buffKey    = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8);
         CryptographicKey cKey       = provider.CreateSymmetricKey(buffKey);
         IBuffer          buffResult = CryptographicEngine.Decrypt(cKey, buffDecrypt, null);
         string           strResult  = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffResult);
         return(strResult);
     }
     catch (Exception)
     {
         return(null);
     }
 }
コード例 #12
0
 public static byte[] DecryptAES(byte[] source, string publicKey)
 {
     if (source == null || source.Length == 0)
     {
         throw new ArgumentNullException("source");
     }
     if (string.IsNullOrEmpty(publicKey))
     {
         throw new ArgumentNullException("publicKey");
     }
     try
     {
         var     str                       = Convert.ToBase64String(source);
         IBuffer toDecryptBuffer           = CryptographicBuffer.DecodeFromBase64String(str);
         SymmetricKeyAlgorithmProvider aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
         var    symetricKey                = aes.CreateSymmetricKey(GetMD5Hash(publicKey));
         var    buffDecrypted              = CryptographicEngine.Decrypt(symetricKey, toDecryptBuffer, null);
         byte[] result;
         CryptographicBuffer.CopyToByteArray(buffDecrypted, out result);
         return(result);
     }
     catch (Exception ex)
     {
         return(null);
     }
 }
コード例 #13
0
        private static string Decrypt(String strMsg)
        {
            Byte[]  bb          = Convert.FromBase64String(strMsg);
            IBuffer buffEncrypt = CryptographicEngine.Decrypt(Key, bb.AsBuffer(), IV.AsBuffer());

            return(CryptographicBuffer.ConvertBinaryToString(encoding, buffEncrypt));
        }
コード例 #14
0
        private void GetTokenResponse(object Sender, IqResultEventArgs e)
        {
            object[] P = (object[])e.State;
#if WINDOWS_UWP
            Certificate Certificate = (Certificate)P[0];
#else
            X509Certificate2 Certificate = (X509Certificate2)P[0];
#endif
            XmlElement E = e.FirstElement;

            if (e.Ok && E != null && E.LocalName == "getTokenChallenge" && E.NamespaceURI == NamespaceProvisioningToken)
            {
                int    SeqNr     = XML.Attribute(E, "seqnr", 0);
                string Challenge = E.InnerText;
                byte[] Bin       = System.Convert.FromBase64String(Challenge);

#if WINDOWS_UWP
                CryptographicKey Key = PersistedKeyProvider.OpenPublicKeyFromCertificate(Certificate,
                                                                                         Certificate.SignatureHashAlgorithmName, CryptographicPadding.RsaPkcs1V15);
                IBuffer Buffer = CryptographicBuffer.CreateFromByteArray(Bin);
                Buffer = CryptographicEngine.Decrypt(Key, Buffer, null);
                CryptographicBuffer.CopyToByteArray(Buffer, out Bin);
                string Response = System.Convert.ToBase64String(Bin);
#else
                Bin = Certificate.GetRSAPrivateKey().Decrypt(Bin, RSAEncryptionPadding.Pkcs1);
                string Response = System.Convert.ToBase64String(Bin);
#endif

                this.client.SendIqGet(this.provisioningServerAddress, "<getTokenChallengeResponse xmlns='" + NamespaceProvisioningToken + "' seqnr='" +
                                      SeqNr.ToString() + "'>" + Response + "</getTokenChallengeResponse>",
                                      this.GetTokenChallengeResponse, P);
            }
        }
コード例 #15
0
        /// <summary>
        /// Decrypts a message using a symmetric algorithm.
        /// </summary>
        private static void SymmetricDecrypt(
            TcpChannelToken token,
            ArraySegment <byte> dataToDecrypt,
            bool useClientKeys)
        {
            // get the decrypting key.
            CryptographicKey decryptingKey = (useClientKeys) ? token.ClientEncryptor : token.ServerEncryptor;
            IBuffer          IV            = (useClientKeys) ? CryptographicBuffer.CreateFromByteArray(token.ClientInitializationVector) : CryptographicBuffer.CreateFromByteArray(token.ServerInitializationVector);

            if (decryptingKey == null)
            {
                throw ServiceResultException.Create(StatusCodes.BadSecurityChecksFailed, "Token missing symmetric key object.");
            }

            SymmetricKeyAlgorithmProvider AesCbcProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbc);

            if (dataToDecrypt.Count % AesCbcProvider.BlockLength != 0)
            {
                throw ServiceResultException.Create(StatusCodes.BadSecurityChecksFailed, "Input data is not an even number of encryption blocks.");
            }

            byte[] blockToDecrypt = new byte[dataToDecrypt.Count];
            Array.ConstrainedCopy(dataToDecrypt.Array, dataToDecrypt.Offset, blockToDecrypt, 0, dataToDecrypt.Count);

            IBuffer block           = CryptographicBuffer.CreateFromByteArray(blockToDecrypt);
            IBuffer encryptedBuffer = CryptographicEngine.Decrypt(decryptingKey, block, IV);

            CryptographicBuffer.CopyToByteArray(encryptedBuffer, out blockToDecrypt);

            Array.ConstrainedCopy(blockToDecrypt, 0, dataToDecrypt.Array, dataToDecrypt.Offset, dataToDecrypt.Count);
        }
コード例 #16
0
ファイル: Aes.cs プロジェクト: vaginessa/BookmarkBrowser
        public byte[] Decrypt(byte[] buffer)
        {
#if WINDOWS_STORE
            SymmetricKeyAlgorithmProvider provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
            CryptographicKey aes    = provider.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(this.key));
            IBuffer          result = CryptographicEngine.Decrypt(aes, CryptographicBuffer.CreateFromByteArray(buffer), CryptographicBuffer.CreateFromByteArray(this.iv));

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

            return(decrypted);
#else
            using (System.Security.Cryptography.Aes aes = AesManaged.Create())
            {
                aes.KeySize = 256;
                aes.Mode    = CipherMode.CBC;

                aes.IV  = iv;
                aes.Key = key;
                using (ICryptoTransform decryptor = aes.CreateDecryptor())
                {
                    return(decryptor.TransformFinalBlock(buffer, 0, buffer.Length));
                }
            }
#endif
        }
コード例 #17
0
ファイル: RhoCrypt.cs プロジェクト: nhinze/rhodes
        public int dbEncrypt(String partition, int size, String data, out String dataOut)
        {
            SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
            CryptographicKey      AES;
            HashAlgorithmProvider HAP      = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            CryptographicHash     Hash_AES = HAP.CreateHash();

            try{
                byte[] hash = new byte[32];
                Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(partition)));
                byte[] temp;
                CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);

                Array.Copy(temp, 0, hash, 0, 16);
                Array.Copy(temp, 0, hash, 15, 16);

                AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));

                Windows.Storage.Streams.IBuffer Buffer = CryptographicBuffer.DecodeFromBase64String(data);
                byte[] Decrypted;
                CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(AES, Buffer, null), out Decrypted);
                dataOut = System.Text.Encoding.UTF8.GetString(Decrypted, 0, Decrypted.Length);
            }
            catch (Exception ex)
            {
                dataOut = "";
                return(getErrorCode() == 0 ? 1 : 0);
            }

            return(getErrorCode() == 0 ? 1 : 0);
        }
コード例 #18
0
        private byte[] DecryptBytesInternal(string data, byte[] iv)
        {
            var algo = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7);
            var key  = algo.CreateSymmetricKey(TextEncoding.GetBytes(_secretKey));

            return(CryptographicEngine.Decrypt(key, Convert.FromBase64String(data), iv));
        }
コード例 #19
0
        /// <summary>
        /// Decrypts a string in Unicode
        /// </summary>
        /// <param name="encryptedData">An encrypted string in Unicode</param>
        /// <returns>The decrypted string in Unicode</returns>
        public string Decrypt(string encryptedData)
        {
            var encryptedBinaryData = Encoding.Unicode.GetBytes(encryptedData).AsBuffer();
            var decryptedData       = CryptographicEngine.Decrypt(cryptographicKey, encryptedBinaryData, null);

            return(Encoding.Unicode.GetString(decryptedData.ToArray()));
        }
コード例 #20
0
ファイル: Crypto.cs プロジェクト: chriskmps/SecureChat
        //Decrypts Data (Always using private key)
        public static string Decrypt(String strAsymmetricAlgName, IBuffer buffPrivateKeyStorage, string encryptedMessage)
        {
            // Open the algorithm provider for the specified asymmetric algorithm.
            AsymmetricKeyAlgorithmProvider objAsymmAlgProv = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(strAsymmetricAlgName);

            // Import the public key from a buffer. You should keep your private key
            // secure. For the purposes of this example, however, the private key is
            // just stored in a static class variable.
            CryptographicKey keyPair = objAsymmAlgProv.ImportKeyPair(buffPrivateKeyStorage);

            //Convert message String to IBuffer
            IBuffer convertedString = CryptographicBuffer.DecodeFromBase64String(encryptedMessage);
            IBuffer buffDecryptedMessage;

            try {
                // Use the private key embedded in the key pair to decrypt the session key.
                buffDecryptedMessage = CryptographicEngine.Decrypt(keyPair, convertedString, null);
            } catch (System.ArgumentException) {
                string invalidDecryptionMessage = "INVALID DECRYPTION KEY";
                return(invalidDecryptionMessage);
            }

            //Return decrpyted message as a string
            string decryptedMessage = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffDecryptedMessage);

            return(decryptedMessage);
        }
コード例 #21
0
        public static string AES_Decrypt(string input, string pass)
        {
            SymmetricKeyAlgorithmProvider sap = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
            CryptographicKey      aes;
            HashAlgorithmProvider hap      = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            CryptographicHash     hash_AES = hap.CreateHash();

            string decrypted = "";

            try
            {
                byte[] hash = new byte[32];
                hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(pass)));
                byte[] temp;
                CryptographicBuffer.CopyToByteArray(hash_AES.GetValueAndReset(), out temp);

                Array.Copy(temp, 0, hash, 0, 16);
                Array.Copy(temp, 0, hash, 15, 16);

                aes = sap.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));

                IBuffer Buffer = CryptographicBuffer.DecodeFromBase64String(input);
                byte[]  Decrypted;
                CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(aes, Buffer, null), out Decrypted);
                decrypted = Encoding.UTF8.GetString(Decrypted, 0, Decrypted.Length);

                return(decrypted);
            }
            catch
            {
                return(null);
            }
        }
コード例 #22
0
ファイル: Cryptogram.cs プロジェクト: littlefeihu/checktask
        public async Task <byte[]> DecryptBytes(byte[] cipherText, byte[] key, byte[] iv)
        {
            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
            {
                throw new ArgumentNullException(Constants.SCipherText);
            }

            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException(Constants.Key);
            }

            if (iv == null || iv.Length <= 0)
            {
                throw new ArgumentNullException(Constants.IV);
            }

            IBuffer keyBuffer = key.AsBuffer(0, key.Length);
            IBuffer ivBuffer  = iv.AsBuffer(0, iv.Length);
            IBuffer encrypted = cipherText.AsBuffer(0, cipherText.Length);

            SymmetricKeyAlgorithmProvider symmetricAlgorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
            CryptographicKey cryptoKey2 = symmetricAlgorithm.CreateSymmetricKey(keyBuffer);
            IBuffer          decrypted  = CryptographicEngine.Decrypt(cryptoKey2, encrypted, ivBuffer);

            byte[] decryptedBytes = decrypted.ToArray(0, (int)decrypted.Length);
            return(await Task.Run(() => decryptedBytes));
        }
コード例 #23
0
ファイル: BaseCrypto.cs プロジェクト: msdiniz/WinRTExamples
        /// <summary>
        /// The decrypt asymmetric.
        /// </summary>
        /// <param name="message">
        /// The message.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        private string DecryptAsymmetric(string message)
        {
            IBuffer messageData      = CryptographicBuffer.DecodeFromBase64String(message);
            var     decryptedMessage = CryptographicEngine.Decrypt(this.keyPair, messageData, null);

            return(CryptographicBuffer.ConvertBinaryToString(Encoding, decryptedMessage));
        }
コード例 #24
0
ファイル: AESProvider.cs プロジェクト: Tsual/PSK
        public string Decrypt(string metaStr)
        {
            #region metaStr_buffer
            var metaStr_buffer = CryptographicBuffer.DecodeFromHexString(metaStr);
            #endregion

            #region _Key
            var _SymmetricKeyAlgorithmProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbc);
            var _Key = _SymmetricKeyAlgorithmProvider.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(this._key));
            #endregion

            #region IV_buffer
            var IV_buffer = CryptographicBuffer.CreateFromByteArray(_iv);
            #endregion

            IBuffer _result_buffer = CryptographicEngine.Decrypt(_Key, metaStr_buffer, IV_buffer);
            byte[]  dat            = new byte[256];
            CryptographicBuffer.CopyToByteArray(_result_buffer, out dat);

            #region rebuild string
            List <byte> list_byte = new List <byte>();
            for (int i = 0; i < dat.Count(); i++)
            {
                if (dat[i] != 0)
                {
                    list_byte.Add(dat[i]);
                }
            }
            #endregion
            return(Encoding.UTF8.GetString(list_byte.ToArray()));
        }
コード例 #25
0
        /// <summary>
        /// Decrypts a data buffer.
        /// </summary>
        /// <param name="buffer">
        /// The data buffer to decrypt.
        /// </param>
        /// <returns>
        /// Returns the decrypted data.
        /// </returns>
        public async Task <IBuffer> DecryptAsync(IBuffer buffer)
        {
            if (this.KeyBuffer == null)
            {
                throw new InvalidOperationException("Cannot encrypt data before Initialize has been called.");
            }

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

            return(await Task.Run(
                       () =>
            {
                try
                {
                    var aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(this.encryptionAlgorithm);
                    var key = this.KeyBuffer;
                    var cryptoKey = aes.CreateSymmetricKey(key);
                    var decrypted = CryptographicEngine.Decrypt(cryptoKey, buffer, null);
                    return decrypted;
                }
                catch (Exception ex)
                {
                    throw new DataEncryptException("Failed to decrypt data.", ex);
                }
            }));
        }
コード例 #26
0
        public static string AES_Decrypt(String EncryptedText, String DecryptionKey)
        {
            string decrypted = "";
            SymmetricKeyAlgorithmProvider SAP      = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
            HashAlgorithmProvider         HAP      = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            CryptographicHash             Hash_AES = HAP.CreateHash();

            try
            {
                //byte[] KeyBytes = System.Text.Encoding.UTF8.GetBytes(password);
                byte[] KeyBytes16 = new byte[16];
                Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(DecryptionKey)));
                byte[] KeyBytes;
                CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out KeyBytes);
                for (int i = 0; i < KeyBytes.Length; i++)
                {
                    KeyBytes16[i] = KeyBytes[i];
                }

                CryptographicKey key = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(KeyBytes16));


                IBuffer Buffer = CryptographicBuffer.DecodeFromBase64String(EncryptedText);
                byte[]  Decrypted;

                CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(key, Buffer, null), out Decrypted);
                decrypted = System.Text.Encoding.UTF8.GetString(Decrypted, 0, Decrypted.Length);
                return(decrypted);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                return("Error in Decryption:With Aes ");
            }
        }
コード例 #27
0
        public Task <byte[]> RsaDecryptAsync(byte[] data, byte[] privateKey, CryptoHashAlgorithm algorithm)
        {
            var provider  = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(ToAsymmetricAlgorithm(algorithm));
            var cryptoKey = provider.ImportKeyPair(privateKey, CryptographicPrivateKeyBlobType.Pkcs8RawPrivateKeyInfo);

            return(Task.FromResult(CryptographicEngine.Decrypt(cryptoKey, data)));
        }
コード例 #28
0
        public static string CipherDecryption(
            string strAlgName,
            IBuffer buffEncrypt,
            IBuffer iv,
            BinaryStringEncoding encoding,
            CryptographicKey key)
        {
            // Declare a buffer to contain the decrypted data.
            IBuffer buffDecrypted;

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

            // 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.
            return(CryptographicBuffer.ConvertBinaryToString(encoding, buffDecrypted));
        }
コード例 #29
0
        /// <summary>
        /// Decrypt a string using dual encryption method. Return a Decrypted clear string
        /// </summary>
        /// <param name="cipherString">Encrypted string</param>
        /// <param name="key">Unique key for encryption/decryption</param>
        /// <returns>Returns decrypted text.</returns>
        public static string DecryptString(string cipherString, string key)
        {
            try
            {
                // Get the MD5 key hash (you can as well use the binary of the key string)
                var keyHash = GetMD5HashKey(key);

                // Create a buffer that contains the encoded message to be decrypted.
                IBuffer toDecryptBuffer = CryptographicBuffer.DecodeFromBase64String(cipherString);

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

                // Create a symmetric key.
                var symetricKey = aes.CreateSymmetricKey(keyHash);

                var buffDecrypted = CryptographicEngine.Decrypt(symetricKey, toDecryptBuffer, null);

                string strDecrypted = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffDecrypted);

                return(strDecrypted);
            }
            catch (Exception ex)
            {
                // MetroEventSource.Log.Error(ex.Message);
                //throw;
                return("");
            }
        }
コード例 #30
0
        /// <summary>
        /// Used internally to handle the decryption
        /// </summary>
        /// <param name="buffEncrypt"></param>
        /// <returns></returns>
        private string CipherDecryption(IBuffer buffEncrypt)
        {
            IBuffer buffDecrypted;

            buffDecrypted = CryptographicEngine.Decrypt(key, buffEncrypt, iv);
            return(CryptographicBuffer.ConvertBinaryToString(encoding, buffDecrypted));
        }