private bool AuthenticateCramMd5(NetworkCredential credentials) { var command = new ImapCommand("AUTHENTICATE CRAM-MD5"); var response = _client.SendAndReceive(command); // don't trim the last plus !! var base64 = response.CurrentLine.TrimStart(Characters.Plus).Trim(); var challenge = Base64Encoder.Decode(base64, Encoding.UTF8); var username = credentials.UserName; var password = credentials.Password; var hash = CramMd5Hasher.ComputeHash(password, challenge); var authentication = username + " " + hash; var authCommand = new BlankImapCommand(Base64Encoder.Encode(authentication)); var reader = _client.SendAndReceive(authCommand); while (!reader.IsCompleted) { reader = _client.Receive(false); } return(reader.IsOk); }
public void BasicEncodingDecoding() { var bytes = new byte[byte.MaxValue + 1]; for (int i = 0; i < byte.MaxValue + 1; i++) { bytes[i] = (byte)i; } for (int value = 0; value < 256; value++) { Span <byte> sourceBytes = bytes.AsSpan().Slice(0, value + 1); Span <byte> encodedBytes = new byte[Base64Encoder.ComputeEncodedLength(sourceBytes.Length)]; Assert.True(Base64Encoder.TryEncode(sourceBytes, encodedBytes, out int consumed, out int encodedBytesCount)); Assert.Equal(encodedBytes.Length, encodedBytesCount); string encodedText = Text.Encoding.ASCII.GetString(encodedBytes.ToArray()); string expectedText = Convert.ToBase64String(bytes, 0, value + 1); Assert.Equal(expectedText, encodedText); if (encodedBytes.Length % 4 == 0) { Span <byte> decodedBytes = new byte[Base64Encoder.ComputeDecodedLength(encodedBytes)]; Assert.True(Base64Encoder.TryDecode(encodedBytes, decodedBytes, out consumed, out int decodedByteCount)); Assert.Equal(sourceBytes.Length, decodedByteCount); Assert.True(sourceBytes.SequenceEqual(decodedBytes)); } } }
private bool AuthenticatePlain(NetworkCredential credentials) { var capabilities = _client.ServerCapability; var username = credentials.UserName; var password = credentials.Password; var auth = username + "\0" + username + "\0" + password; var encodedAuth = Base64Encoder.Encode(auth); if (capabilities.IsInitialClientResponseSupported) { var text = string.Format("AUTHENTICATE PLAIN {0}", encodedAuth); var command = new ImapCommand(text); return(_client.SendAndReceive(command).IsOk); } var authCommand = new ImapCommand("AUTHENTICATE PLAIN"); var response = _client.SendAndReceive(authCommand); if (response.IsContinuation) { var command = new BlankImapCommand(encodedAuth); _client.Send(command); return(_client.Receive().IsOk); } return(false); }
public void EncodeInPlace() { const int numberOfBytes = 15; var list = new List <byte>(); for (int value = 0; value < numberOfBytes; value++) { list.Add((byte)value); } // padding for (int i = 0; i < (numberOfBytes / 3) + 2; i++) { list.Add(0); } var testBytes = list.ToArray(); for (int numberOfBytesToTest = 1; numberOfBytesToTest <= numberOfBytes; numberOfBytesToTest++) { var copy = testBytes.Clone(); var expectedText = Convert.ToBase64String(testBytes, 0, numberOfBytesToTest); var encoded = Base64Encoder.EncodeInPlace(testBytes, numberOfBytesToTest); var encodedText = Text.Encoding.ASCII.GetString(testBytes, 0, encoded); Assert.Equal(expectedText, encodedText); } }
public void DestinationLength_too_small_but_retry___OK(bool isFinalBlock) { const int dataLength = 300; const int destLength = 350; var sut = new Base64Encoder(); Span <byte> data = new byte[dataLength]; Span <T> encoded = new T[destLength]; int requitedSize = sut.GetEncodedLength(dataLength); OperationStatus status = sut.EncodeCore(data, encoded, out int consumed, out int written, isFinalBlock); Assert.Multiple(() => { const int expectedConsumed = destLength / 4 * 3; const int expectedWritten = expectedConsumed / 3 * 4; Assert.AreEqual(OperationStatus.DestinationTooSmall, status); Assert.AreEqual(expectedConsumed, consumed); Assert.AreEqual(expectedWritten, written); }); data = data.Slice(consumed); encoded = new T[sut.GetEncodedLength(data.Length)]; status = sut.EncodeCore(data, encoded, out consumed, out written, isFinalBlock); Assert.AreEqual(OperationStatus.Done, status); Assert.AreEqual(data.Length, consumed); Assert.AreEqual(encoded.Length, written); }
public void Data_of_various_length___roundtrips_correclty_as_string() { var sut = new Base64Encoder(); var bytes = new byte[byte.MaxValue + 1]; for (int i = 0; i < bytes.Length; ++i) { bytes[i] = (byte)(255 - i); } for (int i = 0; i < 256; ++i) { Span <byte> source = bytes.AsSpan(0, i + 1); string encoded = sut.Encode(source); #if NETCOREAPP string encodedExpected = Convert.ToBase64String(source); #else string encodedExpected = Convert.ToBase64String(source.ToArray()); #endif Assert.AreEqual(encodedExpected, encoded); Span <byte> decoded = sut.Decode(encoded.AsSpan()); CollectionAssert.AreEqual(source.ToArray(), decoded.ToArray()); } }
public void DecodeTest() { var actual = Base64Encoder.Decode("QUJDREVGRw=="); var expected = Encoding.ASCII.GetBytes("ABCDEFG"); Assert.Equal(expected, actual); }
public void Encode_KnownArgumentBytes() { byte[] bytes = new byte[] { 0x00, 0x01, 0x03, 0x03, 0x07, 0x00 }; byte[] expectedResult = new byte[] { 65, 65, 69, 68, 65, 119, 99, 65 }; byte[] result = Base64Encoder.Encode(bytes); Assert.AreEqual(expectedResult, result); }
public virtual void SetUp() { expected_plainText = "hello world"; expected_encoded = "aGVsbG8gd29ybGQ="; expected_hexaText = "68656C6C6F20776F726C64"; base64 = new Base64Encoder(); }
public void Encode_KnownArgumentASCII() { byte[] stringBytes = Encoding.ASCII.GetBytes("Hello world"); byte[] expectedResult = new byte[] { 83, 71, 86, 115, 98, 71, 56, 103, 100, 50, 57, 121, 98, 71, 81, 61 }; byte[] result = Base64Encoder.Encode(stringBytes); Assert.AreEqual(expectedResult, result); }
public void Encode_KnownArgumentUTF8() { byte[] stringBytes = Encoding.UTF8.GetBytes("檔案"); byte[] expectedResult = new byte[] { 53, 113, 113, 85, 53, 113, 71, 73 }; byte[] result = Base64Encoder.Encode(stringBytes); Assert.AreEqual(expectedResult, result); }
public void Decode_Bytes_Bytes() { byte[] expectedResult = new byte[] { 0x00, 0x01, 0x03, 0x03, 0x07, 0x00 }; byte[] data = new byte[] { 65, 65, 69, 68, 65, 119, 99, 65 }; byte[] result = Base64Encoder.Decode(data); Assert.AreEqual(expectedResult, result); }
public void EncodeTest() { var source = Encoding.ASCII.GetBytes("ABCDEFG"); var actual = Base64Encoder.Encode(source); Assert.Equal("QUJDREVGRw==", actual); }
public void EncodedSpan_1_to_50_given___correct_decoded_len() { var sut = new Base64Encoder(); Assert.Multiple(() => { for (int i = 1; i < 50; ++i) { var data = new byte[i]; string base64 = Convert.ToBase64String(data); int actual; if (typeof(T) == typeof(byte)) { byte[] base64Bytes = Encoding.ASCII.GetBytes(base64); actual = sut.GetDecodedLength(base64Bytes); } else if (typeof(T) == typeof(char)) { actual = sut.GetDecodedLength(base64.AsSpan()); } else { throw new NotSupportedException(); // just in case new types are introduced in the future } Assert.AreEqual(i, actual); } }); }
/// <inheritdoc/> public override char[] GetChars(ReadOnlySpan <byte> bytes) { // GetChars process the data in two passes, in order to avoid allocating // temporary storage for the result (which would have to be resized) int charsRequired = GetCharCount(bytes); if (charsRequired == 0) { return(Array.Empty <char>()); } var outputChars = new char[charsRequired]; var encoder = new Base64Encoder(Settings); var convertStatus = encoder.ConvertData(bytes, 0, bytes.Length, outputChars.AsSpan(), 0, outputChars.Length, true, out var inputUsed, out var outputUsed); System.Diagnostics.Debug.Assert(convertStatus); System.Diagnostics.Debug.Assert(inputUsed == bytes.Length); System.Diagnostics.Debug.Assert(outputUsed == outputChars.Length); return(outputChars); }
public Base64EncoderTests(Protocol?protocol = null) { _stringData = "random-string"; _binaryData = _stringData.GetBytes(); _base64Data = _binaryData.ToBase64(); encoder = new Base64Encoder(protocol ?? Protocol.MsgPack); }
protected Base64EncoderTests() { _stringData = "random-string"; _binaryData = _stringData.GetBytes(); _base64Data = _binaryData.ToBase64(); _encoder = new Base64Encoder(); }
/// <inheritdoc/> public override int GetCharCount(ReadOnlySpan <byte> bytes) { var encoder = new Base64Encoder(Settings); Span <char> outputBuffer = stackalloc char[1024]; int inputOffset = 0; int inputCount = bytes.Length; int outputLength = 0; ConvertStatus convertStatus; do { convertStatus = encoder.ConvertData(bytes, inputOffset, inputCount, outputBuffer, 0, outputBuffer.Length, true, out var inputUsed, out var outputUsed); outputLength += outputUsed; inputOffset += inputUsed; inputCount -= inputUsed; } while (!convertStatus); return(outputLength); }
private static async Task <(MemoryStream output, IMS2SizeHeader size)> InternalGetEncryptionStreamAsync(Stream input, long inputSize, IBufferedCipher cipher, long headerSize) { byte[] inputBytes = new byte[inputSize]; int read = await input.ReadAsync(inputBytes, 0, (int)inputSize).ConfigureAwait(false); if (inputSize != read) { throw new EndOfStreamException(); } using var msInput = new MemoryStream(inputBytes); using var cs = new CipherStream(msInput, cipher, null); using var ms = new MemoryStream(); var output = new MemoryStream(); await cs.CopyToAsync(ms).ConfigureAwait(false); var data = ms.ToArray(); var encoder = new Base64Encoder(); encoder.Encode(data, 0, data.Length, output); var header = new MS2SizeHeader(output.Length, inputSize, headerSize); output.Position = 0; return(output, header); }
public void DestinationLength_large_but_too_small___status_DestinationTooSmall() { const int base64Length = 400; const int dataLength = 250; var sut = new Base64Encoder(); var data = new byte[dataLength]; T[] base64 = null; if (typeof(T) == typeof(byte)) { base64 = Enumerable.Repeat((T)(object)(byte)'A', base64Length).ToArray(); } else if (typeof(T) == typeof(char)) { base64 = Enumerable.Repeat((T)(object)'A', base64Length).ToArray(); } else { throw new NotSupportedException(); // just in case new types are introduced in the future } OperationStatus status = sut.DecodeCore <T>(base64, data, out int consumed, out int written); Assert.Multiple(() => { int expectedWritten = 250 - 1; int expectedConsumed = expectedWritten / 3 * 4; Assert.AreEqual(OperationStatus.DestinationTooSmall, status); Assert.AreEqual(expectedConsumed, consumed); Assert.AreEqual(expectedWritten, written); }); }
/// <inheritdoc/> public override unsafe string GetString(ReadOnlySpan <byte> bytes) { var encoder = new Base64Encoder(Settings); Span <char> outputBuffer = stackalloc char[1024]; StringBuilder sb = new StringBuilder(); int inputOffset = 0; int inputCount = bytes.Length; ConvertStatus convertStatus; do { convertStatus = encoder.ConvertData(bytes, inputOffset, inputCount, outputBuffer, 0, outputBuffer.Length, true, out var inputUsed, out var outputUsed); if (outputUsed > 0) { fixed(char *charPtr = &outputBuffer[0]) sb.Append(charPtr, outputUsed); } inputOffset += inputUsed; inputCount -= inputUsed; } while (!convertStatus); return(sb.ToString()); }
private static WebClient BuildEx(ResultMachine machine, bool hasId = true) { var client = new WebClient(); client.Headers.Add(HttpRequestHeader.UserAgent, "Ghosts Client"); if (hasId) { client.Headers.Add("ghosts-id", CheckId.Id); } client.Headers.Add("ghosts-name", machine.Name); client.Headers.Add("ghosts-fqdn", machine.FQDN); client.Headers.Add("ghosts-host", machine.Host); client.Headers.Add("ghosts-domain", machine.Domain); client.Headers.Add("ghosts-resolvedhost", machine.ResolvedHost); client.Headers.Add("ghosts-ip", machine.ClientIp); var username = machine.CurrentUsername; if (Program.Configuration.EncodeHeaders) { username = Base64Encoder.Base64Encode(username); } client.Headers.Add("ghosts-user", username); client.Headers.Add("ghosts-version", ApplicationDetails.Version); return(client); }
/// <summary> /// Computes the MD5 checksum of the content. /// </summary> /// <remarks> /// Computes the MD5 checksum of the MIME content in its canonical /// format and then base64-encodes the result. /// </remarks> /// <returns>The md5sum of the content.</returns> /// <exception cref="System.InvalidOperationException"> /// The <see cref="ContentObject"/> is <c>null</c>. /// </exception> public string ComputeContentMd5() { if (ContentObject == null) { throw new InvalidOperationException("Cannot compute Md5 checksum without a ContentObject."); } using (var stream = ContentObject.Open()) { byte[] checksum; using (var filtered = new FilteredStream(stream)) { if (ContentType.IsMimeType("text", "*")) { filtered.Add(new Unix2DosFilter()); } using (var md5 = MD5.Create()) checksum = md5.ComputeHash(filtered); } var base64 = new Base64Encoder(true); var digest = new byte[base64.EstimateOutputLength(checksum.Length)]; int n = base64.Flush(checksum, 0, checksum.Length, digest); return(Encoding.ASCII.GetString(digest, 0, n)); } }
/* * /// <summary> * /// Return true if this is among the supported AUTH * /// types. * /// </summary> * /// <param name="authtypes"></param> * /// <returns></returns> * public bool IsSupported(SmtpAuthType[] authtypes) * { * log.Debug("CHECKING SUPPORTED TYPES"); * for (int i=0; i<authtypes.Length; i++) * { * log.Debug("CHECKING IF "+authtypes[i]+"="+SmtpAuthType.Login); * if (authtypes[i]==SmtpAuthType.Login) * { * return true; * } * } * return false; * } */ /// <summary> /// Return the 235 response code if valid, otherwise /// return the error. /// </summary> /// <param name="smtpProxy"></param> /// <param name="supportedAuthTypes">the supported auth types</param> /// <returns></returns> public SmtpResponse Negotiate(ISmtpProxy smtpProxy, String[] supportedAuthTypes) { SmtpResponse response = smtpProxy.Auth("login"); //log.Debug("RESPONSE WAS "+response.ResponseCode+" "+response.Message); if (response.ResponseCode != 334) { return(response); } Base64Encoder encoder = Base64Encoder.GetInstance(); response = smtpProxy.SendString(encoder.EncodeString(this.UserName, this._charEncoding)); if (response.ResponseCode != 334) { return(response); } response = smtpProxy.SendString(encoder.EncodeString(this.Password, this._charEncoding)); if (response.ResponseCode != 334) { // here it's an error return(response); } else { // here it's ok. return(response); } }
public void DecodeInPlace() { var list = new List <byte>(); for (int value = 0; value < 256; value++) { list.Add((byte)value); } var testBytes = list.ToArray(); for (int value = 0; value < 256; value++) { var sourceBytes = testBytes.AsSpan().Slice(0, value + 1); var buffer = new byte[Base64Encoder.ComputeEncodedLength(sourceBytes.Length)]; var bufferSlice = buffer.AsSpan(); Base64Encoder.TryEncode(sourceBytes, bufferSlice, out int consumed, out int written); var encodedText = Text.Encoding.ASCII.GetString(bufferSlice.ToArray()); var expectedText = Convert.ToBase64String(testBytes, 0, value + 1); Assert.Equal(expectedText, encodedText); var decodedByteCount = Base64Encoder.DecodeInPlace(bufferSlice); Assert.Equal(sourceBytes.Length, decodedByteCount); for (int i = 0; i < decodedByteCount; i++) { Assert.Equal(sourceBytes[i], buffer[i]); } } }
public static string GetKey(string s1, string s2) { if (!string.IsNullOrEmpty(s1) && !string.IsNullOrEmpty(s2)) { s1 = s1.Replace("-", ""); s2 = s2.Replace("-", ""); if (s1.Length < s2.Length) { var s = s2; s2 = s1; s1 = s; } var b = new byte[s1.Length]; for (var i = 0; i < b.Length; i++) { var k = i % s2.Length; b[i] = (byte)((byte)(s1[i]) ^ (byte)(s2[k])); } var base64 = new Base64Encoder(); var result = new String(base64.Encode(b)); return(result.Left(16)); } else { return(string.Empty); } }
public void Encode(Base64Encoder encoder, byte[] buffer, int index, int count) { ValidateEncode(encoder, buffer, index, count); if (encoder.LeftOverBytesCount > 0) { if (FulfillFromLeftover(encoder, buffer, index, ref count)) { return; } int num2 = Convert.ToBase64CharArray(encoder.LeftOverBytes, 0, 3, encoder.CharsLine, 0); WriteChars(encoder, encoder.CharsLine, 0, num2); } StoreLeftOverBytes(encoder, buffer, index, ref count); int num4 = index + count; int length = Base64CodecConstants.LineSizeInBytes; while (index < num4) { if ((index + length) > num4) { length = num4 - index; } int num6 = Convert.ToBase64CharArray(buffer, index, length, encoder.CharsLine, 0); WriteChars(encoder, encoder.CharsLine, 0, num6); index += length; } }
public async Task EncodeAsync(Base64Encoder encoder, byte[] buffer, int index, int count, CancellationToken cancellationToken) { ValidateEncode(encoder, buffer, index, count); if (encoder.LeftOverBytesCount > 0) { if (FulfillFromLeftover(encoder, buffer, index, ref count)) { return; } int num2 = Convert.ToBase64CharArray(encoder.LeftOverBytes, 0, 3, encoder.CharsLine, 0); await WriteCharsAsync(encoder, encoder.CharsLine, 0, num2, cancellationToken).ConfigureAwait(false); } StoreLeftOverBytes(encoder, buffer, index, ref count); int num4 = index + count; int length = Base64CodecConstants.LineSizeInBytes; while (index < num4) { if (index + length > num4) { length = num4 - index; } int num6 = Convert.ToBase64CharArray(buffer, index, length, encoder.CharsLine, 0); await WriteCharsAsync(encoder, encoder.CharsLine, 0, num6, cancellationToken).ConfigureAwait(false); index += length; } }
public void Basic_decoding_with_known_input_isFinalBlock_false___Done(string input, int expectedWritten) { var sut = new Base64Encoder(); ReadOnlySpan <T> encoded; if (typeof(T) == typeof(byte)) { ReadOnlySpan <byte> tmp = Encoding.ASCII.GetBytes(input); encoded = MemoryMarshal.Cast <byte, T>(tmp); } else if (typeof(T) == typeof(char)) { encoded = MemoryMarshal.Cast <char, T>(input.AsSpan()); // .AsSpan() for net48 } else { throw new NotSupportedException(); // just in case new types are introduced in the future } Span <byte> data = new byte[sut.GetMaxDecodedLength(encoded.Length)]; OperationStatus status = sut.DecodeCore(encoded, data, out int consumed, out int written, isFinalBlock: false); byte[] actualData = data.Slice(0, written).ToArray(); Assert.Multiple(() => { Assert.AreEqual(OperationStatus.Done, status); Assert.AreEqual(input.Length, consumed); Assert.AreEqual(expectedWritten, written); byte[] expectedData = Convert.FromBase64String(input); CollectionAssert.AreEqual(expectedData, actualData); }); }
public void Malformed_input___status_InvalidData(string input, bool isFinalBlock, int expectedConsumed, int expectedWritten) { var sut = new Base64Encoder(); ReadOnlySpan <T> encoded; if (typeof(T) == typeof(byte)) { ReadOnlySpan <byte> tmp = Encoding.ASCII.GetBytes(input); encoded = MemoryMarshal.Cast <byte, T>(tmp); } else if (typeof(T) == typeof(char)) { encoded = MemoryMarshal.Cast <char, T>(input.AsSpan()); // AsSpan() for net48 } else { throw new NotSupportedException(); // just in case new types are introduced in the future } Span <byte> data = new byte[sut.GetMaxDecodedLength(encoded.Length)]; OperationStatus status = sut.DecodeCore(encoded, data, out int consumed, out int written, isFinalBlock); Assert.Multiple(() => { Assert.AreEqual(OperationStatus.InvalidData, status); Assert.AreEqual(expectedConsumed, consumed); Assert.AreEqual(expectedWritten, written); }); }
//Encode a common string to base64 text public static string EncodeString2base(string NeedEncodeStr) { byte[] data = System.Text.UnicodeEncoding.UTF8.GetBytes(NeedEncodeStr); Base64Encoder myEncoder = new Base64Encoder(data); StringBuilder sb = new StringBuilder(); sb.Append(myEncoder.GetEncoded()); return sb.ToString(); }
public static char[] Encode(string input) { //first get the bytes for the original byte[] data=System.Text.UnicodeEncoding.UTF8.GetBytes(input); Base64Encoder myEncoder=new Base64Encoder(data); return myEncoder.GetEncoded(); }
static Encoders() { Base64 = new Base64Encoder(); Base58Check = new Base58CheckEncoder(); Base58 = new Base58Encoder(); Hex = new HexEncoder(); ASCII = new ASCIIEncoder(); }
public static string Encode(byte[] input) { //first get the bytes for the original Base64Encoder myEncoder=new Base64Encoder(input); StringBuilder sb=new StringBuilder(); sb.Append(myEncoder.GetEncoded()); return sb.ToString(); }
public string GetRequest(SAMLLib.Enum.RequestFormat format) { using (StringWriter sw = new StringWriter()) { XmlWriterSettings xws = new XmlWriterSettings(); xws.OmitXmlDeclaration = true; using (XmlWriter xw = XmlWriter.Create(sw, xws)) { xw.WriteStartElement("samlp", "AuthnRequest", "urn:oasis:names:tc:SAML:2.0:protocol"); xw.WriteAttributeString("ID", id); xw.WriteAttributeString("Version", "2.0"); xw.WriteAttributeString("IssueInstant", issue_instant); xw.WriteAttributeString("ProtocolBinding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"); xw.WriteAttributeString("AssertionConsumerServiceURL", SAMLSettings.assertionConsumerServiceUrl); xw.WriteStartElement("saml", "Issuer", "urn:oasis:names:tc:SAML:2.0:assertion"); xw.WriteString(SAMLSettings.issuer); xw.WriteEndElement(); xw.WriteStartElement("samlp", "NameIDPolicy", "urn:oasis:names:tc:SAML:2.0:protocol"); xw.WriteAttributeString("Format", "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"); xw.WriteAttributeString("AllowCreate", "true"); xw.WriteEndElement(); // xw.WriteAttributeString("Format", "urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified"); //xw.WriteStartElement("samlp", "RequestedAuthnContext", "urn:oasis:names:tc:SAML:2.0:protocol"); //xw.WriteAttributeString("Comparison", "exact"); //xw.WriteEndElement(); //xw.WriteStartElement("saml", "AuthnContextClassRef", "urn:oasis:names:tc:SAML:2.0:assertion"); //xw.WriteString("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"); //xw.WriteEndElement(); xw.WriteEndElement(); } if (format == SAMLLib.Enum.RequestFormat.Base64) { Base64Encoder encoder = new Base64Encoder(); return encoder.GetBase64EncodeStr(sw.ToString()); } return sw.ToString(); } }
public string GetLogoutRequest(string nameID, SAMLLib.Enum.RequestFormat format) { using (StringWriter sw = new StringWriter()) { XmlWriterSettings xws = new XmlWriterSettings(); xws.OmitXmlDeclaration = true; using (XmlWriter xw = XmlWriter.Create(sw, xws)) { xw.WriteStartElement("samlp", "LogoutRequest", "urn:oasis:names:tc:SAML:2.0:protocol"); xw.WriteAttributeString("xmlns", "saml", null, "urn:oasis:names:tc:SAML:2.0:assertion"); xw.WriteAttributeString("ID", "_" + System.Guid.NewGuid().ToString()); xw.WriteAttributeString("Version", "2.0"); xw.WriteAttributeString("IssueInstant", DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")); xw.WriteAttributeString("Destination", SAMLSettings.idp_logout_target_url); xw.WriteStartElement("saml", "Issuer", "urn:oasis:names:tc:SAML:2.0:assertion"); xw.WriteString(SAMLSettings.issuer); xw.WriteEndElement(); xw.WriteStartElement("saml", "NameID", null); xw.WriteAttributeString("SPNameQualifier", SAMLSettings.issuer); xw.WriteString(nameID); xw.WriteEndElement(); xw.WriteEndElement(); } if (format == SAMLLib.Enum.RequestFormat.Base64) { Base64Encoder encoder = new Base64Encoder(); return encoder.GetBase64EncodeStr(sw.ToString()); } return sw.ToString(); } }
private void Generate(IWriter output, int depth) { var haveMimeVersion = false; var haveContentEncoding = false; var haveContentType = false; var haveContentDisp = false; var haveMsgId = false; var haveFrom = false; var haveDate = false; var haveHeaders = new bool[11]; byte[] bodyToWrite = this.body; var builder = new MediaTypeBuilder(this.ContentType); string contentDisp = (this.ContentDisposition == null) ? null : this.ContentDisposition.ToString(); var transferEnc = 0; var isMultipart = false; string boundary = String.Empty; if (builder.IsMultipart) { boundary = GenerateBoundary(depth); builder.SetParameter("boundary", boundary); isMultipart = true; } if (!isMultipart) { if (builder.TopLevelType.Equals("message")) { if (builder.SubType.Equals("delivery-status") || builder.SubType.Equals("global-delivery-status")) { bodyToWrite = DowngradeDeliveryStatus(bodyToWrite); } bool msgCanBeUnencoded = CanBeUnencoded(bodyToWrite, depth > 0); if ((builder.SubType.Equals("rfc822") || builder.SubType.Equals( "news")) && !msgCanBeUnencoded) { builder.SetSubType("global"); } else if (builder.SubType.Equals("disposition-notification") && !msgCanBeUnencoded) { builder.SetSubType("global-disposition-notification"); } else if (builder.SubType.Equals("delivery-status") && !msgCanBeUnencoded) { builder.SetSubType("global-delivery-status"); } else if (!msgCanBeUnencoded && !builder.SubType.Equals("global") && !builder.SubType.Equals("global-disposition-notification") && !builder.SubType.Equals("global-delivery-status") && !builder.SubType.Equals("global-headers")) { #if DEBUG throw new MessageDataException("Message body can't be encoded: " + builder.ToString() + ", " + this.ContentType); #else { throw new MessageDataException("Message body can't be encoded"); } #endif } } } string topLevel = builder.TopLevelType; transferEnc = topLevel.Equals("message") || topLevel.Equals("multipart") ? (topLevel.Equals("multipart") || ( !builder.SubType.Equals("global") && !builder.SubType.Equals("global-headers") && !builder.SubType.Equals("global-disposition-notification") && !builder.SubType.Equals("global-delivery-status"))) ? EncodingSevenBit : TransferEncodingToUse( bodyToWrite, depth > 0) : TransferEncodingToUse(bodyToWrite, depth > 0); string encodingString = "7bit"; if (transferEnc == EncodingBase64) { encodingString = "base64"; } else if (transferEnc == EncodingQuotedPrintable) { encodingString = "quoted-printable"; } // Write the header fields for (int i = 0; i < this.headers.Count; i += 2) { string name = this.headers[i]; string value = this.headers[i + 1]; if (name.Equals("content-type")) { if (haveContentType) { // Already outputted, continue continue; } haveContentType = true; value = builder.ToString(); } if (name.Equals("content-disposition")) { if (haveContentDisp || contentDisp == null) { // Already outputted, continue continue; } haveContentDisp = true; value = contentDisp; } else if (name.Equals("content-transfer-encoding")) { if (haveContentEncoding) { // Already outputted, continue continue; } haveContentEncoding = true; value = encodingString; } else if (name.Equals("date")) { if (haveDate) { continue; } haveDate = true; } else if (name.Equals("from")) { if (haveFrom) { // Already outputted, continue continue; } haveFrom = true; } if ( depth > 0 && ( name.Length < 8 || !name.Substring( 0, 8).Equals("content-"))) { // don't generate header fields not starting with "Content-" // in body parts continue; } if (name.Equals("mime-version")) { haveMimeVersion = true; } else if (name.Equals("message-id")) { if (haveMsgId) { // Already outputted, continue continue; } haveMsgId = true; } else { if (ValueHeaderIndices.ContainsKey(name)) { int headerIndex = ValueHeaderIndices[name]; if (headerIndex < 9) { if (haveHeaders[headerIndex]) { // Already outputted, continue continue; } haveHeaders[headerIndex] = true; if (!this.IsValidAddressingField(name)) { value = GenerateAddressList( ParseAddresses(this.GetMultipleHeaders(name))); if (value.Length == 0) { // No addresses, synthesize a field value = this.SynthesizeField(name); } } } if (headerIndex == 9 || headerIndex == 10) { // Resent-From/Resent-Sender, can appear // more than once value = GenerateAddressList(ParseAddresses(value)); if (value.Length == 0) { // No addresses, synthesize a field value = this.SynthesizeField(name); } } } } string rawField = Capitalize(name) + ":" + (StartsWithWhitespace(value) ? String.Empty : " ") + value; if (CanOutputRaw(rawField)) { AppendAscii(output, rawField); if (rawField.IndexOf(": ", StringComparison.Ordinal) < 0) { throw new MessageDataException("No colon+space: " + rawField); } } else if (HasTextToEscape(value)) { string downgraded = HeaderFieldParsers.GetParser(name).DowngradeFieldValue(value); if ( HasTextToEscapeIgnoreEncodedWords( downgraded, 0, downgraded.Length)) { if (name.Equals("message-id") || name.Equals("resent-message-id") || name.Equals( "in-reply-to") || name.Equals("references") || name.Equals( "original-recipient") || name.Equals("final-recipient")) { // Header field still contains invalid characters (such // as non-ASCII characters in 7-bit messages), convert // to a downgraded field name = "downgraded-" + name; downgraded = Rfc2047.EncodeString(ParserUtility.TrimSpaceAndTab(value)); } else { #if DEBUG throw new MessageDataException("Header field still has non-Ascii or controls: " + name + " " + value); #else throw new MessageDataException( "Header field still has non-Ascii or controls"); #endif } } bool haveDquote = downgraded.IndexOf('"') >= 0; var encoder = new WordWrapEncoder(!haveDquote); encoder.AddString(Capitalize(name) + ": " + downgraded); string newValue = encoder.ToString(); AppendAscii(output, newValue); } else { bool haveDquote = value.IndexOf('"') >= 0; var encoder = new WordWrapEncoder(!haveDquote); encoder.AddString(Capitalize(name) + ": " + value); string newValue = encoder.ToString(); AppendAscii(output, newValue); } AppendAscii(output, "\r\n"); } if (!haveFrom && depth == 0) { // Output a synthetic From field if it doesn't // exist and this isn't a body part AppendAscii(output, "From: [email protected]\r\n"); } if (!haveDate && depth == 0) { AppendAscii(output, "Date: "); AppendAscii( output, GetDateString(DateTimeUtilities.GetCurrentLocalTime())); AppendAscii(output, "\r\n"); } if (!haveMsgId && depth == 0) { AppendAscii(output, "Message-ID:\r\n "); AppendAscii(output, this.GenerateMessageID()); AppendAscii(output, "\r\n"); } if (!haveMimeVersion && depth == 0) { AppendAscii(output, "MIME-Version: 1.0\r\n"); } if (!haveContentType) { AppendAscii(output, "Content-Type: " + builder + "\r\n"); } if (!haveContentEncoding) { AppendAscii( output, "Content-Transfer-Encoding: " + encodingString + "\r\n"); } ICharacterEncoder bodyEncoder = null; switch (transferEnc) { case EncodingBase64: bodyEncoder = new Base64Encoder(true, builder.IsText, false); break; case EncodingQuotedPrintable: bodyEncoder = new QuotedPrintableEncoder( builder.IsText ? 2 : 0, false); break; default: bodyEncoder = new IdentityEncoder(); break; } // Write the body AppendAscii(output, "\r\n"); if (!isMultipart) { var index = 0; while (true) { int c = (index >= bodyToWrite.Length) ? -1 : ((int)bodyToWrite[index++]) & 0xff; int count = bodyEncoder.Encode(c, output); if (count == -2) { throw new MessageDataException("encoding error"); } if (count == -1) { break; } } } else { foreach (Message part in this.Parts) { AppendAscii(output, "\r\n--" + boundary + "\r\n"); part.Generate(output, depth + 1); } AppendAscii(output, "\r\n--" + boundary + "--"); } }
/// <include file='doc\XmlTextWriter.uex' path='docs/doc[@for="XmlTextWriter.WriteBase64"]/*' /> /// <devdoc> /// <para>Encodes the specified binary bytes as base64 and writes out /// the resulting text.</para> /// </devdoc> public override void WriteBase64(byte[] buffer, int index, int count) { if (!this.flush) { AutoComplete(Token.Content); } this.flush = true; // No need for us to explicitly validate the args. The StreamWriter will do // it for us. if (null == this.base64Encoder) { this.base64Encoder = new Base64Encoder(); } WriteRaw(this.base64Encoder.EncodeToBase64(buffer, index, count)); }
/// <summary> /// 字符串Base64编码 /// </summary> /// <param name="srcString">需编码字符串</param> /// <param name="encoding">系统字符编码方式</param> /// <returns></returns> public static string Base64Encode(string srcString, System.Text.Encoding encoding) { if (null == srcString || string.Empty == srcString) return string.Empty; string result = string.Empty; Base64Encoder ec = new Base64Encoder(); result = ec.GetEncoded(encoding.GetBytes(srcString)); return result; }
public void GetEncodedTest() { byte[] input = {64, 65, 66}; var target = new Base64Encoder(input); char[] expected = {'Q', 'E', 'F', 'C'}; char[] actual = target.GetEncoded(); CollectionAssert.AreEqual(expected, actual, "Kfd.Tools.Base64Encoder.GetEncoded did not return the expected value."); }
public void ConstructorTest() { byte[] input = {64, 65, 66}; var target = new Base64Encoder(input); Assert.AreEqual(input, target.GetSource()); }
/// <summary> /// Computes the MD5 checksum of the content. /// </summary> /// <remarks> /// Computes the MD5 checksum of the MIME content in its canonical /// format and then base64-encodes the result. /// </remarks> /// <returns>The md5sum of the content.</returns> /// <exception cref="System.InvalidOperationException"> /// The <see cref="ContentObject"/> is <c>null</c>. /// </exception> public string ComputeContentMd5 () { if (ContentObject == null) throw new InvalidOperationException ("Cannot compute Md5 checksum without a ContentObject."); using (var stream = ContentObject.Open ()) { byte[] checksum; using (var filtered = new FilteredStream (stream)) { if (ContentType.Matches ("text", "*")) filtered.Add (new Unix2DosFilter ()); using (var md5 = MD5.Create ()) checksum = md5.ComputeHash (filtered); } var base64 = new Base64Encoder (true); var digest = new byte[base64.EstimateOutputLength (checksum.Length)]; int n = base64.Flush (checksum, 0, checksum.Length, digest); return Encoding.ASCII.GetString (digest, 0, n); } }