/// <summary>
        /// Tries to sign and verify a bit of test data using the given certificate.
        /// This will cause the security subsystem to grant the calling app access
        /// to the certificate's private key for the current session.
        ///
        /// </summary>
        /// <param name="selectedCertificate">The X.509 Certificate for which access is required</param>
        /// <returns>True on successful signing and verification, false otherwise.</returns>
        private static bool VerifyCertificateKeyAccess(Certificate selectedCertificate)
        {
            bool VerifyResult = false;              // default to access failure
            var  keyPairTask  = PersistedKeyProvider.OpenKeyPairFromCertificateAsync(
                selectedCertificate, HashAlgorithmNames.Sha1,
                CryptographicPadding.RsaPkcs1V15).AsTask();

            keyPairTask.Wait();
            CryptographicKey keyPair = keyPairTask.Result;
            String           buffer  = "Data to sign";
            IBuffer          Data    = CryptographicBuffer.ConvertStringToBinary(buffer, BinaryStringEncoding.Utf16BE);

            try
            {
                // sign the data by using the key
                var signedDataTask = CryptographicEngine.SignAsync(keyPair, Data).AsTask();
                signedDataTask.Wait();
                IBuffer Signed = signedDataTask.Result;
                VerifyResult = CryptographicEngine.VerifySignature(keyPair, Data, Signed);
            }
            catch (Exception exp)
            {
                Debug.WriteLine("Verification Failed. Exception Occurred : {0}", exp.Message);
                // default result is false so drop through to exit.
            }

            return(VerifyResult);
        }
Esempio n. 2
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);
        }
Esempio n. 3
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";
            }
        }
        /// <summary>
        /// Verifies the asymmetric signature of some data blob.
        /// </summary>
        /// <param name="signingPublicKey">The public key used to verify the signature.</param>
        /// <param name="data">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 VerifySignature(byte[] signingPublicKey, byte[] data, byte[] signature, string hashAlgorithm)
        {
            var signer = this.GetSignatureProvider(hashAlgorithm);
            var key    = signer.ImportPublicKey(signingPublicKey.ToBuffer(), CryptographicPublicKeyBlobType.Capi1PublicKey);

            return(CryptographicEngine.VerifySignature(key, data.ToBuffer(), signature.ToBuffer()));
        }
Esempio n. 5
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)));
 }
Esempio n. 6
0
        private static bool VerifyHMAC(IBuffer data, IBuffer hmacKeyBuffer, IBuffer hmac)
        {
            var provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
            var key      = provider.CreateKey(hmacKeyBuffer);

            return(CryptographicEngine.VerifySignature(key, data, hmac));
        }
Esempio n. 7
0
        public static async Task <bool> VerifyCertificateKeyAccess(Certificate selectedCertificate)
        {
            bool             VerifyResult = false; // default to access failure
            CryptographicKey keyPair      = await PersistedKeyProvider.OpenKeyPairFromCertificateAsync(
                selectedCertificate, HashAlgorithmNames.Sha1,
                CryptographicPadding.RsaPkcs1V15);

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

            try
            {
                //sign the data by using the key
                IBuffer Signed = await CryptographicEngine.SignAsync(keyPair, Data);

                VerifyResult = CryptographicEngine.VerifySignature(keyPair, Data, Signed);
            }
            catch (Exception exp)
            {
                System.Diagnostics.Debug.WriteLine("Verification Failed. Exception Occurred : {0}", exp.Message);
                // default result is false so drop through to exit.
            }

            return(VerifyResult);
        }
        public static bool Verify(byte[] key, byte[] message, byte[] signature)
        {
            IMacAlgorithmProvider provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithm.HmacSha256);

            ICryptographicKey hmacKey = provider.CreateKey(key);

            return(CryptographicEngine.VerifySignature(hmacKey, message, signature));
        }
        public bool IsSignatureValid(byte[] publicKey, byte[] data, byte[] signature)
        {
            string base64ServerKey = @"BgIAAACkAABSU0ExAAQAAAEAAQDZr6InA2zWwmTIQig+hi4AFP1+80cGdVf05OACoSPemuD1MlRhVv0FlNyrEPgEUltGpHLWjJVu+52ofFcZ4vlhA9ud63/GNwF+klu93wGnL7/9B3W1H5Wvdk1PBHKKrFgB5B+ThCpu60zU8+/xyqzZCImdm2OakrhqYo/PfHPgzQ==";
            var    alg             = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaSignPkcs1Sha1);
            var    key             = alg.ImportPublicKey(CryptographicBuffer.DecodeFromBase64String(base64ServerKey));

            return(CryptographicEngine.VerifySignature(key, data.AsBuffer(), signature.AsBuffer()));
        }
        public bool Verify([ReadOnlyArray] byte[] signature, [ReadOnlyArray] byte[] securedInput, object key)
        {
            var sharedKey = Ensure.Type <byte[]>(key, "HmacUsingSha expects key to be byte[] array.");

            IBuffer msg  = CryptographicBuffer.CreateFromByteArray(securedInput);
            IBuffer hmac = CryptographicBuffer.CreateFromByteArray(signature);

            CryptographicKey hmacKey = AlgProvider.CreateKey(CryptographicBuffer.CreateFromByteArray(sharedKey));

            return(CryptographicEngine.VerifySignature(hmacKey, msg, hmac));
        }
