尝试将字符串转换为 HMACSHA1 .NET 的 base64 时出错

Getting an error when trying to convert a string to base64 for HMACSHA1 .NET

我正在尝试生成签名并使用 HMACSHA1 对其进行签名。我不断收到错误提示,提示输入不是有效的 Base-64 字符串。

这是代码

string authSecret = "dBV2PdhYMnruSMb";
string signSession = "application_id=1234&auth_key=aDRceQyTXSYEdJU&nonce=4567779998&timestamp=1623103648&user[login]=johnWick@mail.com&user[password]=12345678";

//convert the session signature string to a byte array
byte[] signature = Encoding.UTF8.GetBytes(signSession);

// converting authsecret to a byte array
var apiKey = Convert.FromBase64String(authSecret);

// Generate a HMACSHA1 signature
using(HMACSHA1 hmac = new HMACSHA1(apiKey))
{
    byte[] signatureBytes = hmac.ComputeHash(signature);
    string base64Signature = Convert.ToBase64String(signatureBytes);
    session.Signature = base64Signature;
}
// this is the line that keeps throwing an error
var apiKey = Convert.FromBase64String(authSecret);

这里是错误信息

System.FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
   at System.Convert.FromBase64CharPtr(Char* inputPtr, Int32 inputLength)
   at System.Convert.FromBase64String(String s)
   at ChatboxApi.Utilities.ConnectyCubeUtils.GenerateSessionParams(User user) in C:\Users\Owner\Documents\App Projects\React_Projects\chatboxApi\ChatboxApi\Utilities\ConnectyCubeUtils.cs:line 110
   at ChatboxApi.Services.AuthService.AuthService.CreateSession(User user) in C:\Users\Owner\Documents\App Projects\React_Projects\chatboxApi\ChatboxApi\Services\AuthService\AuthService.cs:line 17
   at ChatboxApi.Controllers.AuthController.SignUp(User user) in C:\Users\Owner\Documents\App Projects\React_Projects\chatboxApi\ChatboxApi\Controllers\AuthController.cs:line 22
   at lambda_method6(Closure , Object )
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Base64 字符串的长度始终是 4 个字符的倍数。你的是15个字符,所以它需要一个填充字符才能达到16个。

如果在末尾加一个=变成dBV2PdhYMnruSMb=就可以解码了

您应该调查为什么您的字符串末尾缺少填充。

我终于弄明白我做错了什么了。我需要将输出编码为十六进制而不是 bas64。

string signSession = "application_id=3610&auth_key=aDRceQyTXSYEdJU&nonce=6304033672&timestamp=1623098533&user[login]=john@mail.com&user[password]=123456789";

string key = "dBV2PdhYMnruSMb";

//convert the session signature string to a byte array
byte[] signature = Encoding.UTF8.GetBytes(signSession);

var apiKey = Encoding.UTF8.GetBytes(key);

//Generate a HMACSHA1 signature
using (HMACSHA1 hmac = new HMACSHA1(apiKey))
{
    byte[] signatureBytes = hmac.ComputeHash(signature);
    string hexSignature = BitConverter.ToString(signatureBytes).ToLowerInvariant().Replace("-", "");
    Console.WriteLine(hexSignature);
    session.Signature = hexSignature;
}

这里有一个link的解决方案