コード例 #1
0
        public String SampleDeriveFromPbkdf(
            String strAlgName,
            UInt32 targetSize)
        {
            // Open the specified algorithm.
            KeyDerivationAlgorithmProvider objKdfProv = KeyDerivationAlgorithmProvider.OpenAlgorithm(strAlgName);

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

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

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

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

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

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

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

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

            // Return the encoded string
            return(strKeyBase64);
        }
コード例 #2
0
ファイル: Crypter.cs プロジェクト: gituser9/Private-Diary
        public static string Encrypt(string toEncrypt)
        {
            try
            {
                // Get the MD5 key hash (you can as well use the binary of the key string)
                var keyHash = GetMD5Hash(Constant.Key);

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

                // Create a symmetric key.
                var symetricKey = aes.CreateSymmetricKey(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)
            {
                // MetroEventSource.Log.Error(ex.Message);
                return("");
            }
        }
コード例 #3
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);
     }
 }
コード例 #4
0
        /// <summary>
        /// Symmetrically encrypts the specified buffer using a randomly generated key.
        /// </summary>
        /// <param name="data">The data to encrypt.</param>
        /// <param name="encryptionVariables">Optional encryption variables to use; or <c>null</c> to use randomly generated ones.</param>
        /// <returns>
        /// The result of the encryption.
        /// </returns>
        public override SymmetricEncryptionResult Encrypt(byte[] data, SymmetricEncryptionVariables encryptionVariables)
        {
            Requires.NotNull(data, "data");

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

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

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

            return(new SymmetricEncryptionResult(
                       symmetricKeyMaterial.ToArray(),
                       ivBuffer.ToArray(),
                       cipherTextBuffer.ToArray()));
        }
コード例 #5
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);
            }
        }
コード例 #6
0
        //String strMsg = "1234567812345678";     // Data to encrypt.
        //String strAlgName = SymmetricAlgorithmNames.AesCbc;
        //UInt32 keyLength = 32;                  // Length of the key, in bytes
        //BinaryStringEncoding encoding;          // Binary encoding value
        //IBuffer iv;                             // Initialization vector
        //CryptographicKey key;

        public async Task EncryptFileAes(FileItemViewModel fileToEncrypt)
        {
            if (!fileToEncrypt.IsEncrypted)
            {
                var fileBuffer = await FileIO.ReadBufferAsync(fileToEncrypt.File);

                CreateNonce(fileToEncrypt);
                var encryptedData = CryptographicEngine.EncryptAndAuthenticate(aesKey, fileBuffer, fileToEncrypt.Nonce,
                                                                               null);

                var serialData = new SerialisableAuthData(encryptedData.AuthenticationTag, encryptedData.EncryptedData);

                var serializer = new XmlSerializer(typeof(SerialisableAuthData));
                using (var stream = await fileToEncrypt.File.OpenStreamForWriteAsync())
                {
                    TextWriter output = new StreamWriter(stream);
                    serializer.Serialize(output, serialData);
                    await stream.FlushAsync();

                    output.Dispose();
                    stream.Dispose();
                }
                fileToEncrypt.IsEncrypted = true;
            }
            else
            {
                throw new Exception("Tried to encrypt file with encrypted flag already set to true");
            }
        }
コード例 #7
0
        public string Encrypt(string plainText)
        {
            if (string.IsNullOrEmpty(plainText))
            {
                throw new ArgumentNullException("plainText");
            }
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException("Key");
            }
            if (string.IsNullOrEmpty(iv))
            {
                throw new ArgumentNullException("IV");
            }

            BinaryStringEncoding encoding = BinaryStringEncoding.Utf8;

            IBuffer          keyBuffer = CryptographicBuffer.ConvertStringToBinary(key, encoding);
            CryptographicKey cryptoKey = alg.CreateSymmetricKey(keyBuffer);
            IBuffer          ivBuffer  = CryptographicBuffer.ConvertStringToBinary(iv, encoding);

            // Add padding so buffer length is multiple of 16
            plainText = PadString(plainText);

            IBuffer inputBuffer     = CryptographicBuffer.ConvertStringToBinary(plainText, encoding);
            IBuffer encryptedBuffer = CryptographicEngine.Encrypt(cryptoKey, inputBuffer, ivBuffer);

            return(CryptographicBuffer.EncodeToHexString(encryptedBuffer));
        }