Esempio n. 11
0
        private async void VerifyButton_Click_1(object sender, RoutedEventArgs e)
        {
            var provider = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA256");
            var key      = provider.CreateKey(
                AsBuffer(MakeBigPassword(PASSWORD1)));
            var result = CryptographicEngine.VerifySignature(key,
                                                             AsBuffer(BigTextBox.Text),
                                                             _signature.AsBuffer());

            await SimpleDialog(result? "The signature was valid. Your data was not modified." :
                               "The signature is invalid. The data has been tampered with since it was last signed.");
        }
Esempio n. 12
0
        public static bool Verify(byte[] key, byte[] message, byte[] signature)
        {
            MacAlgorithmProvider provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);

            IBuffer          buffKey = CryptographicBuffer.CreateFromByteArray(key);
            CryptographicKey hmacKey = provider.CreateKey(buffKey);

            IBuffer buffMessage = CryptographicBuffer.CreateFromByteArray(message);

            IBuffer buffSignature = CryptographicBuffer.CreateFromByteArray(signature);

            return(CryptographicEngine.VerifySignature(hmacKey, buffMessage, buffSignature));
        }
        public bool Verify([ReadOnlyArray] byte[] signature, [ReadOnlyArray] byte[] securedInput, object key)
        {
            var publicKey = Ensure.Type <CryptographicKey>(key, "EcdsaUsingSha expects key to be of type 'CryptographicKey'");

            IBuffer msg = CryptographicBuffer.CreateFromByteArray(securedInput);
            IBuffer sig = CryptographicBuffer.CreateFromByteArray(signature);

            //reattach key to alg provider
            IBuffer keyBlob = publicKey.ExportPublicKey(CryptographicPublicKeyBlobType.BCryptPublicKey);

            CryptographicKey cKey = AlgProvider.ImportPublicKey(keyBlob, CryptographicPublicKeyBlobType.BCryptPublicKey);

            return(CryptographicEngine.VerifySignature(cKey, msg, sig));
        }
Esempio n. 14
0
        private static bool SampleVerifyHMAC(IBuffer buffMsg, CryptographicKey hmacKey, IBuffer buffHMAC)
        {
            Boolean IsAuthenticated = CryptographicEngine.VerifySignature(hmacKey, buffMsg, buffHMAC);

            if (!IsAuthenticated)
            {
                Debug.WriteLine("The Integrity of RSA cannot be verified.");
                return(false);
            }
            else
            {
                Debug.WriteLine("The Integrity of RSA verified succesful");
                return(true);
            }
        }
