Search code examples
c#.netasp.net-corehmacsha1

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


I am trying to generate a signature and sign it using HMACSHA1. I keep getting an error saying that the input is not a valid Base-64 string.

Here is the code

string authSecret = "dBV2PdhYMnruSMb";
string signSession = "application_id=1234&auth_key=aDRceQyTXSYEdJU&nonce=4567779998&timestamp=1623103648&user[login][email protected]&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);

And here is the error message

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)

Solution

  • I finally figured out what I was doing wrong. I need to encode the output to hex instead of bas64.

    string signSession = "application_id=3610&auth_key=aDRceQyTXSYEdJU&nonce=6304033672&timestamp=1623098533&user[login][email protected]&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;
    }
    

    Here is a link to the solution

    https://stackoverflow.com/a/67882962/13009779