DER长度超过4个字节?

时间:2015-09-03 06:48:19

标签: c# cryptography itextsharp digital-signature

我想对pdf文档进行数字签名,但我正在接受预期

  

DER长度超过4个字节。

这是我的代码:

public static Asn1EncodableVector GetTimestamp(byte[] signature)
{

        ITSAClient tsc = new TSAClientBouncyCastle("https://wstsa.kibs.mk/wsTSA.asmx", null, null);
        //return tsc.GetTimeStampToken(null, tsImprint);
        HashAlgorithm sha = new SHA1CryptoServiceProvider();


      //byte[] hash =  sha1.ComputeHash(bytData);
        String ID_TIME_STAMP_TOKEN = "1.2.840.113549.1.9.16.2.14"; // RFC 3161 id-aa-timeStampToken
        mk.kibs.wstsatest.wsTSATest oWS1 = new mk.kibs.wstsatest.wsTSATest();
    //    HashAlgorithm sha = new SHA1CryptoServiceProvider();

        mk.kibs.wstsatest.TSCheck_Bytes bytes = new mk.kibs.wstsatest.TSCheck_Bytes();
        mk.kibs.wstsatest.TSResponse_Bytes b = new mk.kibs.wstsatest.TSResponse_Bytes();
        byte[] filename = File.ReadAllBytes(@"C:\Users\nikola.nedelkovski\Desktop\nalozinovi.pdf");

        SHA1CryptoServiceProvider shax = new SHA1CryptoServiceProvider();
       byte [] hashx = shax.ComputeHash(filename);
    //   Asn1InputStream tempstream = new Asn1InputStream(new MemoryStream(tsc.GetTimeStampToken(null, hashx)));
       // mk.kibs.wstsatest.TSResponse_Bytes resp1 = oWS1.funGenerateTS_Bytes(hashx);

        oWS1.Dispose();
   //     hashx = b.bytTSToken;
        //hashx = bytes.bytHashMessage;
        bytes.bytHashMessage = hashx;
       Asn1InputStream tempstream = new Asn1InputStream(new MemoryStream(hashx));

        Asn1EncodableVector unauthAttributes = new Asn1EncodableVector();

        Asn1EncodableVector v = new Asn1EncodableVector();
        v.Add(new DerObjectIdentifier(ID_TIME_STAMP_TOKEN)); // id-aa-timeStampToken
        Asn1Sequence seq = (Asn1Sequence)tempstream.ReadObject();
        v.Add(new DerSet(seq));

        unauthAttributes.Add(new DerSequence(v));
        //return unauthAttributes;
     //   return unauthAttributes;
        return unauthAttributes;
    }

    public static X509Certificate2 GetCertificate()
    {
        X509Store st = new X509Store(StoreName.My, StoreLocation.CurrentUser);
        st.Open(OpenFlags.ReadOnly);
        X509Certificate2Collection col = st.Certificates;
        X509Certificate2 card = null;
        X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(col, "Certificates", "Select one to sign", X509SelectionFlag.SingleSelection);
        if (sel.Count > 0)
        {
            X509Certificate2Enumerator en = sel.GetEnumerator();
            en.MoveNext();
            card = en.Current;
        }
        st.Close();
        return card;
}

异常将在以下行引发:您可以在上面提到的代码中找到它

Asn1Sequence seq = (Asn1Sequence)tempstream.ReadObject();

请提供任何帮助或建议?

1 个答案:

答案 0 :(得分:1)

好吧,你创建一个哈希,它由可以包含任何值的二进制字节组成。然后你执行:

Asn1Sequence seq = (Asn1Sequence)tempstream.ReadObject();

对二进制数据无法区分随机数据。随机二进制数据不代表ASN.1 SEQUENCE。

您需要重新设计自己的方法并了解自己的所作所为。很可能你应该自己生成ASN.1 SEQUENCE而不是解析它。