/// <summary> /// ��ע����Ϣ���ݲ��÷ǶԳƼ��ܵķ�ʽ���� /// </summary> /// <param name="originalString">δ���ܵ��ı����������</param> /// <param name="encrytedString">���ܺ���ı�����ע�����к�</param> /// <returns>�����֤�ɹ�����True������ΪFalse</returns> public static bool Validate(string originalString, string encrytedString) { bool bPassed = false; using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { try { rsa.FromXmlString(UIConstants.PublicKey); //��Կ RSAPKCS1SignatureDeformatter formatter = new RSAPKCS1SignatureDeformatter(rsa); formatter.SetHashAlgorithm("SHA1"); byte[] key = Convert.FromBase64String(encrytedString); //��֤ SHA1Managed sha = new SHA1Managed(); byte[] name = sha.ComputeHash(ASCIIEncoding.ASCII.GetBytes(originalString)); if (formatter.VerifySignature(name, key)) { bPassed = true; } } catch { } } return bPassed; }
public void RSAConstructors () { RSAPKCS1SignatureDeformatter fmt; fmt = new RSAPKCS1SignatureDeformatter (); fmt = new RSAPKCS1SignatureDeformatter (rsa); }
public static bool Verify(Stream input, Stream output, string publicKey) { // ファイルから情報の抽出 var buffer = new byte[64]; if (input.Read(buffer, 0, 64) < 64) throw new Exception("File is corrupted.(KSIG: Magic Not Found)"); var magicstr = Encoding.UTF8.GetString(buffer).Split(new[] { ":" }, StringSplitOptions.None); if (magicstr.Length < 2) throw new Exception("File is corrupted.(KSIG: Invalid Magic Length)"); if (magicstr[0] != MagicStr) throw new Exception("File is corrupted.(KSIG: Invalid Magic String)"); var siglen = int.Parse(magicstr[1]); var sigbuf = new byte[siglen]; if (input.Read(sigbuf, 0, siglen) < siglen) throw new Exception("File is corrupted.(KSIG: Invalid Signature)"); var data = ReadAllBytes(input); using (var sha = new SHA256Managed()) using (var rsa = new RSACryptoServiceProvider()) { // Compute hash var hash = sha.ComputeHash(data); // RSA Initialize rsa.FromXmlString(publicKey); // deformat var deformatter = new RSAPKCS1SignatureDeformatter(rsa); deformatter.SetHashAlgorithm("SHA256"); if (!deformatter.VerifySignature(hash, sigbuf)) return false; } output.Write(data, 0, data.Length); return true; }
/// <summary> /// 引用证书非对称加/解密RSA-公钥验签【OriginalString:原文;SignatureString:签名字符;pubkey_path:证书路径;CertificatePW:证书密码;SignType:签名摘要类型(1:MD5,2:SHA1)】 /// </summary> public static bool CerRSAVerifySignature(string OriginalString, string SignatureString, string pubkey_path, string CertificatePW, int SignType) { byte[] OriginalByte = System.Text.Encoding.UTF8.GetBytes(OriginalString); byte[] SignatureByte = Convert.FromBase64String(SignatureString); X509Certificate2 x509_Cer1 = new X509Certificate2(pubkey_path, CertificatePW); RSACryptoServiceProvider rsapub = (RSACryptoServiceProvider)x509_Cer1.PublicKey.Key; rsapub.ImportCspBlob(rsapub.ExportCspBlob(false)); RSAPKCS1SignatureDeformatter f = new RSAPKCS1SignatureDeformatter(rsapub); byte[] HashData; switch (SignType) { case 1: f.SetHashAlgorithm("MD5");//摘要算法MD5 MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); HashData = md5.ComputeHash(OriginalByte); break; default: f.SetHashAlgorithm("SHA1");//摘要算法SHA1 SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider(); HashData = sha.ComputeHash(OriginalByte); break; } if (f.VerifySignature(HashData, SignatureByte)) { return true; } else { return false; } }
public static bool CompareCode(string regcode) { if (regcode == null || regcode == "") { return false; } try { string toolcode = GetDiskVolumeSerialNumber() + GetCpuSerialNumber(); string pubkey = "<RSAKeyValue><Modulus>xe3teTUwLgmbiwFJwWEQnshhKxgcasglGsfNVFTk0hdqKc9i7wb+gG7HOdPZLh65QyBcFfzdlrawwVkiPEL5kNTX1q3JW5J49mTVZqWd3w49reaLd8StHRYJdyGAL4ZovBhSTThETi+zYvgQ5SvCGkM6/xXOz+lkMaEgeFcjQQs=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"; string prikey = "<RSAKeyValue><Modulus>xe3teTUwLgmbiwFJwWEQnshhKxgcasglGsfNVFTk0hdqKc9i7wb+gG7HOdPZLh65QyBcFfzdlrawwVkiPEL5kNTX1q3JW5J49mTVZqWd3w49reaLd8StHRYJdyGAL4ZovBhSTThETi+zYvgQ5SvCGkM6/xXOz+lkMaEgeFcjQQs=</Modulus><Exponent>AQAB</Exponent><P>5flMAd7IrUTx92yomBdJBPDzp1Kclpaw4uXB1Ht+YXqwLW/9icI6mcv7d2O0kuVLSWj8DPZJol9V8AtvHkC3oQ==</P><Q>3FRA9UWcFrVPvGR5bewcL7YqkCMZlybV/t6nCH+gyMfbEvgk+p04F+j8WiHDykWj+BahjScjwyF5SGADbrfJKw==</Q><DP>b4WOU1XbERNfF3JM67xW/5ttPNX185zN2Ko8bbMZXWImr1IgrD5RNqXRo1rphVbGRKoxmIOSv7flr8uLrisKIQ==</DP><DQ>otSZlSq2qomgvgg7PaOLSS+F0TQ/i1emO0/tffhkqT4ah7BgE97xP6puJWZivjAteAGxrxHH+kPY0EY1AzRMNQ==</DQ><InverseQ>Sxyz0fEf5m7GrzAngLDRP/i+QDikJFfM6qPyr3Ub6Y5RRsFbeOWY1tX3jmV31zv4cgJ6donH7W2dSBPi67sSsw==</InverseQ><D>nVqofsIgSZltxTcC8fA/DFz1kxMaFHKFvSK3RKIxQC1JQ3ASkUEYN/baAElB0f6u/oTNcNWVPOqE31IDe7ErQelVc4D26RgFd5V7dSsF3nVz00s4mq1qUBnCBLPIrdb0rcQZ8FUQTsd96qW8Foave4tm8vspbM65iVUBBVdSYYE=</D></RSAKeyValue>"; using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(pubkey); RSAPKCS1SignatureDeformatter f = new RSAPKCS1SignatureDeformatter(rsa); f.SetHashAlgorithm("SHA1"); SHA1Managed sha = new SHA1Managed(); byte[] name = sha.ComputeHash(ASCIIEncoding.ASCII.GetBytes(toolcode)); byte[] key = Convert.FromBase64String(regcode); return f.VerifySignature(name, key); } } catch { return false; } }
public DigitalSignatureVerificationResult VerifySignature(DigitalSignatureVerificationArguments arguments) { var res = new DigitalSignatureVerificationResult(); try { var rsaProviderSender = new RSACryptoServiceProvider(); rsaProviderSender.FromXmlString(arguments.PublicKeyForSignatureVerification.ToString()); var deformatter = new RSAPKCS1SignatureDeformatter(rsaProviderSender); deformatter.SetHashAlgorithm(_hashingService.HashAlgorithmCode()); var hashResult = _hashingService.Hash(arguments.CipherText); res.SignaturesMatch = deformatter.VerifySignature(hashResult.HashedBytes, arguments.Signature); if (res.SignaturesMatch) { var rsaProviderReceiver = new RSACryptoServiceProvider(); rsaProviderReceiver.FromXmlString(arguments.FullKeyForDecryption.ToString()); var decryptedBytes = rsaProviderReceiver.Decrypt(Convert.FromBase64String(arguments.CipherText), false); res.DecodedText = Encoding.UTF8.GetString(decryptedBytes); } res.Success = true; } catch (Exception ex) { res.ExceptionMessage = ex.Message; } return res; }
public bool verify(byte[] sig) { m_cs.Close(); RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSA.ImportParameters(m_RSAKeyInfo); RSAPKCS1SignatureDeformatter RSADeformatter = new RSAPKCS1SignatureDeformatter(RSA); RSADeformatter.SetHashAlgorithm("SHA1"); long i = 0; long j = 0; byte[] tmp; if (sig[0] == 0 && sig[1] == 0 && sig[2] == 0) { long i1 = (sig[i++] << 24) & 0xff000000; long i2 = (sig[i++] << 16) & 0x00ff0000; long i3 = (sig[i++] << 8) & 0x0000ff00; long i4 = (sig[i++]) & 0x000000ff; j = i1 | i2 | i3 | i4; i += j; i1 = (sig[i++] << 24) & 0xff000000; i2 = (sig[i++] << 16) & 0x00ff0000; i3 = (sig[i++] << 8) & 0x0000ff00; i4 = (sig[i++]) & 0x000000ff; j = i1 | i2 | i3 | i4; tmp = new byte[j]; Array.Copy(sig, i, tmp, 0, j); sig = tmp; } return RSADeformatter.VerifySignature(m_sha1, sig); }
public static bool ValidatePathWithEncodedRSAPKCS1SignatureAndPublicRSAKey(string path, string base64Signature, string publicKey) { try { byte[] signature = Convert.FromBase64String(base64Signature); byte[] data = File.ReadAllBytes(path); SHA256CryptoServiceProvider cryptoTransformSHA256 = new SHA256CryptoServiceProvider(); byte[] sha256Hash = cryptoTransformSHA256.ComputeHash(data); string cleanKey = ""; string[] lines = publicKey.Split(new char[] {'\n', '\r'}); foreach (string line in lines) { cleanKey += line.Trim(); } byte[] publicKeyData = Convert.FromBase64String(cleanKey); RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); provider.ImportCspBlob(publicKeyData); RSAPKCS1SignatureDeformatter formatter = new RSAPKCS1SignatureDeformatter(provider); formatter.SetHashAlgorithm("SHA256"); return formatter.VerifySignature(sha256Hash, signature); } catch (Exception ex) { Console.WriteLine(ex.Message); return false; } }
public override AsymmetricSignatureDeformatter CreateDeformatter(AsymmetricAlgorithm key) { if (key == null) throw new ArgumentNullException(nameof(key)); var d = new RSAPKCS1SignatureDeformatter(key); d.SetHashAlgorithm(SHA_512); return d; }
public void RSAConstructors () { RSAPKCS1SignatureDeformatter fmt; fmt = new RSAPKCS1SignatureDeformatter (); AssertNotNull ("RSAPKCS1SignatureDeformatter()", fmt); fmt = new RSAPKCS1SignatureDeformatter (rsa); AssertNotNull ("RSAPKCS1SignatureDeformatter(rsa)", fmt); }
public override AsymmetricSignatureDeformatter CreateDeformatter(AsymmetricAlgorithm key) { if (key == null) throw new ArgumentNullException("key"); RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(key); deformatter.SetHashAlgorithm("SHA256"); return deformatter; }
public bool VerifySignature(byte[] hash, byte[] signedhash) { RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSAParameters RSAKeyInfo = new RSAParameters(); RSAKeyInfo.Modulus = m_public.Modulus; RSAKeyInfo.Exponent = m_public.Exponent; RSA.ImportParameters(RSAKeyInfo); RSAPKCS1SignatureDeformatter RSADeformatter = new RSAPKCS1SignatureDeformatter(RSA); RSADeformatter.SetHashAlgorithm("MD5"); return RSADeformatter.VerifySignature(hash, signedhash); }
/// <summary> /// Create a deformatter /// </summary> /// <param name="key">Key</param> /// <returns>Deformatter</returns> public override AsymmetricSignatureDeformatter CreateDeformatter(AsymmetricAlgorithm key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } var df = new RSAPKCS1SignatureDeformatter(key); df.SetHashAlgorithm(typeof(SHA256Managed).FullName); return df; }
public bool VerifySignature(byte[] hashOfDataToSign, byte[] signature) { using (var rsa = new RSACryptoServiceProvider(2048)) { rsa.ImportParameters(_publicKey); var rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa); rsaDeformatter.SetHashAlgorithm("SHA256"); return rsaDeformatter.VerifySignature(hashOfDataToSign, signature); } }
/// <summary> /// RSA验证 /// </summary> /// <param name="CypherText">签名后的Base64字符串</param> /// <param name="xmlString">密钥(至少含公钥)</param> /// <param name="PlainText">原始串</param> public static bool VerifyString(string CypherText, string xmlString, string PlainText) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(xmlString); RSAPKCS1SignatureDeformatter f = new RSAPKCS1SignatureDeformatter(rsa); f.SetHashAlgorithm("SHA1"); SHA1Managed sha = new SHA1Managed(); byte[] bText = System.Convert.FromBase64String(CypherText); byte[] bEnc = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(PlainText)); return f.VerifySignature(bEnc, bText); }
public override AsymmetricSignatureDeformatter CreateDeformatter(AsymmetricAlgorithm key) { if (key == null) { throw new Exception("Invalid key specified for RSAPKCS1SHA256SignatureDescription!"); } RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(key); deformatter.SetHashAlgorithm("SHA256"); return deformatter; }
/// <summary> /// デジタル署名を検証する /// </summary> /// <param name="message">署名の付いたメッセージ</param> /// <param name="signature">署名</param> /// <param name="publicKey">送信者の公開鍵</param> /// <returns>認証に成功した時はTrue。失敗した時はFalse。</returns> public static bool VerifyDigitalSignature(byte[] message, byte[] signature, string publicKey) { byte[] hashData = SHA256.Create().ComputeHash(message); using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(publicKey); RSAPKCS1SignatureDeformatter rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa); rsaDeformatter.SetHashAlgorithm("SHA256"); return rsaDeformatter.VerifySignature(hashData, signature); } }
public bool ValidateSignature(OAuthContext authContext, SigningContext signingContext) { if (signingContext.Algorithm == null) throw Error.AlgorithmPropertyNotSetOnSigningContext(); SHA1CryptoServiceProvider sha1 = GenerateHash(signingContext); var deformatter = new RSAPKCS1SignatureDeformatter(signingContext.Algorithm); deformatter.SetHashAlgorithm("MD5"); byte[] signature = Convert.FromBase64String(authContext.Signature); return deformatter.VerifySignature(sha1, signature); }
public bool Verify(byte[] signature, byte[] securedInput, object key) { using (var sha = HashAlgorithm) { var publicKey = Ensure.Type<AsymmetricAlgorithm>(key, "RsaUsingSha alg expects key to be of AsymmetricAlgorithm type."); byte[] hash = sha.ComputeHash(securedInput); var pkcs1 = new RSAPKCS1SignatureDeformatter(publicKey); pkcs1.SetHashAlgorithm(hashMethod); return pkcs1.VerifySignature(hash, signature); } }
static void Main(string[] args) { string pubKey = ConfigurationManager.AppSettings["pubKey"]; string priKey = ConfigurationManager.AppSettings["priKey"]; string input = ConfigurationManager.AppSettings["input"]; string user = ConfigurationManager.AppSettings["user"]; using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { SHA1Managed sha = new SHA1Managed(); rsa.FromXmlString(priKey); Console.WriteLine("begin to encode:"); RSAPKCS1SignatureFormatter signFormatter = new RSAPKCS1SignatureFormatter(rsa); signFormatter.SetHashAlgorithm("SHA1"); byte[] source = System.Text.ASCIIEncoding.UTF8.GetBytes(input); byte[] result = sha.ComputeHash(source); byte[] b = signFormatter.CreateSignature(result); var signature = Convert.ToBase64String(b); string outputFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sn", input + ".key"); FileInfo fi = new FileInfo(outputFile); if (!fi.Directory.Exists) { fi.Directory.Create(); } StreamWriter sw = new StreamWriter(fi.OpenWrite(), Encoding.UTF8); sw.Write(signature); sw.Close(); Console.WriteLine(); Console.WriteLine(signature); using (RSACryptoServiceProvider rsa2 = new RSACryptoServiceProvider()) { rsa2.FromXmlString(pubKey); RSAPKCS1SignatureDeformatter decodeFormatter = new RSAPKCS1SignatureDeformatter(rsa2); decodeFormatter.SetHashAlgorithm("SHA1"); byte[] key = Convert.FromBase64String(signature); byte[] name = sha.ComputeHash(ASCIIEncoding.UTF8.GetBytes(input)); if (decodeFormatter.VerifySignature(name, key)) { Console.WriteLine("===========can be decoded"); } else { Console.WriteLine("===CANOT be decoded.................."); } } } }
public static bool Verify(byte[] publicKey, byte[] signature, Stream stream) { #if Windows try { using (var rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(Encoding.ASCII.GetString(publicKey)); var rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa); rsaDeformatter.SetHashAlgorithm("SHA256"); using (var Sha256 = SHA256.Create()) { return rsaDeformatter.VerifySignature(Sha256.ComputeHash(stream), signature); } } } catch (Exception) { return false; } #endif #if Unix lock (_lockObject) { try { using (var rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(Encoding.ASCII.GetString(publicKey)); var rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa); rsaDeformatter.SetHashAlgorithm("SHA256"); using (var Sha256 = SHA256.Create()) { return rsaDeformatter.VerifySignature(Sha256.ComputeHash(stream), signature); } } } catch (Exception) { return false; } } #endif }
public bool CheckSign() { var signMsgVal = GetSign(); byte[] bytes = System.Text.Encoding.UTF8.GetBytes(signMsgVal); byte[] SignatureByte = Convert.FromBase64String(signMsg); var publicKey = CoreHelper.CustomSetting.GetConfigKey("快钱WEB公钥文件"); X509Certificate2 cert = new X509Certificate2(publicKey, ""); RSACryptoServiceProvider rsapri = (RSACryptoServiceProvider)cert.PublicKey.Key; rsapri.ImportCspBlob(rsapri.ExportCspBlob(false)); RSAPKCS1SignatureDeformatter f = new RSAPKCS1SignatureDeformatter(rsapri); byte[] result; f.SetHashAlgorithm("SHA1"); SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider(); result = sha.ComputeHash(bytes); return f.VerifySignature(result, SignatureByte); }
public bool Validate(string EncyptedBase64Key) { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(pubkey); RSAPKCS1SignatureDeformatter f = new RSAPKCS1SignatureDeformatter(rsa); f.SetHashAlgorithm("SHA1"); byte[] key = Convert.FromBase64String(pubkey); SHA1Managed sha = new SHA1Managed(); byte[] name = sha.ComputeHash(ASCIIEncoding.ASCII.GetBytes(EncyptedBase64Key)); if (f.VerifySignature(name, key)) return true; else return false; } }
public void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext.HttpContext.User != null && (filterContext.HttpContext.User.Identity as ClaimsIdentity).Claims.Any()) { var currentUserClaim = (filterContext.HttpContext.User.Identity as ClaimsIdentity).Claims.FirstOrDefault(claim => claim.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"); if (currentUserClaim != null) { var currentUser = currentUserClaim.Value; if (currentUser != null) if (UserForLogOutDictionary.ContainsKey(currentUser)) { FederatedAuthentication.SessionAuthenticationModule.DeleteSessionTokenCookie(); filterContext.HttpContext.Response.Redirect(UrlHelper.GenerateContentUrl("~/", filterContext.HttpContext)); filterContext.HttpContext.Response.End(); string temp; UserForLogOutDictionary.TryRemove(currentUserClaim.Value, out temp); } } } var extendeduser = filterContext.HttpContext.Request.Form.Get("SAMLLogoutUser"); if (string.IsNullOrEmpty(extendeduser)) { return; } var user = extendeduser.Split(";".ToCharArray())[0]; var issuer = HttpUtility.UrlDecode(extendeduser.Split(";".ToCharArray())[1]); var signed = filterContext.HttpContext.Request.Form.Get("hash"); var cert = AuthServicesController.Options.IdentityProviders[new EntityId() { Id = issuer }]; RSAPKCS1SignatureDeformatter RSADeformatter = new RSAPKCS1SignatureDeformatter(cert.SigningKeys.First()); RSADeformatter.SetHashAlgorithm("SHA1"); SHA1Managed SHhash = new SHA1Managed(); if (RSADeformatter.VerifySignature( SHhash.ComputeHash(new UnicodeEncoding().GetBytes(HttpUtility.UrlEncode(extendeduser))), System.Convert.FromBase64String(signed)) ) { UserForLogOutDictionary[user] = "true"; return; } }
public static bool CheckCopyright() { XmlDocument document = HiCache.Get("Hishop_SiteLicense") as XmlDocument; HttpContext current = HttpContext.Current; if (document == null) { string path = null; if (current != null) { path = current.Request.MapPath("~/config/Hishop.lic"); } else { path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Hishop.lic"); } if (!File.Exists(path)) { return false; } document = new XmlDocument(); document.LoadXml(File.ReadAllText(path)); HiCache.Max("Hishop_SiteLicense", document, new CacheDependency(path)); } XmlNode node = document.DocumentElement.SelectSingleNode("//Host"); XmlNode node2 = document.DocumentElement.SelectSingleNode("//LicenseDate"); XmlNode node3 = document.DocumentElement.SelectSingleNode("//ExpiresDate"); XmlNode node4 = document.DocumentElement.SelectSingleNode("//Signature"); SiteSettings masterSettings = SettingsManager.GetMasterSettings(false); if (string.Compare(node.InnerText, masterSettings.SiteUrl, true, CultureInfo.InvariantCulture) != 0) { return false; } string s = string.Format(CultureInfo.InvariantCulture, "Host={0}&LicenseDate={1}&ExpiresDate={2}&Key={3}", new object[] { masterSettings.SiteUrl, node2.InnerText, node3.InnerText, masterSettings.CheckCode }); bool flag = false; using (RSACryptoServiceProvider provider = new RSACryptoServiceProvider()) { provider.FromXmlString(LicenseHelper.GetPublicKey()); RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(provider); deformatter.SetHashAlgorithm("SHA1"); byte[] rgbSignature = Convert.FromBase64String(node4.InnerText); byte[] rgbHash = new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(s)); flag = deformatter.VerifySignature(rgbHash, rgbSignature); } return (flag && (DateTime.Now < DateTime.Parse(node3.InnerText))); }
public bool Verify(byte[] signature, byte[] securedInput, object key) { #if NET40 using (var sha = HashAlgorithm) { var publicKey = Ensure.Type<AsymmetricAlgorithm>(key, "RsaUsingSha alg expects key to be of AsymmetricAlgorithm type."); byte[] hash = sha.ComputeHash(securedInput); var pkcs1 = new RSAPKCS1SignatureDeformatter(publicKey); pkcs1.SetHashAlgorithm(hashMethod); return pkcs1.VerifySignature(hash, signature); } #elif NETSTANDARD1_4 var publicKey = Ensure.Type<RSA>(key, "RsaUsingSha alg expects key to be of RSA type."); return publicKey.VerifyData(securedInput, signature, HashAlgorithm, RSASignaturePadding.Pkcs1); #endif }
static public bool CheckSignature(byte[] data, int offset, byte[] signedHash) { //Create a new instance of RSACryptoServiceProvider. var rsa = new RSACryptoServiceProvider(2048); //The hash to sign. HashAlgorithm ha = SHA256.Create(); var hash = ha.ComputeHash(data, offset, 0x100); //Create an RSAPKCS1SignatureDeformatter object and pass it the //RSACryptoServiceProvider to transfer the key information. var rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa); rsaDeformatter.SetHashAlgorithm("SHA256"); //Verify the hash and display the results to the console. return rsaDeformatter.VerifySignature(hash, signedHash); }
public static void Check(out bool isValid, out bool expired, out int siteQty) { siteQty = 0; isValid = false; expired = true; XmlDocument document = HiCache.Get("FileCache_CommercialLicenser") as XmlDocument; if (document == null) { string path = HttpContext.Current.Request.MapPath("/config/Certificates.cer"); if (!File.Exists(path)) { return; } document = new XmlDocument(); document.LoadXml(File.ReadAllText(path)); HiCache.Max("FileCache_CommercialLicenser", document, new CacheDependency(path)); } XmlNode node = document.DocumentElement.SelectSingleNode("//Host"); XmlNode node2 = document.DocumentElement.SelectSingleNode("//LicenseDate"); XmlNode node3 = document.DocumentElement.SelectSingleNode("//Expires"); XmlNode node4 = document.DocumentElement.SelectSingleNode("//SiteQty"); XmlNode node5 = document.DocumentElement.SelectSingleNode("//Signature"); if (string.Compare(node.InnerText, HttpContext.Current.Request.Url.Host, true, CultureInfo.InvariantCulture) == 0) { string s = string.Format(CultureInfo.InvariantCulture, "Host={0}&Expires={1}&SiteQty={2}&LicenseDate={3}", new object[] { HttpContext.Current.Request.Url.Host, node3.InnerText, node4.InnerText, node2.InnerText }); using (RSACryptoServiceProvider provider = new RSACryptoServiceProvider()) { provider.FromXmlString(LicenseHelper.GetPublicKey()); RSAPKCS1SignatureDeformatter deformatter = new RSAPKCS1SignatureDeformatter(provider); deformatter.SetHashAlgorithm("SHA1"); byte[] rgbSignature = Convert.FromBase64String(node5.InnerText); byte[] rgbHash = new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(s)); isValid = deformatter.VerifySignature(rgbHash, rgbSignature); } expired = DateTime.Now > DateTime.Parse(node3.InnerText); if (!(!isValid ? true : expired)) { int.TryParse(node4.InnerText, out siteQty); } } }
public static bool VerifySignature(string textToVerify, string signature, string XMLpublicKey) { RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSA.FromXmlString(XMLpublicKey); RSAPKCS1SignatureDeformatter RSADeformatter = new RSAPKCS1SignatureDeformatter(RSA); RSADeformatter.SetHashAlgorithm("SHA1"); SHA1Managed SHhashpub = new SHA1Managed(); if (RSADeformatter.VerifySignature( SHhashpub.ComputeHash(new UnicodeEncoding().GetBytes(textToVerify)), System.Convert.FromBase64String(signature)) ) { /// The signature is valid. return true; } else { /// The signature is not valid. return false; } }
public static bool VerifyLicense() { //The XML file that holds the public key, license key, and the Digital Signature XmlDocument licenseFile = new XmlDocument(); licenseFile.Load(Environment.CurrentDirectory + @"\licenseinfo.xml"); // The RSA public key RSAParameters RSAKeyInfo = new RSAParameters { Modulus = Convert.FromBase64String(licenseFile.DocumentElement.SelectSingleNode(@"/LicenseInfo/RSAKeyValue/Modulus").InnerText), Exponent = Convert.FromBase64String(licenseFile.DocumentElement.SelectSingleNode(@"/LicenseInfo/RSAKeyValue/Exponent").InnerText) }; RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSA.ImportParameters(RSAKeyInfo); // A deformatter to verify the digital signature against the license RSAPKCS1SignatureDeformatter rsaDeformatter = new RSAPKCS1SignatureDeformatter(RSA); rsaDeformatter.SetHashAlgorithm("SHA1"); // The hash to be verified against the signature byte[] hash = Encoding.ASCII.GetBytes(licenseFile.DocumentElement.SelectSingleNode(@"/LicenseInfo/KEY").InnerText); // The signature used to verify the hash byte[] signature = Convert.FromBase64String(licenseFile.DocumentElement.SelectSingleNode(@"/LicenseInfo/SignedKey").InnerText); string savedLicenseKey = licenseFile.DocumentElement.SelectSingleNode(@"/LicenseInfo/KEY").InnerText; string truncatedMachineName = savedLicenseKey.Substring(savedLicenseKey.LastIndexOf(@"/") + 5); // If license is not licensed to this computer if (Environment.MachineName.Substring(0, truncatedMachineName.Length) != truncatedMachineName) { return false; } // If the signature is valid, return true if (rsaDeformatter.VerifySignature(hash, signature)) { return true; } return false; }
/// <summary> /// RSA签名验证 /// </summary> /// <param name="strKeyPublic">公钥</param> /// <param name="HashbyteDeformatter">Hash描述</param> /// <param name="DeformatterData">签名后的结果</param> /// <returns></returns> public bool SignatureDeformatter(string strKeyPublic, byte[] HashbyteDeformatter, byte[] DeformatterData) { try { System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(strKeyPublic); System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA); //指定解密的时候HASH算法为MD5 RSADeformatter.SetHashAlgorithm("MD5"); if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData)) { return(true); } else { return(false); } } catch (Exception ex) { throw ex; } }
public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, string p_strDeformatterData) { byte[] DeformatterData; byte[] HashbyteDeformatter; HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter); System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPublic); System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA); //指定解密的时候HASH算法为MD5 RSADeformatter.SetHashAlgorithm("MD5"); DeformatterData = Convert.FromBase64String(p_strDeformatterData); if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData)) { return(true); } else { return(false); } }
/// <summary> /// RSA签名验证 /// </summary> /// <param name="strKeyPublic">公钥</param> /// <param name="strHashbyteDeformatter">Hash描述</param> /// <param name="strDeformatterData">签名后的结果</param> /// <returns></returns> public bool SignatureDeformatter(string strKeyPublic, string strHashbyteDeformatter, string strDeformatterData) { try { byte[] DeformatterData; byte[] HashbyteDeformatter; HashbyteDeformatter = Convert.FromBase64String(strHashbyteDeformatter); System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(strKeyPublic); System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA); //指定解密的时候HASH算法为MD5 RSADeformatter.SetHashAlgorithm("MD5"); DeformatterData = Convert.FromBase64String(strDeformatterData); if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData)) { return true; } else { return false; } } catch (Exception ex) { throw ex; } }
/// <summary> /// RSA加密解密及RSA签名和验证 /// </summary> public class RSA { #region RSA 加密解密 #region RSA 的密钥产生 /// <summary> /// RSA 的密钥产生 产生私钥 和公钥 /// </summary> /// <param name="xmlKeys"></param> /// <param name="xmlPublicKey"></param> public Tuple<string,string> generateKey() { System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); string xmlKeys = rsa.ToXmlString(true); string xmlPublicKey = rsa.ToXmlString(false); return Tuple.Create<string, string>(xmlKeys, xmlPublicKey); } #endregion #region RSA的加密函数 //############################################################################## //RSA 方式加密 //说明KEY必须是XML的行式,返回的是字符串 //在有一点需要说明!!该加密方式有 长度 限制的!! //############################################################################## //RSA的加密函数 string public string encrypt(string xmlPublicKey, string m_strEncryptString) { byte[] PlainTextBArray; byte[] CypherTextBArray; string Result; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(xmlPublicKey); PlainTextBArray = (new UnicodeEncoding()).GetBytes(m_strEncryptString); CypherTextBArray = rsa.Encrypt(PlainTextBArray, false); Result = Convert.ToBase64String(CypherTextBArray); return Result; } //RSA的加密函数 byte[] public string encrypt(string xmlPublicKey, byte[] EncryptString) { byte[] CypherTextBArray; string Result; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(xmlPublicKey); CypherTextBArray = rsa.Encrypt(EncryptString, false); Result = Convert.ToBase64String(CypherTextBArray); return Result; } #endregion #region RSA的解密函数 //RSA的解密函数 string public string decrypt(string xmlPrivateKey, string m_strDecryptString) { byte[] PlainTextBArray; byte[] DypherTextBArray; string Result; System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(xmlPrivateKey); PlainTextBArray = Convert.FromBase64String(m_strDecryptString); DypherTextBArray = rsa.Decrypt(PlainTextBArray, false); Result = (new UnicodeEncoding()).GetString(DypherTextBArray); return Result; } //RSA的解密函数 byte public string decrypt(string xmlPrivateKey, byte[] DecryptString) { byte[] DypherTextBArray; string Result; System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(xmlPrivateKey); DypherTextBArray = rsa.Decrypt(DecryptString, false); Result = (new UnicodeEncoding()).GetString(DypherTextBArray); return Result; } #endregion #endregion #region RSA数字签名 #region 获取Hash描述表 //获取Hash描述表 public bool GetHash(string m_strSource, ref byte[] HashData) { //从字符串中取得Hash描述 byte[] Buffer; System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5"); Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource); HashData = MD5.ComputeHash(Buffer); return true; } //获取Hash描述表 public bool GetHash(string m_strSource, ref string strHashData) { //从字符串中取得Hash描述 byte[] Buffer; byte[] HashData; System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5"); Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource); HashData = MD5.ComputeHash(Buffer); strHashData = Convert.ToBase64String(HashData); return true; } //获取Hash描述表 public bool GetHash(System.IO.FileStream objFile, ref byte[] HashData) { //从文件中取得Hash描述 System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5"); HashData = MD5.ComputeHash(objFile); objFile.Close(); return true; } //获取Hash描述表 public bool GetHash(System.IO.FileStream objFile, ref string strHashData) { //从文件中取得Hash描述 byte[] HashData; System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5"); HashData = MD5.ComputeHash(objFile); objFile.Close(); strHashData = Convert.ToBase64String(HashData); return true; } #endregion #region RSA签名 //RSA签名 public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref byte[] EncryptedSignatureData) { System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPrivate); System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA); //设置签名的算法为MD5 RSAFormatter.SetHashAlgorithm("MD5"); //执行签名 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature); return true; } //RSA签名 public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref string m_strEncryptedSignatureData) { byte[] EncryptedSignatureData; System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPrivate); System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA); //设置签名的算法为MD5 RSAFormatter.SetHashAlgorithm("MD5"); //执行签名 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature); m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData); return true; } //RSA签名 public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref byte[] EncryptedSignatureData) { byte[] HashbyteSignature; HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature); System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPrivate); System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA); //设置签名的算法为MD5 RSAFormatter.SetHashAlgorithm("MD5"); //执行签名 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature); return true; } //RSA签名 public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref string m_strEncryptedSignatureData) { byte[] HashbyteSignature; byte[] EncryptedSignatureData; HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature); System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPrivate); System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA); //设置签名的算法为MD5 RSAFormatter.SetHashAlgorithm("MD5"); //执行签名 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature); m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData); return true; } #endregion #region RSA 签名验证 public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, byte[] DeformatterData) { System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPublic); System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA); //指定解密的时候HASH算法为MD5 RSADeformatter.SetHashAlgorithm("MD5"); if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData)) { return true; } else { return false; } } public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, byte[] DeformatterData) { byte[] HashbyteDeformatter; HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter); System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPublic); System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA); //指定解密的时候HASH算法为MD5 RSADeformatter.SetHashAlgorithm("MD5"); if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData)) { return true; } else { return false; } } public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, string p_strDeformatterData) { byte[] DeformatterData; System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPublic); System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA); //指定解密的时候HASH算法为MD5 RSADeformatter.SetHashAlgorithm("MD5"); DeformatterData = Convert.FromBase64String(p_strDeformatterData); if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData)) { return true; } else { return false; } } public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, string p_strDeformatterData) { byte[] DeformatterData; byte[] HashbyteDeformatter; HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter); System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPublic); System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA); //指定解密的时候HASH算法为MD5 RSADeformatter.SetHashAlgorithm("MD5"); DeformatterData = Convert.FromBase64String(p_strDeformatterData); if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData)) { return true; } else { return false; } } } #endregion #endregion