コード例 #8
0
        private static string Encrypt(String strMsg)
        {
            IBuffer buffMsg     = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding);
            IBuffer buffEncrypt = CryptographicEngine.Encrypt(Key, buffMsg, IV.AsBuffer());

            return(CryptographicBuffer.EncodeToBase64String(buffEncrypt));
        }
コード例 #9
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));
        }
コード例 #10
0
 public bool VerifySignature(byte[] key)
 {
     return(CryptographicEngine.VerifySignature(
                AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithm.RsaSignPssSha512).ImportPublicKey(key),
                Encoding.Unicode.GetBytes(License.ToJson(Formatting.None)),
                Convert.FromBase64String(Signature)));
 }
コード例 #11
0
        /// <summary>
        /// This is the click handler for the 'RunSample' button.  It is responsible for executing the sample code.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RunSample_Click(object sender, RoutedEventArgs e)
        {
            SignVerifyText.Text = "";

            String  cookie = "Some Data to sign";
            IBuffer Data   = CryptographicBuffer.ConvertStringToBinary(cookie, BinaryStringEncoding.Utf16BE);

            CryptographicKey key = null;

            if ((bool)bHmac.IsChecked)
            {
                key = GenerateHMACKey();
            }
            else
            {
                key = GenerateAsymmetricKey();
            }

            if (key != null)
            {
                // Sign the data by using the generated key.
                IBuffer Signature = CryptographicEngine.Sign(key, Data);
                SignVerifyText.Text += "    Data was successfully signed.\n";

                // Verify the signature by using the public key.
                if (!CryptographicEngine.VerifySignature(key, Data, Signature))
                {
                    SignVerifyText.Text += "Signature verification failed!";
                    return;
                }
                SignVerifyText.Text += "    Signature was successfully verified.\n";
            }
        }
コード例 #12
0
        void CreateHMAC(String strMsg, String strAlgName, out IBuffer buffMsg, out CryptographicKey hmacKey, out IBuffer buffHMAC)
        {
            // Create a MacAlgorithmProvider object for the specified algorithm.
            MacAlgorithmProvider objMacProv = MacAlgorithmProvider.OpenAlgorithm(strAlgName);

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

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

            buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding);

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

            hmacKey = objMacProv.CreateKey(buffKeyMaterial);

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

            // Verify that the HMAC length is correct for the selected algorithm
            if (buffHMAC.Length != objMacProv.MacLength)
            {
                throw new Exception("Error computing digest");
            }
        }
コード例 #13
0
ファイル: EncryptionHelper.cs プロジェクト: LuanNg/PianoTiles
    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);

        // 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);
    }
        public static async Task <string> CreateDeviceAuthChallengeResponseAsync(IDictionary <string, string> challengeData)
        {
            string      authHeaderTemplate = "PKeyAuth {0}, Context=\"{1}\", Version=\"{2}\"";
            Certificate certificate        = null;

            try
            {
                certificate = await FindCertificate(challengeData).ConfigureAwait(false);
            }
            catch (AdalException ex)
            {
                if (ex.ErrorCode == AdalError.DeviceCertificateNotFound)
                {
                    return(await Task.FromResult(string.Format(CultureInfo.InvariantCulture, @"PKeyAuth Context=""{0}"",Version=""{1}""", challengeData["Context"], challengeData["Version"])).ConfigureAwait(false));
                }
            }
            DeviceAuthJWTResponse response = new DeviceAuthJWTResponse(challengeData["SubmitUrl"],
                                                                       challengeData["nonce"], Convert.ToBase64String(certificate.GetCertificateBlob().ToArray()));
            IBuffer input = CryptographicBuffer.ConvertStringToBinary(response.GetResponseToSign(),
                                                                      BinaryStringEncoding.Utf8);
            CryptographicKey keyPair = await
                                       PersistedKeyProvider.OpenKeyPairFromCertificateAsync(certificate, HashAlgorithmNames.Sha256,
                                                                                            CryptographicPadding.RsaPkcs1V15).AsTask().ConfigureAwait(false);

            IBuffer signed = await CryptographicEngine.SignAsync(keyPair, input).AsTask().ConfigureAwait(false);

            string signedJwt = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", response.GetResponseToSign(),
                                             Base64UrlEncoder.Encode(signed.ToArray()));
            string authToken = string.Format(CultureInfo.InvariantCulture, " AuthToken=\"{0}\"", signedJwt);

            return(string.Format(CultureInfo.InvariantCulture, authHeaderTemplate, authToken, challengeData["Context"], challengeData["Version"]));
        }
