public static bool VerifyCryptoExceptionOnLoad(string xml, bool loadXmlThrows)
        {
            var xmlDoc = new XmlDocument();

            xmlDoc.PreserveWhitespace = true;
            xmlDoc.LoadXml(xml);

            var signatureNode = (XmlElement)xmlDoc.GetElementsByTagName("Signature", XmlNameSpace.Url[NS.XmlDsigNamespaceUrl])[0];

            SignatureChecker signedXml = new SignatureChecker(xmlDoc);

            if (loadXmlThrows)
            {
                Assert.Throws <System.Security.Cryptography.CryptographicException>(() => signedXml.LoadXml(signatureNode));
            }
            else
            {
                signedXml.LoadXml(signatureNode);
            }

            if (!loadXmlThrows)
            {
                bool checkSigResult = signedXml.CheckSignature();
                return(checkSigResult);
            }
            return(false);
        }
Пример #2
0
 public WeChatController(SignatureChecker signatureChecker,
                         IHttpClientFactory httpClientFactory,
                         IJsTicketAccessor jsTicketAccessor,
                         ISignatureGenerator signatureGenerator,
                         IWeChatOfficialOptionsResolver optionsResolver)
 {
     _signatureChecker   = signatureChecker;
     _httpClientFactory  = httpClientFactory;
     _jsTicketAccessor   = jsTicketAccessor;
     _signatureGenerator = signatureGenerator;
     _optionsResolver    = optionsResolver;
 }
Пример #3
0
        private static bool VerifyXml(string signedXmlText, RsaKeyParameters key)
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.PreserveWhitespace = true;
            xmlDoc.LoadXml(signedXmlText);

            SignatureChecker signedXml = new SignatureChecker(xmlDoc);
            var signatureNode          = (XmlElement)xmlDoc.GetElementsByTagName("Signature")[0];

            signedXml.LoadXml(signatureNode);
            return(signedXml.CheckSignature(key));
        }
 public WeChatController(SignatureChecker signatureChecker,
                         IOptions <AbpWeChatOfficialOptions> officialOptions,
                         IHttpClientFactory httpClientFactory,
                         IJsTicketAccessor jsTicketAccessor,
                         ISignatureGenerator signatureGenerator,
                         IHttpContextAccessor httpContextAccessor)
 {
     _signatureChecker    = signatureChecker;
     _httpClientFactory   = httpClientFactory;
     _jsTicketAccessor    = jsTicketAccessor;
     _signatureGenerator  = signatureGenerator;
     _httpContextAccessor = httpContextAccessor;
     _officialOptions     = officialOptions.Value;
 }
        private static bool VerifyXml(string signedXmlText, X509Certificate certificate)
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.PreserveWhitespace = true;
            xmlDoc.LoadXml(signedXmlText);

            SignatureChecker signedXml = new SignatureChecker(xmlDoc);
            var signatureNode          = (XmlElement)xmlDoc.GetElementsByTagName("Signature")[0];

            signedXml.LoadXml(signatureNode);

            return(signedXml.CheckSignature(certificate, verifySignatureOnly: true));
        }
