public void Unwrap2() { var kwp = new EcdhKeyWrapper(_bobKey, EncryptionAlgorithm.A128CbcHS256, KeyManagementAlgorithm.EcdhEsA128KW); byte[] wrappedKey = new byte[kwp.GetKeyWrapSize()]; var header = new JwtHeader { { JwtHeaderParameterNames.Apu, Utf8.GetString(Base64Url.Encode("Alice")) }, { JwtHeaderParameterNames.Apv, Utf8.GetString(Base64Url.Encode("Bob")) } }; kwp.WrapKey(_aliceKey, header, wrappedKey); var kuwp = new EcdhKeyUnwrapper(_bobKey, EncryptionAlgorithm.A128CbcHS256, KeyManagementAlgorithm.EcdhEsA128KW); var apu = Encoding.UTF8.GetString(Base64Url.Encode("Alice"));; var apv = Encoding.UTF8.GetString(Base64Url.Encode("Bob")); header.TryGetValue(JwtHeaderParameterNames.Epk, out var epkElement); var epk = (Jwk)epkElement.Value; var parsed = JwtHeaderDocument.TryParseHeader(Encoding.UTF8.GetBytes($"{{\"apu\":\"{apu}\",\"apv\":\"{apv}\",\"epk\":{epk}}}"), null, TokenValidationPolicy.NoValidation, out var jwtHeader, out var error); Assert.True(parsed); byte[] unwrappedKey = new byte[kuwp.GetKeyUnwrapSize(wrappedKey.Length)]; var unwrapped = kuwp.TryUnwrapKey(wrappedKey, unwrappedKey, jwtHeader, out int bytesWritten); Assert.True(unwrapped); }
public static string ReadUtf8StringFromPointer(IntPtr lpstr) { if (lpstr == IntPtr.Zero || lpstr == new IntPtr(-1)) { return(null); } var byteCount = 0; unsafe { var p = (byte *)lpstr.ToPointer(); while (*p != 0) { byteCount += 1; p += 1; } } if (byteCount == 0) { return(string.Empty); } var strBuffer = new byte[byteCount]; Marshal.Copy(lpstr, strBuffer, 0, byteCount); var str = Utf8.GetString(strBuffer); return(str); }
/// <inheritsdoc /> public override SymmetricJwk WrapKey(Jwk?staticKey, JwtHeader header, Span <byte> destination) { if (header is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.header); } var contentEncryptionKey = CreateSymmetricKey(EncryptionAlgorithm, (SymmetricJwk?)staticKey); Span <byte> buffer = stackalloc byte[_saltSizeInBytes + 1 + _algorithmNameLength]; _saltGenerator.Generate(buffer.Slice(_algorithmNameLength + 1)); buffer[_algorithmNameLength] = 0x00; _algorithm.EncodedUtf8Bytes.CopyTo(buffer); Span <byte> derivedKey = stackalloc byte[_keySizeInBytes]; Pbkdf2.DeriveKey(_password, buffer, _hashAlgorithm, _iterationCount, derivedKey); Span <byte> salt = buffer.Slice(_algorithmNameLength + 1, _saltSizeInBytes); Span <byte> b64Salt = stackalloc byte[Base64Url.GetArraySizeRequiredToEncode(salt.Length)]; Base64Url.Encode(salt, b64Salt); header.Add(JwtHeaderParameterNames.P2s, Utf8.GetString(b64Salt)); header.Add(JwtHeaderParameterNames.P2c, _iterationCount); using var keyWrapper = new AesKeyWrapper(derivedKey, EncryptionAlgorithm, _keyManagementAlgorithm); return(keyWrapper.WrapKey(contentEncryptionKey, header, destination)); }
/// <inheritsdoc /> public override SymmetricJwk WrapKey(Jwk?staticKey, JwtHeader header, Span <byte> destination) { var cek = CreateSymmetricKey(EncryptionAlgorithm, (SymmetricJwk?)staticKey); Span <byte> nonce = stackalloc byte[IVSize]; RandomNumberGenerator.Fill(nonce); Span <byte> tag = stackalloc byte[TagSize]; using (var aesGcm = new AesGcm(_key.K)) { var keyBytes = cek.AsSpan(); if (destination.Length > keyBytes.Length) { destination = destination.Slice(0, keyBytes.Length); } aesGcm.Encrypt(nonce, keyBytes, destination, tag); Span <byte> nonceB64 = stackalloc byte[IVB64Size]; Base64Url.Encode(nonce, nonceB64); header.Add(JwtHeaderParameterNames.IV, Utf8.GetString(nonceB64)); Span <byte> tagB64 = stackalloc byte[TagB64Size]; Base64Url.Encode(tag, tagB64); header.Add(JwtHeaderParameterNames.Tag, Utf8.GetString(tagB64)); } return(cek); }
/// <inheritsdoc /> public override SymmetricJwk WrapKey(Jwk?staticKey, JwtHeader header, Span <byte> destination) { if (header is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.header); } var contentEncryptionKey = CreateSymmetricKey(EncryptionAlgorithm, (SymmetricJwk?)staticKey); int bufferSize = _saltSizeInBytes + _algorithmNameLength + 1; byte[]? bufferToReturn = null; Span <byte> buffer = bufferSize > Pbkdf2.SaltSizeThreshold + 18 + 1 // 18 = max alg name length ? (bufferToReturn = ArrayPool <byte> .Shared.Rent(bufferSize)) : stackalloc byte[Pbkdf2.SaltSizeThreshold + 18 + 1]; buffer = buffer.Slice(0, bufferSize); _saltGenerator.Generate(buffer.Slice(_algorithmNameLength + 1)); buffer[_algorithmNameLength] = 0x00; _algorithm.EncodedUtf8Bytes.CopyTo(buffer); Span <byte> derivedKey = stackalloc byte[KeySizeThreshold].Slice(0, _keySizeInBytes); Pbkdf2.DeriveKey(_password, buffer, _hashAlgorithm, _iterationCount, derivedKey); Span <byte> salt = buffer.Slice(_algorithmNameLength + 1, _saltSizeInBytes); int saltLengthB64 = Base64Url.GetArraySizeRequiredToEncode(salt.Length); byte[]? arrayToReturn = null; Span <byte> b64Salt = saltLengthB64 > Pbkdf2.SaltSizeThreshold * 4 / 3 ? (arrayToReturn = ArrayPool <byte> .Shared.Rent(saltLengthB64)) : stackalloc byte[Pbkdf2.SaltSizeThreshold * 4 / 3]; try { int length = Base64Url.Encode(salt, b64Salt); header.Add(JwtHeaderParameterNames.P2s, Utf8.GetString(b64Salt.Slice(0, saltLengthB64))); header.Add(JwtHeaderParameterNames.P2c, _iterationCount); using var keyWrapper = new AesKeyWrapper(derivedKey, EncryptionAlgorithm, _keyManagementAlgorithm); return(keyWrapper.WrapKey(contentEncryptionKey, header, destination)); } finally { if (bufferToReturn != null) { ArrayPool <byte> .Shared.Return(bufferToReturn); } if (arrayToReturn != null) { ArrayPool <byte> .Shared.Return(arrayToReturn); } } }
public virtual void TryParse_Success(T expected) { var parsed = TryParse(expected.Utf8Name, out var algorithm); Assert.True(parsed); Assert.NotNull(algorithm); Assert.Same(expected, algorithm); parsed = TryParse(Utf8.GetString(expected.Utf8Name), out var algorithm2); Assert.True(parsed); Assert.NotNull(algorithm2); Assert.Same(expected, algorithm2); }
internal static string SendWebhook(DiscordWebhook discordWebHook, string url) { if (!string.IsNullOrEmpty(url) && Uri.TryCreate(url, UriKind.Absolute, out Uri uri)) { byte[] jsonData = Utf8Json.JsonSerializer.Serialize(discordWebHook); Debug("WebHook sent: \n" + Utf8.GetString(jsonData)); return(WebPost(uri, jsonData)); } else { return("Failed creating URI of WebHook link: " + url); } }
public void Wrap_Rfc7518_Appendix_C() { var kwp = new EcdhKeyWrapper(_bobKey, EncryptionAlgorithm.A128Gcm, KeyManagementAlgorithm.EcdhEs); var header = new JwtHeader { { JwtHeaderParameterNames.Apu, Utf8.GetString(Base64Url.Encode("Alice")) }, { JwtHeaderParameterNames.Apv, Utf8.GetString(Base64Url.Encode("Bob")) } }; Span <byte> wrappedKey = stackalloc byte[kwp.GetKeyWrapSize()]; var cek = kwp.WrapKey(_aliceKey, header, wrappedKey); var expected = new byte[] { 86, 170, 141, 234, 248, 35, 109, 32, 92, 34, 40, 205, 113, 167, 16, 26 }; Assert.Equal(expected, cek.AsSpan().ToArray()); }
public override string ToString() { return(Utf8.GetString(_data)); }
HtmlElement RenderImage() { var container = Document.CreateElement("div"); string mimetype = null; switch (image.Format) { case ImageFormat.Png: mimetype = "image/png"; break; case ImageFormat.Jpeg: mimetype = "image/jpeg"; break; case ImageFormat.Gif: mimetype = "image/gif"; break; case ImageFormat.Svg: mimetype = "image/svg+xml"; break; case ImageFormat.Unknown: mimetype = "image"; break; case ImageFormat.Uri: break; default: var errorElem = Document.CreateElement( "div", @class: "renderer-image-error", innerText: $"Unable to render ImageFormat.{image.Format}"); container.AppendChild(errorElem); return(container); } var imageContainer = Document.CreateElement("div", "renderer-image-container"); var imageElem = Document.CreateElement("img"); if (image.Width > 0) { imageElem.SetAttribute("style", $"width: {image.Width}px !important"); } // Right now we only care about image load completion to refocus the input, which is only // necessary if the image is the root item, and if we are on Mac, where image loading // is fully asynchronous. if (RenderState.ParentState == null && InteractiveInstallation.Default.IsMac) { EventListener onLoadListener = null; onLoadListener = imageElem.AddEventListener("load", evnt => { evnt.Target.RemoveEventListener("load", onLoadListener); Context.NotifyAsyncRenderComplete(RenderState); }); } if (image.Format == ImageFormat.Uri) { imageElem.SetAttribute("src", Utf8.GetString(image.Data)); } else { imageElem.SetAttribute("src", $"data:{mimetype};base64,{Convert.ToBase64String (image.Data)}"); } imageContainer.AppendChild(imageElem); var backgroundImageDiv = Document.CreateElement( "div", "renderer-image-background-image", $"width: {image.Width}px !important;"); imageContainer.AppendChild(backgroundImageDiv); var backgroundColorDiv = Document.CreateElement( "div", "renderer-image-background-color", $"width: {image.Width}px !important;"); imageContainer.AppendChild(backgroundColorDiv); // TODO: Reimplement with hover menu //if (RenderState.ParentState == null) { // var sliderElem = (HtmlInputElement)Document.CreateElement ("input"); // sliderElem.Value = "0"; // sliderElem.Type = "range"; // container.AppendChild (sliderElem); // Action<Event> slideHandler = evnt => { // double val; // if (!Double.TryParse (sliderElem.Value, out val)) // return; // var opacity = (val / 100.0).ToString (); // backgroundImageDiv.Style.SetProperty ("opacity", opacity); // backgroundColorDiv.Style.SetProperty ("opacity", opacity); // }; // sliderElem.AddEventListener ("input", slideHandler); // // "input" is correct for live sliding events, but IE incorrectly implements using "change" // sliderElem.AddEventListener ("change", slideHandler); //} container.AppendChild(imageContainer); return(container); }