コード例 #15
0
        /// <summary>
        /// 对字符串依据指定的算法和密钥进行加密,如果使用 CBC 算法,还需要初始化向量
        /// </summary>
        /// <param name="content">源字符串</param>
        /// <param name="strAlgName">加密算法</param>
        /// <param name="encoding">字符串编码方式</param>
        /// <param name="key">密钥</param>
        /// <param name="iniVec">CBC 初始化向量</param>
        /// <returns></returns>
        public static IBuffer CipherEncryption(string content, string strAlgName,
                                               BinaryStringEncoding encoding, CryptographicKey key, IBuffer iniVec = null)
        {
            // Create a buffer that contains the encoded message to be encrypted.
            IBuffer buffContent = CryptographicBuffer.ConvertStringToBinary(content, 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 ((buffContent.Length % objAlg.BlockLength) != 0)
                {
                    throw new Exception("Message buffer length must be multiple of block length.");
                }
            }

            if (strAlgName.Contains("CBC") && iniVec == null)
            {
                throw new ArgumentException("Using CBC Encryption, initial vector must have value");
            }
            // Encrypt the data and return.
            IBuffer buffEncrypt = CryptographicEngine.Encrypt(key, buffContent, iniVec);

            return(buffEncrypt);
        }
コード例 #16
0
        public static IBuffer Encrypt(IBuffer data,
                                      CryptographicKey key,
                                      out IBuffer iv,
                                      String AlgorithmName = null)
        {
            //declares
            var strAlgName = AlgorithmName != null ? AlgorithmName : DefaultAlgorithm;

            iv = null;

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

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

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

            // Encrypt the data and return.
            return(CryptographicEngine.Encrypt(key, data, iv));
        }
コード例 #17
0
        public 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));
        }
コード例 #18
0
ファイル: SecureString.cs プロジェクト: pyntya/Cauldron
        /// <summary>
        /// Initializes a new instance of the <see cref="SecureString"/> class from a subarray of
        /// <see cref="char"/> objects.
        /// </summary>
        /// <param name="value">A pointer to an array of System.Char objects.</param>
        /// <param name="length">The number of elements of value to include in the new instance.</param>
        public unsafe SecureString(char *value, int length)
        {
            this.Length = length;
            this.initialisationVector = Encoding.UTF8.GetBytes(CryptoUtils.BrewPassword(42)).GetBytes(16);

            byte[] dataCopy = new byte[length];
            var    gc       = GCHandle.Alloc(dataCopy, GCHandleType.Pinned);

            for (int i = 0; i < dataCopy.Length; i++)
            {
                dataCopy[i] = (byte)*(value + i);
            }

            // We cannot use our Aes implemtation in here because we will cause a cycling
            // dependency... And that will lead to a StackOverflow

            var passPhrase  = Encoding.UTF8.GetBytes(Debug.HardwareIdentifier.GetHash(HashAlgorithms.Sha512));
            var keyMaterial = CryptographicBuffer.CreateFromByteArray(passPhrase);

            var toDecryptBuffer = CryptographicBuffer.CreateFromByteArray(dataCopy);
            var aes             = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
            var symetricKey     = aes.CreateSymmetricKey(keyMaterial);
            var buffEncrypted   = CryptographicEngine.Encrypt(symetricKey, dataCopy.AsBuffer(), initialisationVector.AsBuffer());

            CryptographicBuffer.CopyToByteArray(buffEncrypted, out data);

            gc.FillWithRandomValues(dataCopy.Length);
        }
