GVKun编程网logo

Java Signature.verify中的SignatureException结果:签名编码错误IOException引起:序列标签错误

23

对于想了解JavaSignature.verify中的SignatureException结果:签名编码错误IOException引起:序列标签错误的读者,本文将是一篇不可错过的文章,并且为您提供关于

对于想了解Java Signature.verify中的SignatureException结果:签名编码错误IOException引起:序列标签错误的读者,本文将是一篇不可错过的文章,并且为您提供关于BeanDefinitionStoreException, IOException 错误、c# – 为什么我得到SecurityTokenSignatureKeyNotFoundException?、com.amazonaws.mturk.service.exception.ValidationException的实例源码、EGit:执行失败(SignatureException):签名编码错误的有价值信息。

本文目录一览:

Java Signature.verify中的SignatureException结果:签名编码错误IOException引起:序列标签错误

Java Signature.verify中的SignatureException结果:签名编码错误IOException引起:序列标签错误

首先,这不是一个重复的问题,因为大多数人从缺少“ — BEGIN RSA CERTIFICATE–”行的证书创建公钥时报告此异常。

我想要做的要点是1.使用SHA1withRSA算法(RSA密钥为1024位)在JCOP智能卡上签名50Byte消息。2.将签名从智能卡导出到服务器。3.验证服务器上的签名。

智能卡上的代码段以创建签名。关键是我正在使用Java Card中的算法Signature.ALG_RSA_SHA_PKCS1创建签名。

private void setcustccid(APDU apdu) {    byte[] buffer = apdu.getBuffer();    if (buffer[ISO7816.OFFSET_LC] != (byte)24) {      ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);    }    else {      short bytesLeft = (short) (buffer[ISO7816.OFFSET_LC] & 0x00FF);      short readCount = apdu.setIncomingAndReceive();      if (readCount < bytesLeft) {        ISOException.throwIt(ISO7816.SW_BYTES_REMAINING_00);      }      try {                  Signature signature = Signature.getInstance(Signature.ALG_RSA_SHA_PKCS1, false);        signature.init(privKey, Signature.MODE_SIGN);        Util.arrayCopy(buffer, (short)buffer[ISO7816.OFFSET_CDATA], tempStorage, (short) 0, (byte)24);        Util.arrayCopy(transactionHistory, (short)0, tempStorage, (short)24, (byte)30);      }       catch (Exception ex) {        ISOException.throwIt(ISO7816.SW_BYTES_REMAINING_00);      }      signature.sign(tempStorage, (short)0, (short)50, finalEncryptedMsg, (short)0);    }    }

服务器端的代码段试图验证从抛出异常的Java智能卡导出的签名。这里的重点是我在服务器端使用Signature.getInstance(“
SHA1withRSA”)。我正在对签名的消息进行密码解密,只是为了确认生成的公钥是否正常工作。

modulusString = new BigInteger(1, rsaModulus);exponentString = new BigInteger(1, rsaExponent);RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulusString, exponentString);KeyFactory factor = KeyFactory.getInstance("RSA"); PublicKey publicKey = (RSAPublicKey) factor.generatePublic(keySpec);rsaCipher = Cipher.getInstance("RSA");rsaCipher.init(Cipher.DECRYPT_MODE, publicKey);signature = Signature.getInstance("SHA1withRSA");signature.initVerify(publicKey);signature.update(resultBytes);signature.verify(finalEncryptedMsg);tempStorage = rsaCipher.doFinal(finalEncryptedMsg);System.out.println("Decrypted Length = " + tempStorage.length);

例外发生在signature.verify()上。另一个线程引用了相同的异常,但是解决方案是将Bouncy
Castle添加为Signature.getInstance()中的提供者。不确定为什么要要求Bouncy Castle进行签名验证。

任何帮助将不胜感激。如果您需要更多代码来识别问题,请告诉我。

java.security.SignatureException: Signature encoding error    at sun.security.rsa.RSASignature.engineVerify(Unknown Source)    at java.security.Signature$Delegate.engineVerify(Unknown Source)    at java.security.Signature.verify(Unknown Source)    at com.mse.reader.SmartCardReader.main(SmartCardReader.java:234)Caused by: java.io.IOException: Sequence tag error    at sun.security.util.DerInputStream.getSequence(Unknown Source)    at sun.security.rsa.RSASignature.decodeSignature(Unknown Source)    ... 4 more

