Unable to create KeyedHashAlgorithm

E:\0_RG\Code\RG6.PF\rg3-pf\RG3.PF.Utilities\JwtTokenUtil.cs

the key size must be greater than: ‘256’ bits, key has ‘176’ bits. (Parameter ‘keyBytes’)

无法为算法“”创建KeyedHashAlgorithmhttp://www.w3.org/2001/04/xmldsig-more#hmac-sha256',密钥大小必须大于:'256'位,密钥有'176'位。(参数“keyBytes”)

http://www.w3.org/2001/04/xmldsig-more#hmac-sha256



2023-06-05 17:53:05 WARN RG3.BO.Core.Provider.LogConsoleAbstractProvider pushpull.login.services.process/6/IDX10720: Unable to create KeyedHashAlgorithm for algorithm 'http://www.w3.org/2001/04/xmldsig-more#hmac-sha256', the key size must be greater than: '256' bits, key has '176' bits. (Parameter 'keyBytes')
2023-06-05 17:53:05 WARN RG3.BO.Core.Provider.LogConsoleAbstractProvider {"LastDate":null,"LastDateUtc":null,"Level":0,"WebSoketId":null,"Query":null,"ContentType":null,"IsPushDate":null,"TableName":null,"Queues":null,"BulkLocal":false,"BulkTempCsv":null,"BulkDoMethod":null,"SubPullType":null,"CacheSource":"data","Content":"登录失败","MenuId":null,"UserId":null,"ObjectId":null,"AppId":"0","ParentModuleKey":null,"FunName":null,"ColumnField":null,"DimCacheKey":null,"DatabaseType":null,"VerifyApi":null,"XfilterAreaCode":null,"XfilterDepId":null,"XfilterRoleId":null,"Bridge":null,"NoValidate":null,"ClientUserIp":"127.0.0.1","FromLogin":true,"CacheKey":"smdcmJJJJbo-user","SubMkey":null,"SubBeforeKey":null,"Ops":null,"Params":"{\"responseNoNeed\":\"verifyCode,verifyGuid,\",\"unionIdField\":null,\"webSoketId\":null,\"loginType\":0,\"userName\":\"ckguest\",\"telephone\":null,\"idCard\":null,\"email\":null,\"qq\":null,\"password\":\"3AFCEE90306AB916CE0DA436BA81F6AF\",\"verifyCode\":\"hbli\",\"verifySms\":null,\"verifySmsGuid\":null,\"verifyGuid\":\"481c64b7-103d-4e7e-9353-0f7a7ce37d58\",\"remember\":null,\"isAcount\":false,\"openCode\":null,\"openId\":null,\"openMKey\":null,\"openField\":null,\"openUser\":null,\"cacheKeyHt\":null,\"verifyOpnUser\":null}","Process":"loginfail","Body":"{\"logId\":\"4186212283900235776\",\"logType\":null,\"logContent\":null,\"logTime\":\"2023-06-05T17:53:05\",\"createId\":null,\"logJson\":null,\"logPath\":\"/bo/api/v3/auth/login\",\"clientIp\":\"127.0.0.1\",\"queryString\":\"?ignore=true&_nodejs=common-data\",\"ownerId\":\"smdcm\",\"filterAreaCode\":null,\"fromAppid\":null,\"sysId\":null}","UserName":null,"VirPath":null,"ShredConfig":null,"PopedomVerify":null,"ResponseNoNeed":"verifyCode,verifyGuid,","OpsDataType":1,"WsDataType":1,"OpsValues":null,"TableNames":null,"PushMethod":0,"Step":6,"Steps":0,"Message":null,"Cap":true,"FromOpRmt":0,"PushMapperFieldIdx":null,"RequestModuleType":0,"Ids":null,"MapperField":null,"UniqueId":null,"UniqueField":null,"UniqueName":null,"ConnName":null,"NodeJs":null,"SysId":null,"OwnerId":"smdcm","TenantId":"0","ModuleKey":"bo-user","ReponseField":null,"ChannelReceiver":"0","ChannelRule":"0","FromTraceId":"LoginController.cs"}
2023-06-05 17:53:05 EROR RG3.PF.Abstractions.Middlewares.GlobalExceptionMiddleware Exception of type 'RG3.PF.Abstractions.Exceptions.BizException' was thrown.
2023-06-05 17:53:05 EROR RG3.PF.Abstractions.Middlewares.GlobalExceptionMiddleware RG3.PF.Abstractions.Exceptions.BizException: Exception of type 'RG3.PF.Abstractions.Exceptions.BizException' was thrown.
   at RG3.BO.Auth.Controller.LoginController.Post(UserLoginData loginData) in C:\0_RG\Code\RG6.PF\rg3-pf\RG3.BO.Auth\Controller\LoginController.cs:line 164
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(ActionContext actionContext, 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.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)

签名key字节数必须和签名方法一致,比如256,就是32位,如32个拼音

E:\0_RG\Code\RG6.PF\rg3-pf\RG3.Web.Host.PaaS\Config\AppAuth\smdcm\app_security.json