コード例 #19
0
 public async Task DecryptFileAes(FileItemViewModel fileToDecrypt)
 {
     if (fileToDecrypt.IsEncrypted)
     {
         var serializer = new XmlSerializer(typeof(SerialisableAuthData));
         SerialisableAuthData tagData = null;
         using (var stream = await fileToDecrypt.File.OpenStreamForReadAsync())
         {
             tagData = serializer.Deserialize(stream) as SerialisableAuthData;
             stream.Dispose();
         }
         if (tagData != null)
         {
             var data          = tagData.GetData();
             var tag           = tagData.GetTag();
             var decryptedData = CryptographicEngine.DecryptAndAuthenticate(aesKey, data,
                                                                            fileToDecrypt.Nonce, tag, null);
             await FileIO.WriteBufferAsync(fileToDecrypt.File, decryptedData);
         }
         fileToDecrypt.IsEncrypted = false;
     }
     else
     {
         throw new Exception("Tried to dencrypt file with encrypted flag already set to false");
     }
 }
コード例 #20
0
        /// <summary>
        /// Encrypt using AES/ECB
        /// </summary>
        /// <param name="message">The message to encrypt</param>
        /// <param name="key">The key with which to encrypt</param>
        /// <returns>Encrypted data</returns>
        private static byte[] EncryptAes(byte[] message, CryptographicKey key)
        {
            int blockRoundedSize = ((message.Length + 15) / 16) * 16;
            byte[] paddedMessage = new byte[blockRoundedSize];
            Array.Copy(message, paddedMessage, message.Length);

            IBuffer encrypted;
            IBuffer iv = null;
            IBuffer data = CryptographicBuffer.CreateFromByteArray(paddedMessage);
            String algName = SymmetricAlgorithmNames.AesEcb;

            // Encrypt the data.
            try
            {
                encrypted = CryptographicEngine.Encrypt(key, data, iv);
            }
            catch (Exception)
            {
                Debug.WriteLine("An invalid key size was selected for the given algorithm.\n"); 
                return null;
            }

            byte[] encryptedMsg = new byte[encrypted.Length];
            CryptographicBuffer.CopyToByteArray(encrypted, out encryptedMsg);
            return encryptedMsg;
        }
コード例 #21
0
        /// <summary>
        /// Verifies the asymmetric signature of the hash of some data blob.
        /// </summary>
        /// <param name="signingPublicKey">The public key used to verify the signature.</param>
        /// <param name="hash">The hash of the data that was signed.</param>
        /// <param name="signature">The signature.</param>
        /// <param name="hashAlgorithm">The hash algorithm used to hash the data.</param>
        /// <returns>
        /// A value indicating whether the signature is valid.
        /// </returns>
        public override bool VerifyHash(byte[] signingPublicKey, byte[] hash, byte[] signature, string hashAlgorithm)
        {
            var signer = this.GetSignatureProvider(hashAlgorithm);
            var key    = signer.ImportPublicKey(signingPublicKey.ToBuffer(), CryptographicPublicKeyBlobType.Capi1PublicKey);

            return(CryptographicEngine.VerifySignatureWithHashInput(key, hash.ToBuffer(), signature.ToBuffer()));
        }