这是加密的消息和解密的消息。(Base4.encodeBase64)

加密长度= 128

JpypH/vKYR4RLjQA4frCab5WljnAoWgNiGUb0k+DCmh8gdWbOtpR/XUec2rW96Nr1k7czNTb2s/2WQDGXe05a3JjNrlErrfijhdWvn9flIzR/5uPrS3VJw+ALESl8NWqR5HF3AgArE6uYIW87EtSjO0iPJTO2N0cITtLghdUSBs=

解密长度= 50

gCUAABgAAAAAO5rJkAAAAAAAvGFOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=

答案1

小编典典

您已经将您的智能卡提供程序移到了Java SE上的其他提供程序的前面,并且由于某种原因,它还在尝试验证RSA签名,而不仅仅是将其用于RSA私钥操作。

有几种解决方法:

  1. 如果您使用相同的签名实例进行验证,则使用带有公钥的其他签名实例进行验证
  2. 如果那不能解决您的问题,请尝试查看是否可以将智能卡提供程序在Security类中的提供程序列表中向下移动(有关如何执行此操作,请参阅JCA文档)
  3. 否则,只需使用Signature该类提供正确的提供程序,我建议指定"SunRsaSign"(您可能希望使此字符串可配置)
  4. 向背后的公司解释com.mse,他们应该正确实施 延迟的提供者选择 ,而不是吞噬要在其硬件设备中使用的软件公钥

注意,由于智能卡充当服务器,谈论“服务器端”非常令人困惑。“终端端”和“卡端”将更加清晰。

BeanDefinitionStoreException, IOException 错误

BeanDefinitionStoreException, IOException 错误

启动项目后,出现如下错误

严重: StandardWrapper.Throwable

org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/taotao-manage-servlet.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/taotao-manage-servlet.xml]

at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344)

看到IO的时候还以为是IO异常,仔细一看是读取不到taotao-manage-servlet.xml这个文件,这个文件就是我配置springmvc的文件。在web.xml中我是这样写的

文件目录结构:

最简单的解决办法就是将这个配置文件放置到WEB-INF下面,

这就解决了,不知道是不是这个版本的springmvc的问题,还是其他什么问题,总之就是无法找到这个文件。

附注:在解决这个问题的时候发现一个很有意思的东西,记录在这里。

在web.xml中有一个标签:

该标签注意它的名字与servlet-mapping中的servlet-name必须一致 需要一样。另外很多时候的问题,是spring 与springmvc的位置发生错误,spring 必须先于springmvc加载。

c# – 为什么我得到SecurityTokenSignatureKeyNotFoundException?

c# – 为什么我得到SecurityTokenSignatureKeyNotFoundException?

当我尝试将此JWT(由Azure移动服务发布)作为HTTP标头/授权/承载令牌传递时:
Header:
{
    "alg": "HS256","typ": "JWT","kid": "0"
}
Claims:
{
    "ver": 2,"aud": "Facebook","iss": "urn:microsoft:windows-azure:zumo","urn:microsoft:credentials": "pYK8b5...","exp": 1436730730,"uid": "Facebook:10000xxxxxxxxxx"
}

进入我的ASP.NET WEB API配置:

const string issuer = "urn:microsoft:windows-azure:zumo";
byte[] mobileServicesSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["as:SecretKey"]);

app.UseJwtBearerAuthentication(
    new JwtBearerAuthenticationoptions
    {
      AuthenticationMode = AuthenticationMode.Active,AllowedAudiences = new[] { "Facebook" },IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
              {
                  new SymmetricKeyIssuerSecurityTokenProvider(issuer,mobileServicesSecret)
              }
    });

我明白了:

A first chance exception of type
‘System.IdentityModel.Tokens.SecurityTokenSignatureKeyNotFoundException’
occurred in System.IdentityModel.Tokens.Jwt.dll

我怀疑这是因为“孩子”财产的存在?

编辑:使用这个https://github.com/Magenic/JWTvalidator/tree/master/JwtValidator/JwtValidator,可以验证JWT,所以它没有错.但我真的想用OWIN / Katana.

解决方法

Google建议如下 –
Calling the tokeninfo endpoint

Rather than writing your own code to perform these verification steps,we strongly recommend using a Google Api client library for your platform,or calling our tokeninfo validation endpoint.