调整里面 symmetricSecurityKey
1、避免配置文件大范围修改,字符不足,直接代码里面补齐0


  public static string SetUserToJWT(Abstractions.Entity.SecurityToken securityToken, TokenUser tokenUser, DateTime expires)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            //var key = Encoding.ASCII.GetBytes(_configuration[TokenConst.SymmetricSecurityKey]);
            //key 必须32位,如256字节, 同签名 HmacSha256Signature 一致
            var key = Encoding.ASCII.GetBytes(securityToken.SymmetricSecurityKey.PadRight(32, '0'));
            var tokenDescriptor = new SecurityTokenDescriptor();
            tokenDescriptor.Expires = expires;
            tokenDescriptor.SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature);
            if (string.IsNullOrEmpty(tokenUser.ClientId))
            {
                tokenUser.ClientId = tokenUser.UserId ?? "0";
            }
            tokenDescriptor.Subject = new ClaimsIdentity(new Claim[] {          
                new Claim(JwtClaimTypes.Issuer,securityToken.Issuer),
                new Claim(JwtClaimTypes.Audience,securityToken.Audience),
                new Claim(JwtClaimTypes.Id,(tokenUser.UserId??"0").ToString()),
                new Claim(JwtClaimTypes.Name,(tokenUser.UserName??string.Empty).ToString()),
                new Claim(JwtClaimTypes.ClientId,tokenUser.ClientId),
                new Claim(JwtClaimTypesExtend.Expires,expires.ToString()),
                new Claim(JwtClaimTypesExtend.OpenId,tokenUser.OpenId??string.Empty),
                new Claim(JwtClaimTypesExtend.WbId,tokenUser.WbId??string.Empty),
                new Claim(JwtClaimTypesExtend.WxOpenId,tokenUser.WxOpenId??string.Empty),
                new Claim(JwtClaimTypesExtend.WxUnionId,tokenUser.WxUnionId??string.Empty),
                new Claim(JwtClaimTypesExtend.Telephone,tokenUser.Telephone??string.Empty),
                new Claim(JwtClaimTypesExtend.PushName,tokenUser.PushName??string.Empty),
                new Claim(JwtClaimTypesExtend.HeadIcon,tokenUser.HeadIcon??string.Empty),
                new Claim(JwtClaimTypesExtend.AppId,string.Join(CommonConst.COMMA.ToString(),(tokenUser.AppId??new List<string>()).ToArray() )),
                new Claim(JwtClaimTypesExtend.UserGroupId,string.Join(CommonConst.COMMA.ToString(),(tokenUser.UserGroupId??new List<string>()).ToArray() )),
                new Claim(JwtClaimTypesExtend.DepId,string.Join(CommonConst.COMMA.ToString(),(tokenUser.DepId??new List<string>()).ToArray() )),
                new Claim(JwtClaimTypesExtend.SysId,string.Join(CommonConst.COMMA.ToString(),(tokenUser.SysId??new List<string>()).ToArray() )),
                new Claim(JwtClaimTypesExtend.MergeUserId,string.Join(CommonConst.COMMA.ToString(),(tokenUser.MergeUserId??new List<string>()).ToArray() )),
                new Claim(JwtClaimTypesExtend.AreaCode,string.Join(CommonConst.COMMA.ToString(),(tokenUser.AreaCode??new List<string>()).ToArray() )),
                new Claim(JwtClaimTypesExtend.RoleId,string.Join(CommonConst.COMMA.ToString(),(tokenUser.RoleId??new List<string>()).ToArray() )),
                new Claim(JwtClaimTypesExtend.Developer,(tokenUser.Developer??0).ToString())
            });
            var token = tokenHandler.CreateToken(tokenDescriptor);

            var accessToken = tokenHandler.WriteToken(token);
            return accessToken;
        }

A:签名方式调整

https://www.coder.work/article/7915703

在 .NET Core 7.0 中使用http://www.w3.org/2001/04/xmldsig-more#hmac-sha256签名方法时报错,通常是因为:

  1. .NET Core 7.0 不再内置支持 XML Signature 标准,需要安装NuGet包 System.Security.Cryptography.Xml来支持。
  2. HMACSHA256 算法需要安装NuGet包 System.Security.Cryptography.Algorithms来支持。
    要解决这个错误,可以:
1. 安装System.Security.Cryptography.Xml NuGet包:
dotnet add package System.Security.Cryptography.Xml
2. 安装System.Security.Cryptography.Algorithms NuGet包:
dotnet add package System.Security.Cryptography.Algorithms
  1. 引用命名空间:
csharp
using System.Security.Cryptography;
using System.Security.Cryptography.Xml; 
  1. 注册HMACSHA256签名方法:
csharp
XmlDsigHMACSHA256UrlSigningMethod.Register(); 
  1. 计算HMACSHA256签名:
csharp
HMACSHA256 hmac = new HMACSHA256(key);
byte[] signature = hmac.ComputeHash(data);
string signatureBase64 = Convert.ToBase64String(signature);
  1. 在XML文档中指定http://www.w3.org/2001/04/xmldsig-more#hmac-sha256 作为签名方法,signatureBase64作为:
    xml
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
  <SignedInfo>
    ...
    <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"></SignatureMethod>
  </SignedInfo>  
 <SignatureValue>signatureBase64</SignatureValue>
</Signature>
文档更新时间: 2023-06-05 22:45   作者:admin