private static string DomainMapper(Match match) { var idn = new IdnMapping(); var domainName = match.Groups[2].Value; domainName = idn.GetAscii(domainName); return match.Groups[1].Value + domainName; }
public bool IsValidUsername(string strIn) { bool invalid = false; if (String.IsNullOrEmpty(strIn)) return false; MatchEvaluator DomainMapper = match => { // IdnMapping class with default property values. var idn = new IdnMapping(); string domainName = match.Groups[2].Value; try { domainName = idn.GetAscii(domainName); } catch (ArgumentException) { invalid = true; } return match.Groups[1].Value + domainName; }; // Use IdnMapping class to convert Unicode domain names. // strIn = Regex.Replace(strIn, @"(@)(.+)$", DomainMapper); if (invalid) return false; // Return true if strIn is in valid e-mail format. return Regex.IsMatch(strIn, @"^[a-z][a-zA-Z]*$", RegexOptions.IgnoreCase); }
public static bool SslCheckHostnameMatch(SafeSslHandle handle, string hostName, DateTime notBefore) { int result; // The IdnMapping converts Unicode input into the IDNA punycode sequence. // It also does host case normalization. The bypass logic would be something // like "all characters being within [a-z0-9.-]+" // Since it's not documented as being thread safe, create a new one each time. // // The SSL Policy (SecPolicyCreateSSL) has been verified as not inherently supporting // IDNA as of macOS 10.12.1 (Sierra). If it supports low-level IDNA at a later date, // this code could be removed. // // It was verified as supporting case invariant match as of 10.12.1 (Sierra). string matchName = new System.Globalization.IdnMapping().GetAscii(hostName); using (SafeCFDateHandle cfNotBefore = CoreFoundation.CFDateCreate(notBefore)) using (SafeCreateHandle cfHostname = CoreFoundation.CFStringCreateWithCString(matchName)) { result = AppleCryptoNative_SslIsHostnameMatch(handle, cfHostname, cfNotBefore); } switch (result) { case 0: return(false); case 1: return(true); default: Debug.Fail($"AppleCryptoNative_SslIsHostnameMatch returned {result}"); throw new SslException(); } }
public bool IsValidEmail(string strIn) { var invalid = false; if (String.IsNullOrEmpty(strIn)) return false; MatchEvaluator DomainMapper = match => { // IdnMapping class with default property values. IdnMapping idn = new IdnMapping(); string domainName = match.Groups[2].Value; try { domainName = idn.GetAscii(domainName); } catch (ArgumentException) { invalid = true; } return match.Groups[1].Value + domainName; }; // Use IdnMapping class to convert Unicode domain names. strIn = Regex.Replace(strIn, @"(@)(.+)$", DomainMapper); if (invalid) return false; // Return true if strIn is in valid e-mail format. return Regex.IsMatch(strIn, @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$", RegexOptions.IgnoreCase); }
public bool IsEmail(string src) { if (string.IsNullOrWhiteSpace(src)) return false; try { // Use IdnMapping class to convert Unicode domain names. var idn = new IdnMapping(); src = Regex.Replace( src, @"(@)(.+)$", match => match.Groups[1].Value + idn.GetAscii(match.Groups[2].Value), RegexOptions.None, TimeSpan.FromMilliseconds(200)); // Validate email address using Regex. return Regex.IsMatch( src, @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)); } catch (Exception ex) { this.loggingService.Exception(ex, "Error while validation email address:", src); return false; } }
void GetUnicodeInvalid (IdnMapping m, string s, object label) { try { m.GetUnicode (s); Assert.Fail (label != null ? label.ToString () + ":" + s : s); } catch (ArgumentException) { } }
private void VerifyStd3AsciiRules(string unicode) { var idnStd3False = new IdnMapping { UseStd3AsciiRules = false }; var idnStd3True = new IdnMapping { UseStd3AsciiRules = true }; Assert.Equal(unicode, idnStd3False.GetAscii(unicode)); Assert.Throws<ArgumentException>(() => idnStd3True.GetAscii(unicode)); }
private string DomainMapper(Match match) { IdnMapping idn = new IdnMapping(); string domainName = match.Groups[2].Value; try { domainName = idn.GetAscii(domainName); } catch (ArgumentException) { _emailIsInvalid = true; } return match.Groups[1].Value + domainName; }
public static string DomainMapper(Match match) { // IdnMapping class with default property values. var idn = new IdnMapping(); var domainName = match.Groups[2].Value; domainName = idn.GetAscii(domainName); return match.Groups[1].Value + domainName; }
private string DomainMapper(Match match) { // IdnMapping class with default property values. IdnMapping idn = new IdnMapping(); string domainName = match.Groups[2].Value; try { domainName = idn.GetAscii(domainName); } catch(ArgumentException) { this._invalid = true; } return match.Groups[1].Value + domainName; }
public void SimpleValidationTests() { var idn = new IdnMapping(); Assert.Equal("xn--yda", idn.GetAscii("\u0101")); Assert.Equal("xn--yda", idn.GetAscii("\u0101", 0)); Assert.Equal("xn--yda", idn.GetAscii("\u0101", 0, 1)); Assert.Equal("xn--aa-cla", idn.GetAscii("\u0101\u0061\u0041")); Assert.Equal("xn--ab-dla", idn.GetAscii("\u0061\u0101\u0062")); Assert.Equal("xn--ab-ela", idn.GetAscii("\u0061\u0062\u0101")); }
public void FullyQualifiedDomainNameVsIndividualLabels() { var idn = new IdnMapping(); // ASCII only code points Assert.Equal("\u0061\u0062\u0063", idn.GetAscii("\u0061\u0062\u0063")); // non-ASCII only code points Assert.Equal("xn--d9juau41awczczp", idn.GetAscii("\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067")); // ASCII and non-ASCII code points Assert.Equal("xn--de-jg4avhby1noc0d", idn.GetAscii("\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0")); // Fully Qualified Domain Name Assert.Equal("abc.xn--d9juau41awczczp.xn--de-jg4avhby1noc0d", idn.GetAscii("\u0061\u0062\u0063.\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067.\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0")); }
private string DomainMapper(string strIn) { string ret = Regex.Replace(strIn, @"(@)(.+)$", (match) => { IdnMapping idn = new IdnMapping(); string domainName = match.Groups[2].Value; domainName = idn.GetAscii(domainName); return match.Groups[1].Value + domainName; }, RegexOptions.None, TimeSpan.FromMilliseconds(200)); return ret; }
public void EmbeddedNulls() { var idn = new IdnMapping(); Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0101\u0000")); Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0101\u0000", 0)); Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0101\u0000", 0, 2)); Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0101\u0000\u0101")); Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0101\u0000\u0101", 0)); Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0101\u0000\u0101", 0, 3)); Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0101\u0000\u0101\u0000")); Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0101\u0000\u0101\u0000", 0)); Assert.Throws<ArgumentException>(() => idn.GetAscii("\u0101\u0000\u0101\u0000", 0, 4)); }
public static bool IsValidEmail(string email) { bool invalid = false; if (String.IsNullOrEmpty(email)) { return false; } try { email = Regex.Replace(email, @"(@)(.+)$", match => { //use IdnMapping class to convert Unicode domain names. var idn = new IdnMapping(); string domainName = match.Groups[2].Value; try { domainName = idn.GetAscii(domainName); } catch (ArgumentException) { invalid = true; } return match.Groups[1].Value + domainName; }, RegexOptions.Compiled, TimeSpan.FromMilliseconds(200)); } catch (RegexMatchTimeoutException) { return false; } if (invalid) { return false; } //return true if input is in valid e-mail format. try { return EmailRegex.IsMatch(email); } catch (RegexMatchTimeoutException) { return false; } }
private static string ConvertUnicodeToPunycodeDomain(Match match) { string str; IdnMapping idnMapping = new IdnMapping(); string value = match.Groups[2].Value; try { value = idnMapping.GetAscii(value); return string.Concat(match.Groups[1].Value, value); } catch { str = null; } return str; }
// GET: Home public ActionResult Index(string id = "") { _logger.Debug("哈哈"); string domin = Request.Headers["host"]; //Regex r = new Regex(@"[\u4e00-\u9fa5]+"); //Match mc = r.Match(domin); //if (mc.Length != 0)//含中文域名 //{ // IdnMapping dd = new IdnMapping(); // domin = dd.GetUnicode(domin); //} IdnMapping dd = new IdnMapping(); domin = dd.GetUnicode(domin); ViewBag.Domin = domin + " | "+id; return View(); }
bool IsValidEmail(string email) { if (string.IsNullOrWhiteSpace(email)) { return(false); } try { // Normalize the domain email = Regex.Replace(email, @"(@)(.+)$", DomainMapper, RegexOptions.None, TimeSpan.FromMilliseconds(200)); // Examines the domain part of the email and normalizes it. string DomainMapper(Match match) { // Use IdnMapping class to convert Unicode domain names. var idn = new System.Globalization.IdnMapping(); // Pull out and process domain name (throws ArgumentException on invalid) var domainName = idn.GetAscii(match.Groups[2].Value); return(match.Groups[1].Value + domainName); } } catch (RegexMatchTimeoutException e) { return(false); } catch (ArgumentException e) { return(false); } try { return(Regex.IsMatch(email, @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$", RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250))); } catch (RegexMatchTimeoutException) { return(false); } }
// Проверка домена, чтобы все его символы были из ASCII public string DomainMapper(Match match) { // IdnMapping class with default property values. IdnMapping idn = new IdnMapping(); string domainName = match.Groups[2].Value; Console.WriteLine("domain={0}", domainName); try { // Метод IdnMapping.GetAscii нормализует имя домена, преобразует нормализованное имя в представление domainName = idn.GetAscii(domainName); } catch (ArgumentException) { invalid = true; } return match.Groups[1].Value + domainName; }
/// <summary> /// Assists in domain mapping. /// </summary> /// <param name="match"> /// The match. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> private string DomainMapper(Match match) { // IdnMapping class with default property values. var idn = new IdnMapping(); var domainName = match.Groups[2].Value; try { domainName = idn.GetAscii(domainName); } catch (ArgumentException) { MultiLogHelper.Debug<EmailValidationHelper>("Invalid email address"); this.invalid = true; } return match.Groups[1].Value + domainName; }
private static void VerifyMessage(SqrlMessage sqrl) { string url = sqrl.Uri.ToString() .Replace("https://", "sqrl://") .Replace("http://", "qrl://"); var idn = new IdnMapping(); var puny = idn.GetAscii(url); var punyBytes = Encoding.ASCII.GetBytes(puny); var signatureBytes = sqrl.SignatureBytes; var signature = new byte[punyBytes.Length + signatureBytes.Length]; Buffer.BlockCopy(signatureBytes, 0, signature, 0, signatureBytes.Length); Buffer.BlockCopy(punyBytes, 0, signature, signatureBytes.Length, punyBytes.Length); if (!CryptoSign.Open(signature, sqrl.PublicKeyBytes)) { throw new SqrlAuthenticationException("Signature verification failed."); } }
public string DomainMapper(Match match) { m_Invalid = false; // IdnMapping class with default property values. var idn = new IdnMapping(); string domainName = match.Groups[2].Value; try { domainName = idn.GetAscii(domainName); } catch (ArgumentException) { m_Invalid = true; } return match.Groups[1].Value + domainName; }
internal static SslPolicyErrors BuildChainAndVerifyProperties(X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, string hostName) { SslPolicyErrors errors = chain.Build(remoteCertificate) ? SslPolicyErrors.None : SslPolicyErrors.RemoteCertificateChainErrors; if (!checkCertName) { return errors; } if (string.IsNullOrEmpty(hostName)) { return errors | SslPolicyErrors.RemoteCertificateNameMismatch; } int hostNameMatch; using (SafeX509Handle certHandle = Interop.Crypto.X509Duplicate(remoteCertificate.Handle)) { IPAddress hostnameAsIp; if (IPAddress.TryParse(hostName, out hostnameAsIp)) { byte[] addressBytes = hostnameAsIp.GetAddressBytes(); hostNameMatch = Interop.Crypto.CheckX509IpAddress(certHandle, addressBytes, addressBytes.Length, hostName, hostName.Length); } else { // The IdnMapping converts Unicode input into the IDNA punycode sequence. // It also does host case normalization. The bypass logic would be something // like "all characters being within [a-z0-9.-]+" // Since it's not documented as being thread safe, create a new one each time. string matchName = new IdnMapping().GetAscii(hostName); hostNameMatch = Interop.Crypto.CheckX509Hostname(certHandle, matchName, matchName.Length); } } Debug.Assert(hostNameMatch == 0 || hostNameMatch == 1, $"Expected 0 or 1 from CheckX509Hostname, got {hostNameMatch}"); return hostNameMatch == 1 ? errors : errors | SslPolicyErrors.RemoteCertificateNameMismatch; }
public void GetAsciiInvalid () { // hmm... according to RFC 3490, there are couple of // invalid characters in RFC 3491 [Nameprop] ... // comment out them for now. IdnMapping m = new IdnMapping (); GetAsciiInvalid (m, "\x0", 1); GetAsciiInvalid (m, "\xD\xA", 2); GetAsciiInvalid (m, "\x1F", 3); GetAsciiInvalid (m, "\x7F", 4); GetAsciiInvalid (m, "\x80", 5); // GetAsciiInvalid (m, "\xA0", 6); // GetAsciiInvalid (m, "\u1680", 7); GetAsciiInvalid (m, "\u200E", 8); // GetAsciiInvalid (m, "\u0341", 9); GetAsciiInvalid (m, "\uE000", 10); GetAsciiInvalid (m, "\uFFFF", 11); GetAsciiInvalid (m, "\u2028", 12); GetAsciiInvalid (m, "\uD800", 13); // GetAsciiInvalid (m, "\u3000", 14); }
// // Will convert a host name into its unicode equivalent expanding any existing idn names present // internal unsafe static string UnicodeEquivalent(string idnHost, char* hostname, int start, int end) { IdnMapping map = new IdnMapping(); // Test comon scenario first for perf // try to get unicode equivalent try { return map.GetUnicode(idnHost); } catch (ArgumentException) { } // Here because something threw in GetUnicode above // Need to now check individual labels of they had an ace label that was not valid Idn name // or if there is a label with invalid Idn char. bool dummy = true; return UnicodeEquivalent(hostname, start, end, ref dummy, ref dummy); }
// // Will convert a host name into its idn equivalent + tell you if it had a valid idn label // internal unsafe static string IdnEquivalent(char* hostname, int start, int end, ref bool allAscii, ref bool atLeastOneValidIdn) { string bidiStrippedHost = null; string idnEquivalent = IdnEquivalent(hostname, start, end, ref allAscii, ref bidiStrippedHost); if (idnEquivalent != null) { string strippedHost = (allAscii ? idnEquivalent : bidiStrippedHost); fixed (char* strippedHostPtr = strippedHost) { int length = strippedHost.Length; int newPos = 0; int curPos = 0; bool foundAce = false; bool checkedAce = false; bool foundDot = false; do { foundAce = false; checkedAce = false; foundDot = false; //find the dot or hit the end newPos = curPos; while (newPos < length) { char c = strippedHostPtr[newPos]; if (!checkedAce) { checkedAce = true; if ((newPos + 3 < length) && IsIdnAce(strippedHostPtr, newPos)) { newPos += 4; foundAce = true; continue; } } if ((c == '.') || (c == '\u3002') || //IDEOGRAPHIC FULL STOP (c == '\uFF0E') || //FULLWIDTH FULL STOP (c == '\uFF61')) //HALFWIDTH IDEOGRAPHIC FULL STOP { foundDot = true; break; } ++newPos; } if (foundAce) { // check ace validity try { IdnMapping map = new IdnMapping(); map.GetUnicode(new string(strippedHostPtr, curPos, newPos - curPos)); atLeastOneValidIdn = true; break; } catch (ArgumentException) { // not valid ace so treat it as a normal ascii label } } curPos = newPos + (foundDot ? 1 : 0); } while (curPos < length); } } else { atLeastOneValidIdn = false; } return idnEquivalent; }
// // Will convert a host name into its idn equivalent // internal unsafe static string IdnEquivalent(char* hostname, int start, int end, ref bool allAscii, ref string bidiStrippedHost) { string idn = null; if (end <= start) return idn; // indexes are validated int newPos = start; allAscii = true; while (newPos < end) { // check if only ascii chars // special case since idnmapping will not lowercase if only ascii present if (hostname[newPos] > '\x7F') { allAscii = false; break; } ++newPos; } if (allAscii) { // just lowercase for ascii string unescapedHostname = new string(hostname, start, end - start); return ((unescapedHostname != null) ? unescapedHostname.ToLowerInvariant() : null); } else { IdnMapping map = new IdnMapping(); string asciiForm; bidiStrippedHost = Uri.StripBidiControlCharacter(hostname, start, end - start); try { asciiForm = map.GetAscii(bidiStrippedHost); } catch (ArgumentException) { throw new UriFormatException(SR.net_uri_BadUnicodeHostForIdn); } return asciiForm; } }
internal unsafe static string UnicodeEquivalent(char* hostname, int start, int end, ref bool allAscii, ref bool atLeastOneValidIdn) { IdnMapping map = new IdnMapping(); // hostname already validated allAscii = true; atLeastOneValidIdn = false; string idn = null; if (end <= start) return idn; string unescapedHostname = Uri.StripBidiControlCharacter(hostname, start, (end - start)); string unicodeEqvlHost = null; int curPos = 0; int newPos = 0; int length = unescapedHostname.Length; bool asciiLabel = true; bool foundAce = false; bool checkedAce = false; bool foundDot = false; // We run a loop where for every label // a) if label is ascii and no ace then we lowercase it // b) if label is ascii and ace and not valid idn then just lowercase it // c) if label is ascii and ace and is valid idn then get its unicode eqvl // d) if label is unicode then clean it by running it through idnmapping do { asciiLabel = true; foundAce = false; checkedAce = false; foundDot = false; //find the dot or hit the end newPos = curPos; while (newPos < length) { char c = unescapedHostname[newPos]; if (!checkedAce) { checkedAce = true; if ((newPos + 3 < length) && (c == 'x') && IsIdnAce(unescapedHostname, newPos)) foundAce = true; } if (asciiLabel && (c > '\x7F')) { asciiLabel = false; allAscii = false; } if ((c == '.') || (c == '\u3002') || //IDEOGRAPHIC FULL STOP (c == '\uFF0E') || //FULLWIDTH FULL STOP (c == '\uFF61')) //HALFWIDTH IDEOGRAPHIC FULL STOP { foundDot = true; break; } ++newPos; } if (!asciiLabel) { string asciiForm = unescapedHostname.Substring(curPos, newPos - curPos); try { asciiForm = map.GetAscii(asciiForm); } catch (ArgumentException) { throw new UriFormatException(SR.net_uri_BadUnicodeHostForIdn); } unicodeEqvlHost += map.GetUnicode(asciiForm); if (foundDot) unicodeEqvlHost += "."; } else { bool aceValid = false; if (foundAce) { // check ace validity try { unicodeEqvlHost += map.GetUnicode(unescapedHostname.Substring(curPos, newPos - curPos)); if (foundDot) unicodeEqvlHost += "."; aceValid = true; atLeastOneValidIdn = true; } catch (ArgumentException) { // not valid ace so treat it as a normal ascii label } } if (!aceValid) { // for invalid aces we just lowercase the label unicodeEqvlHost += unescapedHostname.Substring(curPos, newPos - curPos).ToLowerInvariant(); if (foundDot) unicodeEqvlHost += "."; } } curPos = newPos + (foundDot ? 1 : 0); } while (curPos < length); return unicodeEqvlHost; }
// Token: 0x06002FE3 RID: 12259 RVA: 0x000B7D34 File Offset: 0x000B5F34 private static string punycode_decode(string ascii) { if (ascii.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadLabelSize"), "ascii"); } if (ascii.Length > 255 - (IdnMapping.IsDot(ascii[ascii.Length - 1]) ? 0 : 1)) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadNameSize", new object[] { 255 - (IdnMapping.IsDot(ascii[ascii.Length - 1]) ? 0 : 1) }), "ascii"); } StringBuilder stringBuilder = new StringBuilder(ascii.Length); int i = 0; int num = 0; int num2 = 0; while (i < ascii.Length) { i = ascii.IndexOf('.', num); if (i < 0 || i > ascii.Length) { i = ascii.Length; } if (i == num) { if (i != ascii.Length) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadLabelSize"), "ascii"); } break; } else { if (i - num > 63) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadLabelSize"), "ascii"); } if (ascii.Length < "xn--".Length + num || !ascii.Substring(num, "xn--".Length).Equals("xn--", StringComparison.OrdinalIgnoreCase)) { stringBuilder.Append(ascii.Substring(num, i - num)); } else { num += "xn--".Length; int num3 = ascii.LastIndexOf('-', i - 1); if (num3 == i - 1) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), "ascii"); } int num4; if (num3 <= num) { num4 = 0; } else { num4 = num3 - num; for (int j = num; j < num + num4; j++) { if (ascii[j] > '\u007f') { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), "ascii"); } stringBuilder.Append((ascii[j] >= 'A' && ascii[j] <= 'Z') ? (ascii[j] - 'A' + 'a') : ascii[j]); } } int k = num + ((num4 > 0) ? (num4 + 1) : 0); int num5 = 128; int num6 = 72; int num7 = 0; int num8 = 0; IL_40D: while (k < i) { int num9 = num7; int num10 = 1; int num11 = 36; while (k < i) { int num12 = IdnMapping.decode_digit(ascii[k++]); if (num12 > (134217727 - num7) / num10) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), "ascii"); } num7 += num12 * num10; int num13 = (num11 <= num6) ? 1 : ((num11 >= num6 + 26) ? 26 : (num11 - num6)); if (num12 >= num13) { if (num10 > 134217727 / (36 - num13)) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), "ascii"); } num10 *= 36 - num13; num11 += 36; } else { num6 = IdnMapping.adapt(num7 - num9, stringBuilder.Length - num2 - num8 + 1, num9 == 0); if (num7 / (stringBuilder.Length - num2 - num8 + 1) > 134217727 - num5) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), "ascii"); } num5 += num7 / (stringBuilder.Length - num2 - num8 + 1); num7 %= stringBuilder.Length - num2 - num8 + 1; if (num5 < 0 || num5 > 1114111 || (num5 >= 55296 && num5 <= 57343)) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), "ascii"); } string value = char.ConvertFromUtf32(num5); int num14; if (num8 > 0) { int l = num7; num14 = num2; while (l > 0) { if (num14 >= stringBuilder.Length) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), "ascii"); } if (char.IsSurrogate(stringBuilder[num14])) { num14++; } l--; num14++; } } else { num14 = num2 + num7; } stringBuilder.Insert(num14, value); if (IdnMapping.IsSupplementary(num5)) { num8++; } num7++; goto IL_40D; } } throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), "ascii"); } bool flag = false; BidiCategory bidiCategory = CharUnicodeInfo.GetBidiCategory(stringBuilder.ToString(), num2); if (bidiCategory == BidiCategory.RightToLeft || bidiCategory == BidiCategory.RightToLeftArabic) { flag = true; } for (int m = num2; m < stringBuilder.Length; m++) { if (!char.IsLowSurrogate(stringBuilder.ToString(), m)) { bidiCategory = CharUnicodeInfo.GetBidiCategory(stringBuilder.ToString(), m); if ((flag && bidiCategory == BidiCategory.LeftToRight) || (!flag && (bidiCategory == BidiCategory.RightToLeft || bidiCategory == BidiCategory.RightToLeftArabic))) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadBidi"), "ascii"); } } } if (flag && bidiCategory != BidiCategory.RightToLeft && bidiCategory != BidiCategory.RightToLeftArabic) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadBidi"), "ascii"); } } if (i - num > 63) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadLabelSize"), "ascii"); } if (i != ascii.Length) { stringBuilder.Append('.'); } num = i + 1; num2 = stringBuilder.Length; } } if (stringBuilder.Length > 255 - (IdnMapping.IsDot(stringBuilder[stringBuilder.Length - 1]) ? 0 : 1)) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadNameSize", new object[] { 255 - (IdnMapping.IsDot(stringBuilder[stringBuilder.Length - 1]) ? 0 : 1) }), "ascii"); } return(stringBuilder.ToString()); }
// Token: 0x06002FE2 RID: 12258 RVA: 0x000B7924 File Offset: 0x000B5B24 private static string punycode_encode(string unicode) { if (unicode.Length == 0) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadLabelSize"), "unicode"); } StringBuilder stringBuilder = new StringBuilder(unicode.Length); int i = 0; int num = 0; int num2 = 0; while (i < unicode.Length) { i = unicode.IndexOfAny(IdnMapping.M_Dots, num); if (i < 0) { i = unicode.Length; } if (i == num) { if (i != unicode.Length) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadLabelSize"), "unicode"); } break; } else { stringBuilder.Append("xn--"); bool flag = false; BidiCategory bidiCategory = CharUnicodeInfo.GetBidiCategory(unicode, num); if (bidiCategory == BidiCategory.RightToLeft || bidiCategory == BidiCategory.RightToLeftArabic) { flag = true; int num3 = i - 1; if (char.IsLowSurrogate(unicode, num3)) { num3--; } bidiCategory = CharUnicodeInfo.GetBidiCategory(unicode, num3); if (bidiCategory != BidiCategory.RightToLeft && bidiCategory != BidiCategory.RightToLeftArabic) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadBidi"), "unicode"); } } int j = 0; for (int k = num; k < i; k++) { BidiCategory bidiCategory2 = CharUnicodeInfo.GetBidiCategory(unicode, k); if (flag && bidiCategory2 == BidiCategory.LeftToRight) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadBidi"), "unicode"); } if (!flag && (bidiCategory2 == BidiCategory.RightToLeft || bidiCategory2 == BidiCategory.RightToLeftArabic)) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadBidi"), "unicode"); } if (IdnMapping.basic((uint)unicode[k])) { stringBuilder.Append(IdnMapping.encode_basic(unicode[k])); j++; } else if (char.IsSurrogatePair(unicode, k)) { k++; } } int num4 = j; if (num4 == i - num) { stringBuilder.Remove(num2, "xn--".Length); } else { if (unicode.Length - num >= "xn--".Length && unicode.Substring(num, "xn--".Length).Equals("xn--", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), "unicode"); } int num5 = 0; if (num4 > 0) { stringBuilder.Append('-'); } int num6 = 128; int num7 = 0; int num8 = 72; while (j < i - num) { int num9 = 134217727; int num10; for (int l = num; l < i; l += (IdnMapping.IsSupplementary(num10) ? 2 : 1)) { num10 = char.ConvertToUtf32(unicode, l); if (num10 >= num6 && num10 < num9) { num9 = num10; } } num7 += (num9 - num6) * (j - num5 + 1); num6 = num9; for (int l = num; l < i; l += (IdnMapping.IsSupplementary(num10) ? 2 : 1)) { num10 = char.ConvertToUtf32(unicode, l); if (num10 < num6) { num7++; } if (num10 == num6) { int num11 = num7; int num12 = 36; for (;;) { int num13 = (num12 <= num8) ? 1 : ((num12 >= num8 + 26) ? 26 : (num12 - num8)); if (num11 < num13) { break; } stringBuilder.Append(IdnMapping.encode_digit(num13 + (num11 - num13) % (36 - num13))); num11 = (num11 - num13) / (36 - num13); num12 += 36; } stringBuilder.Append(IdnMapping.encode_digit(num11)); num8 = IdnMapping.adapt(num7, j - num5 + 1, j == num4); num7 = 0; j++; if (IdnMapping.IsSupplementary(num9)) { j++; num5++; } } } num7++; num6++; } } if (stringBuilder.Length - num2 > 63) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadLabelSize"), "unicode"); } if (i != unicode.Length) { stringBuilder.Append('.'); } num = i + 1; num2 = stringBuilder.Length; } } if (stringBuilder.Length > 255 - (IdnMapping.IsDot(unicode[unicode.Length - 1]) ? 0 : 1)) { throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadNameSize", new object[] { 255 - (IdnMapping.IsDot(unicode[unicode.Length - 1]) ? 0 : 1) }), "unicode"); } return(stringBuilder.ToString()); }
internal static SslPolicyErrors VerifyCertificateProperties( X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, bool isServer, string hostName) { SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None; if (!chain.Build(remoteCertificate)) { sslPolicyErrors |= SslPolicyErrors.RemoteCertificateChainErrors; } if (checkCertName) { if (string.IsNullOrEmpty(hostName)) { sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch; } else { int hostnameMatch; using (SafeX509Handle certHandle = Interop.Crypto.X509Duplicate(remoteCertificate.Handle)) { IPAddress hostnameAsIp; if (IPAddress.TryParse(hostName, out hostnameAsIp)) { byte[] addressBytes = hostnameAsIp.GetAddressBytes(); hostnameMatch = Interop.Crypto.CheckX509IpAddress( certHandle, addressBytes, addressBytes.Length, hostName, hostName.Length); } else { // The IdnMapping converts Unicode input into the IDNA punycode sequence. // It also does host case normalization. The bypass logic would be something // like "all characters being within [a-z0-9.-]+" // // Since it's not documented as being thread safe, create a new one each time. IdnMapping mapping = new IdnMapping(); string matchName = mapping.GetAscii(hostName); hostnameMatch = Interop.Crypto.CheckX509Hostname(certHandle, matchName, matchName.Length); } } if (hostnameMatch != 1) { Debug.Assert(hostnameMatch == 0, "hostnameMatch should be (0,1) was " + hostnameMatch); sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch; } } } return sslPolicyErrors; }
public List<string> GetImportableItems(int packageId, int itemTypeId, Type itemType, ResourceGroupInfo group) { List<string> items = new List<string>(); // get service id int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName); if (serviceId == 0) return items; // Mail provider DNSServer dns = new DNSServer(); ServiceProviderProxy.Init(dns, serviceId); // IDN: The list of importable names is populated with unicode names, to make it easier for the user var idn = new IdnMapping(); if (itemType == typeof(DnsZone)) items.AddRange(dns.GetZones()); return items; }
private static CheckResult TryAccessURL(String strOriginalURL) { CheckResult r = new CheckResult(); try { UriBuilder ubBuildURL = null; try { r.BuildURL = strOriginalURL; ubBuildURL = new UriBuilder(strOriginalURL); //IdnMappingオブジェクトを作成する System.Globalization.IdnMapping im = new System.Globalization.IdnMapping(); //punycodeにエンコードする string punycode = im.GetAscii(ubBuildURL.Host); ubBuildURL.Host = punycode; } catch (Exception err) { r.StatusCode = err.Message; r.StatusDescription = strOriginalURL; Console.WriteLine("{0}:::::{1}", r.StatusCode, r.StatusDescription); throw err; } //WebRequestの作成 System.Net.HttpWebRequest webreq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(ubBuildURL.Uri); r.BuildURL = ubBuildURL.Uri.ToString(); System.Net.HttpWebResponse webres = null; try { //サーバーからの応答を受信するためのWebResponseを取得 webres = (System.Net.HttpWebResponse)webreq.GetResponse(); //応答したURIを表示する System.Diagnostics.Trace.WriteLine(webres.ResponseUri + "\n"); //応答ステータスコードを表示する System.Diagnostics.Trace.WriteLine(String.Format("{0}::{1}", webres.StatusCode, webres.StatusDescription) + "\n"); r.StatusCode = webres.StatusCode.ToString(); r.StatusDescription = webres.StatusDescription.ToString(); } catch (System.Net.WebException ex) { //HTTPプロトコルエラーかどうか調べる if (ex.Status == System.Net.WebExceptionStatus.ProtocolError) { //HttpWebResponseを取得 System.Net.HttpWebResponse errres = (System.Net.HttpWebResponse)ex.Response; //応答したURIを表示する System.Diagnostics.Trace.WriteLine(errres.ResponseUri + "\n"); //応答ステータスコードを表示する System.Diagnostics.Trace.WriteLine(String.Format("{0}:::{1}", errres.StatusCode, errres.StatusDescription)); r.StatusCode = errres.StatusCode.ToString(); r.StatusDescription = errres.StatusDescription.ToString(); } else { r.StatusCode = ex.ToString(); System.Diagnostics.Trace.WriteLine(ex.Message + "\n"); } } finally { //閉じる if (webres != null) { webres.Close(); } } } catch (Exception e) { r.StatusCode = e.Message; r.StatusDescription = e.Message; } return(r); }
private static string GetAsciiZoneName(string zoneName) { if (string.IsNullOrEmpty(zoneName)) return zoneName; var idn = new IdnMapping(); return idn.GetAscii(zoneName); }
private void Initialize() { if (_port == DefaultPort || _port == 0) { new SmtpPermission(SmtpAccess.Connect).Demand(); } else { new SmtpPermission(SmtpAccess.ConnectToUnrestrictedPort).Demand(); } _transport = new SmtpTransport(this); if (MailEventSource.Log.IsEnabled()) MailEventSource.Log.Associate(this, _transport); _onSendCompletedDelegate = new SendOrPostCallback(SendCompletedWaitCallback); if (_host != null && _host.Length != 0) { _host = _host.Trim(); } if (_port == 0) { _port = DefaultPort; } if (_targetName == null) _targetName = "SMTPSVC/" + _host; if (clientDomain == null) { // We use the local host name as the default client domain // for the client's EHLO or HELO message. This limits the // information about the host that we share. Additionally, the // FQDN is not available to us or useful to the server (internal // machine connecting to public server). // SMTP RFC's require ASCII only host names in the HELO/EHLO message. string clientDomainRaw = IPGlobalProperties.GetIPGlobalProperties().HostName; IdnMapping mapping = new IdnMapping(); try { clientDomainRaw = mapping.GetAscii(clientDomainRaw); } catch (ArgumentException) { } // For some inputs GetAscii may fail (bad Unicode, etc). If that happens // we must strip out any non-ASCII characters. // If we end up with no characters left, we use the string "LocalHost". This // matches Outlook behavior. StringBuilder sb = new StringBuilder(); char ch; for (int i = 0; i < clientDomainRaw.Length; i++) { ch = clientDomainRaw[i]; if ((ushort)ch <= 0x7F) sb.Append(ch); } if (sb.Length > 0) clientDomain = sb.ToString(); else clientDomain = "LocalHost"; } }
/// <summary>Indicates whether a specified object and the current <see cref="T:System.Globalization.IdnMapping" /> object are equal.</summary> /// <param name="obj">The object to compare to the current object.</param> /// <returns> /// <see langword="true" /> if the object specified by the <paramref name="obj" /> parameter is derived from <see cref="T:System.Globalization.IdnMapping" /> and its <see cref="P:System.Globalization.IdnMapping.AllowUnassigned" /> and <see cref="P:System.Globalization.IdnMapping.UseStd3AsciiRules" /> properties are equal; otherwise, <see langword="false" />. </returns> // Token: 0x06002FD6 RID: 12246 RVA: 0x000B75A0 File Offset: 0x000B57A0 public override bool Equals(object obj) { IdnMapping idnMapping = obj as IdnMapping; return(idnMapping != null && this.m_bAllowUnassigned == idnMapping.m_bAllowUnassigned && this.m_bUseStd3AsciiRules == idnMapping.m_bUseStd3AsciiRules); }