Пример #6
0
        public static void CheckSignature(MethodInfo mi, Type returnType, params Type[] parameters)
        {
            if (mi == null)
            {
                throw new ArgumentNullException("mi");
            }
            if (returnType == null)
            {
                throw new ArgumentNullException("returnType");
            }

            SignatureChecker checker = new SignatureChecker(returnType, parameters);

            checker.Check(mi);
        }
        public UpdateDownloadForm(Release release)
        {
            InitializeComponent();
            Icon = updateIcon;
            Text = release.Name;
            LocalizeForm();
            Focus();

            changeLog.SetChangelog(release.Changelog);
            _redirectLinks = true;
            downloadProgress.DisplayStyle = TextProgressBar.ProgressBarDisplayText.Both;
            downloadProgress.CustomText   = release.Asset.name;

            _releaseFile = new WebFile(new Uri(release.Asset.browser_download_url));
            _releaseFileOnDownloadProgressChanged = (sender, args) =>
            {
                if (downloadProgress.IsDisposed)
                {
                    return;
                }
                downloadProgress.Invoke(new Action(() => { downloadProgress.Value = args.ProgressPercentage; }));
            };
            _releaseFile.DownloadProgressChanged += _releaseFileOnDownloadProgressChanged;
            _releaseFile.DownloadFailed          += (sender, @event) =>
            {
                Log.Error(@event.Exception, "Couldn't download the Release ");
                MessageBox.Show(@event.Exception.Message,
                                UpdateDownloadStrings.downloadFailed,
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            };
            _releaseFile.Downloaded += (sender, args) =>
            {
                if (!SignatureChecker.IsValid(_releaseFile.FilePath))
                {
                    Log.Error("Wrong signature for the release");
                    MessageBox.Show(UpdateDownloadStrings.notSigned,
                                    UpdateDownloadStrings.notSignedTitle,
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                installButton.Invoke(new Action(() =>
                {
                    installButton.Enabled    = true;
                    downloadProgress.Enabled = false;
                }));
            };
            _releaseFile.DownloadFile();
        }
Пример #8
0
        public static void TestDummySignatureAlgorithm()
        {
            string objectToConstruct = typeof(DummyClass).AssemblyQualifiedName;
            string xml = $@"<?xml version=""1.0"" encoding=""UTF-8""?>
            <a><b xmlns:ns1=""http://www.contoso.com/"">X<Signature xmlns=""http://www.w3.org/2000/09/xmldsig#""><SignedInfo><CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315""/><SignatureMethod Algorithm=""{objectToConstruct}""/><Reference URI=""""><Transforms><Transform Algorithm=""http://www.w3.org/2000/09/xmldsig#enveloped-signature""/><Transform Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-20010315""/></Transforms><DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1""/><DigestValue>ZVZLYkc1BAx+YtaqeYlxanb2cGI=</DigestValue></Reference></SignedInfo><SignatureValue>Kx8xs0of766gimu5girTqiTR5xoiWjN4XMx8uzDDhG70bIqpSzlhh6IA3iI54R5mpqCCPWrJJp85ps4jpQk8RGHe4KMejstbY6YXCfs7LtRPzkNzcoZB3vDbr3ijUSrbMk+0wTaZeyeYs8Z6cOicDIVN6bN6yC/Se5fbzTTCSmg=</SignatureValue><KeyInfo><KeyValue><RSAKeyValue><Modulus>ww2w+NbXwY/GRBZfFcXqrAM2X+P1NQoU+QEvgLO1izMTB8kvx1i/bodBvHTrKMwAMGEO4kVATA1f1Vf5/lVnbqiCLMJPVRZU6rWKjOGD28T/VRaIGywTV+mC0HvMbe4DlEd3dBwJZLIMUNvOPsj5Ua+l9IS4EoszFNAg6F5Lsyk=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue></KeyValue></KeyInfo></Signature></b></a>";

            var xmlDoc = new XmlDocument();

            xmlDoc.PreserveWhitespace = true;
            xmlDoc.LoadXml(xml);

            var signatureNode = (XmlElement)xmlDoc.GetElementsByTagName("Signature", XmlNameSpace.Url[NS.XmlDsigNamespaceUrl])[0];

            SignatureChecker signedXml = new SignatureChecker(xmlDoc);

            signedXml.LoadXml(signatureNode);
            Assert.Throws <System.Security.Cryptography.CryptographicException>(() => signedXml.CheckSignature());
        }
Пример #9
0
        public async void CanMatchSignatures()
        {
            await using var tempFile = new TempFile();

            var sig = new byte[] { 0x00, 0x01, 0x00, 0x00, 0x00 };

            await tempFile.Path.WriteAllBytesAsync(sig);

            var list = new List <Definitions.FileType>
            {
                Definitions.FileType.TTF, Definitions.FileType.ABA, Definitions.FileType.ACCDB
            };

            var checker = new SignatureChecker(list.ToArray());

            var res = await checker.MatchesAsync(tempFile.Path);

            Assert.NotNull(res);
            Assert.Equal(Definitions.FileType.TTF, res);
        }
Пример #10
0
 public LoginAppService(
     LoginService loginService,
     ACodeService aCodeService,
     SignatureChecker signatureChecker,
     SignInManager <IdentityUser> signInManager,
     IDataFilter dataFilter,
     IConfiguration configuration,
     IHttpClientFactory httpClientFactory,
     IUserInfoRepository userInfoRepository,
     IJsonSerializer jsonSerializer,
     IWeChatMiniProgramAsyncLocal weChatMiniProgramAsyncLocal,
     IMiniProgramUserRepository miniProgramUserRepository,
     IMiniProgramLoginNewUserCreator miniProgramLoginNewUserCreator,
     IMiniProgramLoginProviderProvider miniProgramLoginProviderProvider,
     IDistributedCache <MiniProgramPcLoginAuthorizationCacheItem> pcLoginAuthorizationCache,
     IDistributedCache <MiniProgramPcLoginUserLimitCacheItem> pcLoginUserLimitCache,
     IOptions <IdentityOptions> identityOptions,
     IdentityUserManager identityUserManager,
     IMiniProgramRepository miniProgramRepository)
 {
     _loginService                     = loginService;
     _aCodeService                     = aCodeService;
     _signatureChecker                 = signatureChecker;
     _signInManager                    = signInManager;
     _dataFilter                       = dataFilter;
     _configuration                    = configuration;
     _httpClientFactory                = httpClientFactory;
     _userInfoRepository               = userInfoRepository;
     _jsonSerializer                   = jsonSerializer;
     _weChatMiniProgramAsyncLocal      = weChatMiniProgramAsyncLocal;
     _miniProgramUserRepository        = miniProgramUserRepository;
     _miniProgramLoginNewUserCreator   = miniProgramLoginNewUserCreator;
     _miniProgramLoginProviderProvider = miniProgramLoginProviderProvider;
     _pcLoginAuthorizationCache        = pcLoginAuthorizationCache;
     _pcLoginUserLimitCache            = pcLoginUserLimitCache;
     _identityOptions                  = identityOptions;
     _identityUserManager              = identityUserManager;
     _miniProgramRepository            = miniProgramRepository;
 }
Пример #11
0
        /// <summary>
        /// Converts a secure string back to the object tree it represents, using
        /// a custom <see cref="Deserializer"/> and <see cref="SignatureChecker"/>.
        /// </summary>
        /// <param name="secureString">the secure string to be converted back to an
        /// object tree.</param>
        /// <param name="encryptionKey">the key to use to decrypt the ciphertext</param>
        /// <param name="validationKey">ignored</param>
        /// <param name="encryptionAlgorithm">the name of the encryption algorithm to use, null means use default</param>
        /// <param name="validationAlgorithm">the name of the signing algorithm to use, null means use default</param>
        /// <param name="deserializer">a <see cref="Deserializer"/> delegate from the
        /// root object of the object tree that can recreate the object tree from a
        /// <see cref="Stream"/> of serialized bytes.</param>
        /// <param name="sigChecker">a <see cref="SignatureChecker"/> delegate that
        /// compares an actual signature to the expected signature, throwin an exception
        /// if they don't match.</param>
        /// <remarks>The encryption key and algorithms must have
        /// the same values as they did when <see cref="Protect(Serializer, byte[], byte[])"/> was called or
        /// an exception will occur.</remarks>
        public static void Unprotect(string secureString, byte[] encryptionKey, byte[] unused, string encryptionAlgorithm, string validationAlgorithm, Deserializer deserializer, SignatureChecker sigChecker)
        {
            byte[]       secureBytes  = Convert.FromBase64String(secureString);
            MemoryStream secureStream = new MemoryStream(secureBytes);
            BinaryReader binaryReader = new BinaryReader(secureStream);

            byte[] actualHash = binaryReader.ReadBytes(binaryReader.ReadByte());
            byte[] iv         = binaryReader.ReadBytes(binaryReader.ReadByte());
            byte[] cipherText = binaryReader.ReadBytes((int)(secureStream.Length - secureStream.Position));

            // Verify the hash
            HashAlgorithm hashAlgorithm
                = validationAlgorithm != null
                ? HashAlgorithm.Create(validationAlgorithm)
                : HashAlgorithm.Create();

            byte[] expectedHash = hashAlgorithm.ComputeHash(cipherText);
            sigChecker(actualHash, expectedHash);

            // Decrypt the ciphertext
            MemoryStream       cipherTextStream = new MemoryStream(cipherText);
            SymmetricAlgorithm cipher
                = encryptionAlgorithm != null
                ? SymmetricAlgorithm.Create(encryptionAlgorithm)
                : SymmetricAlgorithm.Create();

            cipher.Mode    = CipherMode.CBC;
            cipher.Padding = PaddingMode.PKCS7;
            cipher.Key     = encryptionKey;
            cipher.IV      = iv;
            CryptoStream cryptoStream = new CryptoStream(cipherTextStream, cipher.CreateDecryptor(), CryptoStreamMode.Read);

            try
            {
                deserializer(cryptoStream);
            }
            finally
            {
                cryptoStream.Close();
            }
        }
Пример #12
0
 /// <summary>
 /// Converts a secure string back to the object tree it represents, using
 /// a custom <see cref="Deserializer"/> and <see cref="SignatureChecker"/>.
 /// </summary>
 /// <param name="secureString">the secure string to be converted back to an
 /// object tree.</param>
 /// <param name="encryptionKey">the key to use to decrypt the ciphertext</param>
 /// <param name="validationKey">the key to use to verify the signature</param>
 /// <param name="deserializer">a <see cref="Deserializer"/> delegate from the
 /// root object of the object tree that can recreate the object tree from a
 /// <see cref="Stream"/> of serialized bytes.</param>
 /// <param name="sigChecker">a <see cref="SignatureChecker"/> delegate that
 /// compares an actual signature to the expected signature, throwin an exception
 /// if they don't match.</param>
 /// <remarks>The encryption and validation keys must have
 /// the same values as they did when <see cref="Protect(Serializer, byte[], byte[])"/> was called or
 /// an exception will occur.</remarks>
 public static void Unprotect(string secureString, byte[] encryptionKey, byte[] validationKey, Deserializer deserializer, SignatureChecker sigChecker)
 {
     Unprotect(secureString, encryptionKey, validationKey, null, null, deserializer, sigChecker);
 }
Пример #13
0
        public void DownloadRelease(Release release)
        {
            changeLog.SetChangelog(release.Changelog);
            Name = release.Name;
            downloadProgress.CustomText = release.Asset.name;
            downloadProgress.Value      = 0;
            installButton.Enabled       = false;
            downloadProgress.Enabled    = true;

            _releaseFile = new WebFile(new Uri(release.Asset.browser_download_url));

            _releaseFile.DownloadProgress += (sender, progress) =>
            {
                if (downloadProgress.IsDisposed)
                {
                    return;
                }

                if (downloadProgress.InvokeRequired)
                {
                    downloadProgress.BeginInvoke(new Action(() => { downloadProgress.Value = (int)Math.Ceiling(progress.Percentage); }));
                }
                else
                {
                    downloadProgress.Value = (int)Math.Ceiling(progress.Percentage);
                }
            };
            _releaseFile.DownloadFailed += (sender, @event) =>
            {
                Log.Error(@event.Exception, "Couldn't download the Release ");
                MessageBox.Show(@event.Exception.Message,
                                UpdateDownloadStrings.downloadFailed,
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            };
            _releaseFile.Downloaded += (sender, args) =>
            {
                if (!SignatureChecker.IsValid(_releaseFile.FilePath))
                {
                    Log.Error("Wrong signature for the release");
                    MessageBox.Show(UpdateDownloadStrings.notSigned,
                                    UpdateDownloadStrings.notSignedTitle,
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (installButton.InvokeRequired)
                {
                    installButton.BeginInvoke(new Action(() =>
                    {
                        installButton.Enabled    = true;
                        downloadProgress.Enabled = false;
                    }));
                }
                else
                {
                    installButton.Enabled    = true;
                    downloadProgress.Enabled = false;
                }
            };
            _releaseFile.DownloadFile();
            ShowDialog();
        }
Пример #14
0
 public LtiController(IConfiguration config)
 {
     signatureChecker = new SignatureChecker(config["LtiKey"]);
 }
Пример #15
0
        /// <summary>
        /// Converts a secure string back to the object tree it represents, using
        /// a custom <see cref="Deserializer"/> and <see cref="SignatureChecker"/>.
        /// </summary>
        /// <param name="secureString">the secure string to be converted back to an
        /// object tree.</param>
        /// <param name="encryptionKey">the key to use to decrypt the ciphertext</param>
        /// <param name="validationKey">the key to use to verify the signature</param>
        /// <param name="deserializer">a <see cref="Deserializer"/> delegate from the
        /// root object of the object tree that can recreate the object tree from a
        /// <see cref="Stream"/> of serialized bytes.</param>
        /// <param name="sigChecker">a <see cref="SignatureChecker"/> delegate that
        /// compares an actual signature to the expected signature, throwin an exception
        /// if they don't match.</param>
        /// <remarks>The encryption and validation keys must have
        /// the same values as they did when <see cref="Protect(Serializer, byte[], byte[])"/> was called or
        /// an exception will occur.</remarks>
        public static void Unprotect(string secureString, byte[] encryptionKey, byte[] validationKey, Deserializer deserializer, SignatureChecker sigChecker)
        {
            byte[] secureBytes = Convert.FromBase64String(secureString);
            MemoryStream secureStream = new MemoryStream(secureBytes);
            BinaryReader binaryReader = new BinaryReader(secureStream);
            byte[] actualHash = binaryReader.ReadBytes(binaryReader.ReadByte());
            byte[] iv = binaryReader.ReadBytes(binaryReader.ReadByte());
            byte[] cipherText = binaryReader.ReadBytes((int)(secureStream.Length - secureStream.Position));

            // Verify the hash
            KeyedHashAlgorithm macAlgorithm = KeyedHashAlgorithm.Create();
            macAlgorithm.Key = validationKey;
            byte[] expectedHash = macAlgorithm.ComputeHash(cipherText);
            sigChecker(actualHash, expectedHash);

            // Decrypt the ciphertext
            MemoryStream cipherTextStream = new MemoryStream(cipherText);
            SymmetricAlgorithm cipher = SymmetricAlgorithm.Create();
            cipher.Mode = CipherMode.CBC;
            cipher.Padding = PaddingMode.PKCS7;
            cipher.Key = encryptionKey;
            cipher.IV = iv;
            CryptoStream cryptoStream = new CryptoStream(cipherTextStream, cipher.CreateDecryptor(), CryptoStreamMode.Read);
            try
            {
                deserializer(cryptoStream);
            }
            finally
            {
                cryptoStream.Close();
            }
        }