Esempio n. 15
0
        /// <summary>
        /// The verify asymmetric.
        /// </summary>
        /// <param name="data">
        /// The data.
        /// </param>
        /// <param name="signature">
        /// The signature.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        private bool VerifyAsymmetric(string data, string signature)
        {
            if (this.keyPair == null)
            {
                throw new Exception("Must sign to generate the key pair first.");
            }

            IBuffer buffer          = CryptographicBuffer.ConvertStringToBinary(data, Encoding);
            IBuffer signatureBuffer = CryptographicBuffer.DecodeFromBase64String(signature);
            var     algorithm       = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(this.AlgorithmName);

            var keys = algorithm.ImportKeyPair(this.keyPair.Export());

            return(CryptographicEngine.VerifySignature(keys, buffer, signatureBuffer));
        }
        /// <summary>
        /// 认证用户授权
        /// </summary>
        /// <returns></returns>
        public static async Task <AuthenticatorState> VerifyUserAsync()
        {
            if (await CheckSupportAsync().ConfigureAwait(false))
            {
                if (ApplicationData.Current.LocalSettings.Values["WindowsHelloPublicKeyForUser"] is string PublicKey)
                {
                    KeyCredentialRetrievalResult RetrievalResult = await KeyCredentialManager.OpenAsync(CredentialName);

                    switch (RetrievalResult.Status)
                    {
                    case KeyCredentialStatus.Success:
                    {
                        KeyCredentialOperationResult OperationResult = await RetrievalResult.Credential.RequestSignAsync(CryptographicBuffer.ConvertStringToBinary(ChallengeText, BinaryStringEncoding.Utf8));

                        if (OperationResult.Status == KeyCredentialStatus.Success)
                        {
                            var Algorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaSignPkcs1Sha256);
                            var Key       = Algorithm.ImportPublicKey(CryptographicBuffer.DecodeFromHexString(PublicKey));
                            return(CryptographicEngine.VerifySignature(Key, CryptographicBuffer.ConvertStringToBinary(ChallengeText, BinaryStringEncoding.Utf8), OperationResult.Result) ? AuthenticatorState.VerifyPassed : AuthenticatorState.VerifyFailed);
                        }
                        else
                        {
                            return(AuthenticatorState.UnknownError);
                        }
                    }

                    case KeyCredentialStatus.NotFound:
                    {
                        return(AuthenticatorState.CredentialNotFound);
                    }

                    default:
                    {
                        return(AuthenticatorState.UnknownError);
                    }
                    }
                }
                else
                {
                    return(AuthenticatorState.UserNotRegistered);
                }
            }
            else
            {
                return(AuthenticatorState.WindowsHelloUnsupport);
            }
        }
Esempio n. 17
0
        /// <summary>
        /// The verify symmetric.
        /// </summary>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <param name="data">
        /// The data.
        /// </param>
        /// <param name="signature">
        /// The signature.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        private bool VerifySymmetric(string key, string data, string signature)
        {
            IBuffer buffer          = CryptographicBuffer.ConvertStringToBinary(data, Encoding);
            IBuffer signatureBuffer = CryptographicBuffer.DecodeFromBase64String(signature);

            if (this.hashNames.Contains(this.AlgorithmName))
            {
                var     algorithm = HashAlgorithmProvider.OpenAlgorithm(this.AlgorithmName);
                IBuffer hash      = algorithm.HashData(buffer);
                return(CryptographicBuffer.Compare(hash, signatureBuffer));
            }

            var     macAlgorithm = MacAlgorithmProvider.OpenAlgorithm(this.AlgorithmName);
            IBuffer keyBuffer    = CryptographicBuffer.ConvertStringToBinary(key, Encoding);
            var     keyMaterial  = macAlgorithm.CreateKey(keyBuffer);

            return(CryptographicEngine.VerifySignature(keyMaterial, buffer, signatureBuffer));
        }
Esempio n. 18
0
        /// <summary>
        /// Verifies the asymmetric signature of some data blob.
        /// </summary>
        /// <param name="signingPublicKey">The public key used to verify the signature.</param>
        /// <param name="data">The data that was signed.</param>
        /// <param name="signature">The signature.</param>
        /// <returns>
        /// A value indicating whether the signature is valid.
        /// </returns>
        public override bool VerifySignature(byte[] signingPublicKey, byte[] data, byte[] signature)
        {
            var key = SignatureProvider.ImportPublicKey(signingPublicKey.ToBuffer(), CryptographicPublicKeyBlobType.Capi1PublicKey);

            return(CryptographicEngine.VerifySignature(key, data.ToBuffer(), signature.ToBuffer()));
        }