To validate an ID token using the tokeninfo endpoint,make an HTTPS POST or GET request to the endpoint,and pass your ID token in the id_token parameter. For example,to validate the token “XYZ123”,make the following GET request:

CustomJwtHandler.cs

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Configuration;
using Newtonsoft.Json;
using System.Net;
using System.Threading.Tasks;
using System.Threading;
using Services.Models;
using System.Security.Claims;

namespace Services
{
    /// <summary>
    ///  This is an implementation of Google JWT verification that
    ///  demonstrates:
    ///    - JWT validation
    /// </summary>
    /// @author kunal.bajpai@gmail.com (Kunal Bajpai)


    public class CustomJwtHandler : DelegatingHandler
    {
        private const string URL_GOOGLE_TOKEN_INFO = "https://www.googleapis.com/oauth2/v3/tokeninfo";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)
        {
            HttpStatusCode statusCode;
            string token;

            var authHeader = request.Headers.Authorization;
            if (authHeader == null)
            {
                // Missing authorization header
                return base.SendAsync(request,cancellationToken);
            }

            if (!TryRetrievetoken(request,out token))
            {
                return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(HttpStatusCode.Unauthorized));
            }

            try
            {
                Validatetoken(token);
                return base.SendAsync(request,cancellationToken);
            }
            catch (SecurityTokenInvalidAudienceException)
            {
                statusCode = HttpStatusCode.Unauthorized;
            }
            catch (SecurityTokenValidationException)
            {
                statusCode = HttpStatusCode.Unauthorized;
            }
            catch (Exception)
            {
                statusCode = HttpStatusCode.InternalServerError;
            }

            return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(statusCode));
        }
        /// <summary>
        /// Validates JWT Token
        /// </summary>
        /// <param name="JwtToken"></param>
        private void Validatetoken(string JwtToken)
        {
            try
            {
                using (WebClient wc = new WebClient())
                {
                    TokenInfo tokenInfo = JsonConvert.DeserializeObject<TokenInfo>(wc.DownloadString(URL_GOOGLE_TOKEN_INFO + "?id_token=" + JwtToken));

                    ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(ExtractClaims(tokenInfo),tokenInfo.Issuer));

                    Thread.CurrentPrincipal = claimsPrincipal;
                    HttpContext.Current.User = claimsPrincipal;
                }
            }
            catch (WebException e)
            {
                HttpStatusCode statusCode = ((HttpWebResponse)e.Response).StatusCode;
                if (statusCode == HttpStatusCode.BadRequest)
                {
                    throw new SecurityTokenValidationException();
                }
                else
                {
                    throw new Exception();
                }
            }
        }

        /// <summary>
        /// Tries to retrieve Token
        /// </summary>
        /// <param name="request"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private static bool TryRetrievetoken(HttpRequestMessage request,out string token)
        {
            token = null;
            IEnumerable<string> authorizationHeaders;

            if (!request.Headers.TryGetValues("Authorization",out authorizationHeaders) ||
            authorizationHeaders.Count() > 1)
            {
                return false;
            }

            var bearerToken = authorizationHeaders.ElementAt(0);
            token = bearerToken.StartsWith("Bearer ") ? bearerToken.Substring(7) : bearerToken;
            return true;
        }

        private List<Claim> ExtractClaims(TokenInfo tokenInfo)
        {
            List<Claim> claims = new List<Claim> {
                new Claim(ClaimTypes.Name,tokenInfo.Name),new Claim(ClaimTypes.Email,tokenInfo.Email),new Claim(ClaimTypes.Givenname,tokenInfo.Givenname),new Claim(ClaimTypes.Surname,tokenInfo.FamilyName),new Claim(ApplicationUser.CLaim_TYPE_LOCALE,tokenInfo.Locale),new Claim(ClaimTypes.NameIdentifier,tokenInfo.ProviderKey,ClaimValueTypes.String,tokenInfo.Issuer),new Claim(ApplicationUser.CLaim_TYPE_EMAIL_CONFIRMED,tokenInfo.IsEmailVerifed.ToString(),ClaimValueTypes.Boolean)
            };

            return claims;
        }
    }
}

TokenInfo.cs

using Microsoft.AspNet.Identity.EntityFramework;
using Newtonsoft.Json;

namespace Services.Models
{
    public class TokenInfo
    {
        [JsonProperty("iss")]
        public string Issuer { get; set; }

        [JsonProperty("aud")]
        public string AudienceClientId { get; set; }