コード例 #22
0
        /// <summary>
        /// Generate the signature value based on the given signature base and hash algorithm
        /// </summary>
        /// <param name="macAlgorithm">The hash algorithm used to perform the hashing</param>
        /// <param name="signatureBase">The signature based as produced by the GenerateSignatureBase method or by any other means</param>
        /// <param name="key">The key to generate signatrure with macAlgorithm.</param>
        /// <returns>A base64 string of the hash value</returns>
        public string GenerateSignatureUsingHash(MacAlgorithmProvider macAlgorithm, string data, string key)
        {
            if (macAlgorithm == null)
            {
                throw new ArgumentNullException("macAlgorithm");
            }

            if (string.IsNullOrEmpty(data))
            {
                throw new ArgumentNullException("data");
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("key");
            }

            // Convert the key to a buffer.
            IBuffer KeyMaterial = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8);

            // Generate key to sign by specified algorithm.
            CryptographicKey MacKey = macAlgorithm.CreateKey(KeyMaterial);

            // Convert the data to a buffer.
            IBuffer DataToBeSigned = CryptographicBuffer.ConvertStringToBinary(data, BinaryStringEncoding.Utf8);

            // Sign the data by specified algorithm with generated key.
            IBuffer SignatureBuffer = CryptographicEngine.Sign(MacKey, DataToBeSigned);

            // Get signature with Base64.
            string signature = CryptographicBuffer.EncodeToBase64String(SignatureBuffer);

            return(signature);
        }
コード例 #23
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);
     }
 }
コード例 #24
0
            public string HMACSign(byte[] data, string key, SigningAlgorithm algorithmName)
            {
                var crypt = MacAlgorithmProvider.OpenAlgorithm(ConvertToAlgorithName(algorithmName));

                if (String.IsNullOrEmpty(key))
                {
                    throw new ArgumentNullException("key", "Please specify a Secret Signing Key.");
                }

                if (data == null || data.Length == 0)
                {
                    throw new ArgumentNullException("data", "Please specify data to sign.");
                }

                if (null == crypt)
                {
                    throw new ArgumentNullException("algorithm", "Please specify a KeyedHashAlgorithm to use.");
                }

                IBuffer dataBuffer = CryptographicBuffer.CreateFromByteArray(data);
                var     keyBuffer  = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8);
                var     cryptoKey  = crypt.CreateKey(keyBuffer);

                var    sigBuffer = CryptographicEngine.Sign(cryptoKey, dataBuffer);
                string signature = CryptographicBuffer.EncodeToBase64String(sigBuffer);

                return(signature);
            }
コード例 #25
0
        byte[] load_and_verify(ref string filepath)
        {
            byte[] data = userLoader(ref filepath);
            if (data == null)
            {
                return(null);
            }
            if (data.Length < 128)
            {
                throw new InvalidProgramException(filepath + " length less than 128!");
            }

            byte[] sig         = new byte[128];
            byte[] filecontent = new byte[data.Length - 128];
            Array.Copy(data, sig, 128);
            Array.Copy(data, 128, filecontent, 0, filecontent.Length);

#if !UNITY_WSA || UNITY_EDITOR
            if (!rsa.VerifyData(filecontent, sha, sig))
            {
                throw new InvalidProgramException(filepath + " has invalid signature!");
            }
#else
            if (!CryptographicEngine.VerifySignature(key, CryptographicBuffer.CreateFromByteArray(filecontent), CryptographicBuffer.CreateFromByteArray(sig)))
            {
                throw new InvalidProgramException(filepath + " has invalid signature!");
            }
#endif
            return(filecontent);
        }
コード例 #26
0
            public byte[] HMACSignBinary(byte[] data, byte[] key, SigningAlgorithm algorithmName)
            {
                var crypt = MacAlgorithmProvider.OpenAlgorithm(ConvertToAlgorithName(algorithmName));

                if (key == null || key.Length == 0)
                {
                    throw new ArgumentNullException("key", "Please specify a Secret Signing Key.");
                }

                if (data == null || data.Length == 0)
                {
                    throw new ArgumentNullException("data", "Please specify data to sign.");
                }

                if (null == crypt)
                {
                    throw new ArgumentNullException("algorithm", "Please specify a KeyedHashAlgorithm to use.");
                }

                IBuffer dataBuffer = CryptographicBuffer.CreateFromByteArray(data);
                var     keyBuffer  = CryptographicBuffer.CreateFromByteArray(key);
                var     cryptoKey  = crypt.CreateKey(keyBuffer);

                var sigBuffer = CryptographicEngine.Sign(cryptoKey, dataBuffer);

                return(sigBuffer.ToArray());
            }