Esempio n. 19
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 async void RunSample_Click(object sender, RoutedEventArgs e)
        {
            Certificate selectedCertificate = null;
            string      verifyselection     = VerifyCert.SelectionBoxItem.ToString();

            //get the selected certificate
            if (CertificateList.SelectedIndex >= 0 && CertificateList.SelectedIndex < certList.Count)
            {
                selectedCertificate = certList[CertificateList.SelectedIndex];
            }

            if (selectedCertificate == null)
            {
                ViewCertText.Text = "Please select a certificate first.";
                return;
            }

            // a certificate was selected, do the desired operation
            if (verifyselection.Equals("Verify Certificate"))
            {
                //Build the chain
                var chain = await selectedCertificate.BuildChainAsync(null, null);

                //Validate the chain
                var result = chain.Validate();
                verifytext = "\n Verification Result :" + result.ToString();
            }
            else if (verifyselection.Equals("Sign/Verify using certificate key"))
            {
                // get private key
                CryptographicKey keyPair = await PersistedKeyProvider.OpenKeyPairFromCertificateAsync(selectedCertificate, HashAlgorithmNames.Sha1, CryptographicPadding.RsaPkcs1V15);

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

                try
                {
                    //sign the data by using the key
                    IBuffer Signed  = CryptographicEngine.Sign(keyPair, Data);
                    bool    bresult = CryptographicEngine.VerifySignature(keyPair, Data, Signed);

                    if (bresult == true)
                    {
                        verifytext = "\n Verification Result : Successfully signed and verified signature";
                    }
                    else
                    {
                        verifytext = "\n Verification Result : Verify Signature Failed";
                    }
                }
                catch (Exception exp)
                {
                    verifytext = "\n Verification Failed. Exception Occurred :" + exp.Message;
                }
            }
            else if (verifyselection.Equals("Sign/Verify using CMS based format"))
            {
                IInputStream pdfInputstream;
                InMemoryRandomAccessStream originalData = new InMemoryRandomAccessStream();
                //Populate the new memory stream
                pdfInputstream = originalData.GetInputStreamAt(0);
                CmsSignerInfo signer = new CmsSignerInfo();
                signer.Certificate       = selectedCertificate;
                signer.HashAlgorithmName = HashAlgorithmNames.Sha1;
                IList <CmsSignerInfo> signers = new List <CmsSignerInfo>();

                signers.Add(signer);
                try
                {
                    IBuffer signature = await CmsDetachedSignature.GenerateSignatureAsync(pdfInputstream, signers, null);

                    CmsDetachedSignature cmsSignedData = new CmsDetachedSignature(signature);
                    pdfInputstream = originalData.GetInputStreamAt(0);
                    SignatureValidationResult validationResult = await cmsSignedData.VerifySignatureAsync(pdfInputstream);

                    if (SignatureValidationResult.Success == validationResult)
                    {
                        verifytext = "\n Verification Result : Successfully signed and verified Signature";
                    }
                    else
                    {
                        verifytext = "\n Verification Result : Verify Signature using CMS based format Failed";
                    }
                }
                catch (Exception exp)
                {
                    verifytext = "\n Verification Failed. Exception Occurred :" + exp.Message;
                }
            }
            else if (verifyselection.Equals("Get certificate and show details"))
            {
                DisplayCertificate(selectedCertificate);
            }

            ViewCertText.Text += verifytext;
            verifytext         = string.Empty;
        }
Esempio n. 20
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)
        {
            String algName = AlgorithmNames.SelectionBoxItem.ToString();
            UInt32 KeySize = UInt32.Parse(KeySizes.SelectionBoxItem.ToString());

            Scenario8Text.Text = "";

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

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

            Scenario8Text.Text += "*** Sample Signature Algorithm\n";
            Scenario8Text.Text += "    Algorithm Name: " + Algorithm.AlgorithmName + "\n";
            Scenario8Text.Text += "    Key Size: " + KeySize + "\n";

            // Generate a key pair.
            try
            {
                keyPair = Algorithm.CreateKeyPair(KeySize);
            }
            catch (ArgumentException ex)
            {
                Scenario8Text.Text += ex.Message + "\n";
                Scenario8Text.Text += "An invalid key size was specified for the given algorithm.";
                return;
            }
            // Sign the data by using the generated key.
            IBuffer Signature = CryptographicEngine.Sign(keyPair, Data);

            Scenario8Text.Text += "    Data was successfully signed.\n";

            // Export the public key.
            blobOfPublicKey     = keyPair.ExportPublicKey();
            blobOfKeyPair       = keyPair.Export();
            Scenario8Text.Text += "    Key pair was successfully exported.\n";

            // Import the public key.
            CryptographicKey keyPublic = Algorithm.ImportPublicKey(blobOfPublicKey);

            // Check the key size.
            if (keyPublic.KeySize != keyPair.KeySize)
            {
                Scenario8Text.Text += "ImportPublicKey failed!  The imported key's size did not match the original's!";
                return;
            }
            Scenario8Text.Text += "    Public key was successfully imported.\n";

            // Import the key pair.
            keyPair = Algorithm.ImportKeyPair(blobOfKeyPair);

            // Check the key size.
            if (keyPublic.KeySize != keyPair.KeySize)
            {
                Scenario8Text.Text += "ImportKeyPair failed!  The imported key's size did not match the original's!";
                return;
            }
            Scenario8Text.Text += "    Key pair was successfully imported.\n";

            // Verify the signature by using the public key.
            if (!CryptographicEngine.VerifySignature(keyPublic, Data, Signature))
            {
                Scenario8Text.Text += "Signature verification failed!";
                return;
            }
            Scenario8Text.Text += "    Signature was successfully verified.\n";
        }