        [JsonProperty("sub")]
        public string ProviderKey { get; set; }

        [JsonProperty("email_verified")]
        public bool IsEmailVerifed { get; set; }

        [JsonProperty("azp")]
        public string AndroidClientId { get; set; }

        [JsonProperty("email")]
        public string Email { get; set; }

        [JsonProperty("iat")]
        public long IssuedAt { get; set; }

        [JsonProperty("exp")]
        public long ExpiresAt { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("picture")]
        public string Picture { get; set; }

        [JsonProperty("given_name")]
        public string Givenname { get; set; }

        [JsonProperty("family_name")]
        public string FamilyName { get; set; }

        [JsonProperty("locale")]
        public string Locale { get; set; }

        [JsonProperty("alg")]
        public string Algorithm { get; set; }

        [JsonProperty("kid")]
        public string kid { get; set; }

        public override bool Equals(object obj)
        {
            if (obj.GetType() != typeof(ApplicationUser))
            {
                return false;
            }

            ApplicationUser user = (ApplicationUser)obj;
            bool hasLogin = false;

            foreach (IdentityUserLogin login in user.Logins)
            {
                if (login.ProviderKey == ProviderKey)
                {
                    hasLogin = true;
                    break;
                }
            }
            if (!hasLogin) { return false; }

            if (user.FirstName != Givenname) { return false; }
            if (user.LastName != FamilyName) { return false; }
            if (user.Locale != Locale) { return false; }

            return base.Equals(obj);
        }
    }
}

WebApiConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;

namespace Services
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",routeTemplate: "api/{controller}/{id}",defaults: new { id = RouteParameter.Optional }
            );
            config.MessageHandlers.Add(new CustomJwtHandler());
        }
    }
}

com.amazonaws.mturk.service.exception.ValidationException的实例源码

com.amazonaws.mturk.service.exception.ValidationException的实例源码

项目:java-aws-mturk    文件:TestRequesterService.java   
public void testValidateInvalidExternalQuestion() throws Exception {
  HITQuestion htmlQuestion = new HITQuestion(defaultInvalidExternalQuestionFileName);

  try {
    service.previewHIT(defaultHITInput,defaultHITProperties,htmlQuestion);

    fail("Expected ValidationException when previewing HIT with invalid external question." );
  }
  catch (ValidationException e) {
    // Expected exception
  }
}
项目:java-aws-mturk    文件:TestRequesterService.java   
public void testValidateInvalidHTMLQuestion() throws Exception {
  // HTMLQuestion has invalid FrameHeight
  try {
    QAPValidator.validateFile(defaultInvalidHTMLQuestionFileName);
    fail("Expected ValidationException when previewing a HIT with an invalid HTMLQuestion");
  } catch (ValidationException e) {
    // Expected exception
    assertContains("ValidationFailure was not caused by an invalid frame height.","'I am not a number; I am a free man!' is not a valid value for 'integer'",e.getMessage());
  }
}
项目:java-aws-mturk    文件:TestRequesterService.java   
public void testCreateInvalidFormattedContentHIT() throws Exception {
  HITQuestion htmlQuestion = new HITQuestion(defaultInvalidFormattedContentQuestionFileName);

  try {
    service.previewHIT(defaultHITInput,htmlQuestion);

    fail("Expected ValidationException when creating HIT with invalid formatted content." );
  }
  catch (ValidationException e) {
    // Expected exception
  }
}
项目:java-aws-mturk    文件:TestRequesterService.java   
public void testCreateScriptFormattedContentHIT() throws Exception {
  HITQuestion htmlQuestion = new HITQuestion(defaultScriptFormattedContentQuestionFileName);

  try {
    service.previewHIT(defaultHITInput,htmlQuestion);

    fail("Expected ValidationException when creating HIT with script in formatted content." );
  }
  catch (ValidationException e) {
    // Expected exception
  }
}
项目:mturksdk-java-code-maven    文件:TestRequesterService.java   
public void testValidateInvalidExternalQuestion() throws Exception {
  HITQuestion htmlQuestion = new HITQuestion(defaultInvalidExternalQuestionFileName);

  try {
    service.previewHIT(defaultHITInput,htmlQuestion);

    fail("Expected ValidationException when previewing HIT with invalid external question." );
  }
  catch (ValidationException e) {
    // Expected exception
  }
}
项目:mturksdk-java-code-maven    文件:TestRequesterService.java   
public void testValidateInvalidHTMLQuestion() throws Exception {
  // HTMLQuestion has invalid FrameHeight
  try {
    QAPValidator.validateFile(defaultInvalidHTMLQuestionFileName);
    fail("Expected ValidationException when previewing a HIT with an invalid HTMLQuestion");
  } catch (ValidationException e) {
    // Expected exception
    assertContains("ValidationFailure was not caused by an invalid frame height.",e.getMessage());
  }
}
项目:mturksdk-java-code-maven    文件:TestRequesterService.java   
public void testCreateInvalidFormattedContentHIT() throws Exception {
  HITQuestion htmlQuestion = new HITQuestion(defaultInvalidFormattedContentQuestionFileName);

  try {
    service.previewHIT(defaultHITInput,htmlQuestion);

    fail("Expected ValidationException when creating HIT with invalid formatted content." );
  }
  catch (ValidationException e) {
    // Expected exception
  }
}
项目:mturksdk-java-code-maven    文件:TestRequesterService.java   
public void testCreateScriptFormattedContentHIT() throws Exception {
  HITQuestion htmlQuestion = new HITQuestion(defaultScriptFormattedContentQuestionFileName);

  try {
    service.previewHIT(defaultHITInput,htmlQuestion);

    fail("Expected ValidationException when creating HIT with script in formatted content." );
  }
  catch (ValidationException e) {
    // Expected exception
  }
}
项目:java-aws-mturk    文件:QAPValidator.java   
public static void validate(String question) throws ValidationException,IOException {
  validate(question,false,QUESTION_FORM_XSD,false);
}
项目:java-aws-mturk    文件:QAPValidator.java   
public static void validateFile(String fileName)
  throws ValidationException,IOException {
  validate(fileName,true,false);
}
项目:mturksdk-java-code-maven    文件:QAPValidator.java   
public static void validate(String question) throws ValidationException,false);
}
项目:mturksdk-java-code-maven    文件:QAPValidator.java   
public static void validateFile(String fileName)
  throws ValidationException,false);
}