コード例 #27
0
ファイル: Crypter.cs プロジェクト: gituser9/Private-Diary
        public static string Decrypt(string cipherString)
        {
            try
            {
                // Get the MD5 key hash (you can as well use the binary of the key string)
                var keyHash = GetMD5Hash(Constant.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("");
            }
        }
コード例 #28
0
        public byte[] Sign(byte[] securedInput, object key)
        {
            //using (var sha = HashAlgorithm)
            //{
            //var privateKey = Ensure.Type<AsymmetricAlgorithm>(key, "RsaUsingSha alg expects key to be of AsymmetricAlgorithm type.");

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

            //CryptographicKey cryptographicKey = (CryptographicKey)key;
            CryptographicKey cryptographicKey = provider.ImportKeyPair(((CryptographicKey)key).Export(CryptographicPrivateKeyBlobType.BCryptPrivateKey),
                                                                       CryptographicPrivateKeyBlobType.BCryptPrivateKey);

            //provider.ImportKeyPair(null, CryptographicPrivateKeyBlobType.)

            IBuffer signedData =
                CryptographicEngine.Sign(cryptographicKey, CryptographicBuffer.CreateFromByteArray(securedInput));

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

            return(result);

            //var pkcs1 = new RSAPKCS1SignatureFormatter(privateKey);
            //pkcs1.SetHashAlgorithm(hashMethod);

            //return pkcs1.CreateSignature(sha.ComputeHash(securedInput));
            //}
        }
コード例 #29
0
ファイル: ApiHelper.cs プロジェクト: lenghun/BiliBili-UWP
        public static async Task <string> GetEncryptedPassword(string passWord)
        {
            string base64String;

            try
            {
                //https://secure.bilibili.com/login?act=getkey&rnd=4928
                //https://passport.bilibili.com/login?act=getkey&rnd=4928
                HttpBaseProtocolFilter httpBaseProtocolFilter = new HttpBaseProtocolFilter();
                httpBaseProtocolFilter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Expired);
                httpBaseProtocolFilter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Untrusted);
                Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(httpBaseProtocolFilter);
                //WebClientClass wc = new WebClientClass();
                string stringAsync = await httpClient.GetStringAsync((new Uri("https://secure.bilibili.com/login?act=getkey&rnd=" + new Random().Next(1000, 9999), UriKind.Absolute)));

                JObject jObjects = JObject.Parse(stringAsync);
                string  str      = jObjects["hash"].ToString();
                string  str1     = jObjects["key"].ToString();
                string  str2     = string.Concat(str, passWord);
                string  str3     = Regex.Match(str1, "BEGIN PUBLIC KEY-----(?<key>[\\s\\S]+)-----END PUBLIC KEY").Groups["key"].Value.Trim();
                byte[]  numArray = Convert.FromBase64String(str3);
                AsymmetricKeyAlgorithmProvider asymmetricKeyAlgorithmProvider = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
                CryptographicKey cryptographicKey = asymmetricKeyAlgorithmProvider.ImportPublicKey(WindowsRuntimeBufferExtensions.AsBuffer(numArray), 0);
                IBuffer          buffer           = CryptographicEngine.Encrypt(cryptographicKey, WindowsRuntimeBufferExtensions.AsBuffer(Encoding.UTF8.GetBytes(str2)), null);
                base64String = Convert.ToBase64String(WindowsRuntimeBufferExtensions.ToArray(buffer));
            }
            catch (Exception)
            {
                throw;
                //base64String = pw;
            }
            return(base64String);
        }
コード例 #30
0
ファイル: UWPEncryption.cs プロジェクト: WongKyle/xoff
        private void GenerateKeyMaterial(string password, uint iterationCount, out IBuffer keyMaterial, out IBuffer iv)
        {
            // setup KDF parameters for the desired salt and iteration count
            IBuffer saltBuffer = CryptographicBuffer.CreateFromByteArray(SALT);
            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(_keyDerivationAlgo);

            var     pwBytes        = Encoding.GetEncoding("ASCII").GetBytes(password);
            IBuffer passwordBuffer = CryptographicBuffer.CreateFromByteArray(pwBytes);

            //IBuffer passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
            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);
        }