首页 > 解决方案 > blazor wasm 使用 Cryptography.Algorithms 错误

问题描述

   Unhandled exception rendering component: System.Security.Cryptography.Algorithms is not supported on this platform.
System.PlatformNotSupportedException: System.Security.Cryptography.Algorithms is not supported on this platform.
   at System.Security.Cryptography.Aes.Create()
   at AutoTradingWebAppV2.Helper.Crypto.Encryptstring(String text, String keyString) in D:\Web\AutoTradingApp-BWASM\AutoTradingWebAppV2\Helper\Crypto.cs:line 12
   at AutoTradingWebAppV2.Handler.CustomUpbitAuthHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in D:\Web\AutoTradingApp-BWASM\AutoTradingWebAppV2\Handler\CustomUpbitAuthHandler.cs:line 31
   at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.<>n__0(HttpRequestMessage request, CancellationToken cancellationToken)
   at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
   at System.Net.Http.Json.HttpClientJsonExtensions.<GetFromJsonAsyncCore>d__13`1[[System.Collections.Generic.IEnumerable`1[[DTOs.AccountDTO, DTOs, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()
   at Services.UpbitService.GetAccounts() in D:\Web\AutoTradingApp-BWASM\Services\UpbitService.cs:line 31
   at AppViewModels.UpbitTradingViewModel.GetAccounts() in D:\Web\AutoTradingApp-BWASM\AppViewModels\UpbitTradingViewModel.cs:line 156
   at AutoTradingWebAppV2.Pages.TradingInfoBoard.TryConnectToWebsocket() in D:\Web\AutoTradingApp-BWASM\AutoTradingWebAppV2\Pages\TradingInfoBoard.razor.cs:line 48
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)

https://docs.microsoft.com/en-us/dotnet/core/compatibility/cryptography/5.0/cryptography-apis-not-supported-on-blazor-webassembly

那么如何在 blazor 创建 JWT 呢?或使用AES?

如何修复它或他们何时更新 blazor?

            var jwtToken = JwtBuilder.Create()
                                     .WithAlgorithm(new HMACSHA256Algorithm())
                                     .WithSecret(SecretKey)
                                     .AddClaim("access_key",AccessKey)
                                     .AddClaim("nonce", Guid.NewGuid().ToString())
                                     .Encode();
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", jwtToken);

我将此代码添加到 httpclient 处理程序,但不能在 blazor 上使用此代码...

+

这是开放的 API 示例代码。我必须在客户端创建 JWT 令牌并向 api 发送请求

C#代码。

public class OpenAPISample {
    public static void Main() {
        var payload = new JwtPayload
        {
            { "access_key", "Access Key" },
            { "nonce", Guid.NewGuid().ToString() },
            { "query_hash", queryHash },
            { "query_hash_alg", "SHA512" }
        };

        byte[] keyBytes = Encoding.Default.GetBytes("Secret Key");
        var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(keyBytes);
        var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, "HS256");
        var header = new JwtHeader(credentials);
        var secToken = new JwtSecurityToken(header, payload);

        var jwtToken = new JwtSecurityTokenHandler().WriteToken(secToken);
        var authorizationToken = "Bearer " + jwtToken;
    }
}

JAVA 示例代码(网站上没有 C# 代码)

 public static void main(String[] args) {
        String accessKey = System.getenv("OPEN_API_ACCESS_KEY");
        String secretKey = System.getenv("OPEN_API_SECRET_KEY");
        String serverUrl = System.getenv("OPEN_API_SERVER_URL");

        Algorithm algorithm = Algorithm.HMAC256(secretKey);
        String jwtToken = JWT.create()
                .withClaim("access_key", accessKey)
                .withClaim("nonce", UUID.randomUUID().toString())
                .sign(algorithm);

        String authenticationToken = "Bearer " + jwtToken;

        try {
            HttpClient client = HttpClientBuilder.create().build();
            HttpGet request = new HttpGet(serverUrl + "/v1/accounts");
            request.setHeader("Content-Type", "application/json");
            request.addHeader("Authorization", authenticationToken);

            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();

            System.out.println(EntityUtils.toString(entity, "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

标签: cryptographyblazor-webassembly

解决方案


如何在 blazor 创建 JWT?

在服务器上创建一个 JWT。并由客户端应用程序使用。

由于技术原因,API 不受支持,但您不应该在客户端上使用它们。您的客户端无法隐藏任何凭据,它只会提供错误的安全性。

这也适用于 AES。你不能隐藏钥匙。


他们只给我访问密钥和密钥,并要求我制作 jwt

您应该在自己的服务器上执行此操作。您的 SPA 客户端调用调用 Open API 服务器的服务器。

确保密钥永远不会出现在 SPA 客户端中。


推荐阅读