EGit:执行失败(SignatureException):签名编码错误

EGit:执行失败(SignatureException):签名编码错误

如何解决EGit:执行失败(SignatureException):签名编码错误?

当我从 GIT 拉取或推送代码时出现以下错误。

Failed (SignatureException) to execute: Signature encoding error

解决方法

花了一段时间才找到一个简单的解决方案。

您可以尝试以下任一方法:

解决方案 1:

  1. 转到您的 ssh 文件夹 (cd ~/.ssh/)

  2. 检查您是否有 config 文件,否则创建一个名为 config 的文件并复制以下详细信息。

My current ssh folder structure

Host github.foo.com
Hostname github.foo.com
User git
Port 22
IdentityFile ~/.ssh/your_private_key
HostKeyAlgorithms ^rsa-sha2-512,rsa-sha2-256,ssh-rsa

(根据需要替换主机名和密钥路径。)

就我而言,我正在尝试访问 IBM GitHub 存储库。我的私钥文件名是 id_rsa

示例:

Host github.ibm.com
Hostname github.ibm.com
User git
Port 22
IdentityFile ~/.ssh/id_rsa
HostKeyAlgorithms ^rsa-sha2-512,ssh-rsa

解决方案 2:

  1. 转到您的 ssh 文件夹 (cd ~/.ssh/)
  2. 在其他位置备份您的 known_hosts 文件(或重命名它。例如:在上面的屏幕截图中,我将其更改为 known_hosts_1),然后将其删除。

现在尝试从 EGit git pull 或 push。 save keys in known_hosts file

解决方案 3: 如果解决方案 1:解决方案 2: 单独不起作用,请同时尝试这两种解决方案。即创建一个 config 文件并删除/重命名 known_hosts 文件。

更详细的讨论在: https://www.eclipse.org/forums/index.php?t=msg&th=1108282/

关于Java Signature.verify中的SignatureException结果:签名编码错误IOException引起:序列标签错误的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于BeanDefinitionStoreException, IOException 错误、c# – 为什么我得到SecurityTokenSignatureKeyNotFoundException?、com.amazonaws.mturk.service.exception.ValidationException的实例源码、EGit:执行失败(SignatureException):签名编码错误等相关知识的信息别忘了在本站进行查找喔。

本文标签: