Beispiel #1
0
        public static string ComputeSHA3(byte[] data)
        {
            var hashRaw = DigestUtilities.CalculateDigest("SHA3-384", data);
            var hash    = Hex.ToHexString(hashRaw);

            return(hash);
        }
Beispiel #2
0
        public static byte[] CalcHash(string password, byte[] bsalt)
        {
            byte[] bpass     = Encoding.Unicode.GetBytes(password);
            var    bsaltpass = bsalt.Concat(bpass).ToArray();

            return(DigestUtilities.CalculateDigest("GOST3411", bsaltpass));
        }
Beispiel #3
0
        private static CertID CreateCertID(
            AlgorithmIdentifier hashAlg,
            X509Certificate issuerCert,
            DerInteger serialNumber)
        {
            try
            {
                String hashAlgorithm = hashAlg.Algorithm.Id;

                X509Name issuerName     = PrincipalUtilities.GetSubjectX509Principal(issuerCert);
                byte[]   issuerNameHash = DigestUtilities.CalculateDigest(
                    hashAlgorithm, issuerName.GetEncoded());

                AsymmetricKeyParameter issuerKey = issuerCert.GetPublicKey();
                SubjectPublicKeyInfo   info      = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKey);
                byte[] issuerKeyHash             = DigestUtilities.CalculateDigest(
                    hashAlgorithm, info.PublicKeyData.GetBytes());

                return(new CertID(hashAlg, new DerOctetString(issuerNameHash),
                                  new DerOctetString(issuerKeyHash), serialNumber));
            }
            catch (Exception e)
            {
                throw new OcspException("problem creating ID: " + e, e);
            }
        }
Beispiel #4
0
        public void TestSha1WithRsaNonData()
        {
            MemoryStream bOut = new MemoryStream();

            IX509Store x509Certs = CmsTestUtil.MakeCertStore(OrigCert, SignCert);
            IX509Store x509Crls  = CmsTestUtil.MakeCrlStore(SignCrl, OrigCrl);

            CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();

            gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1);
            gen.AddCertificates(x509Certs);
            gen.AddCrls(x509Crls);

            byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);

            Stream sigOut = gen.Open(bOut, "1.2.3.4", true);

            sigOut.Write(testBytes, 0, testBytes.Length);
            sigOut.Close();

            CmsSignedDataParser sp = new CmsSignedDataParser(bOut.ToArray());

            CmsTypedStream stream = sp.GetSignedContent();

            Assert.AreEqual("1.2.3.4", stream.ContentType);

            stream.Drain();

            // compute expected content digest
            byte[] hash = DigestUtilities.CalculateDigest("SHA1", testBytes);

            VerifySignatures(sp, hash);
        }
Beispiel #5
0
        /// <summary>
        /// Check if the TimeStampToken matches the data
        /// </summary>
        /// <returns>
        /// true if the data are verified by the TimeStampToken
        /// </returns>
        public virtual bool MatchData(byte[] data)
        {
            string hashAlgorithm = timeStamp.TimeStampInfo.HashAlgorithm.Algorithm.Id;

            byte[] computedDigest = DigestUtilities.CalculateDigest(hashAlgorithm, data);
            return(computedDigest.SequenceEqual(timeStamp.TimeStampInfo.GetMessageImprintDigest()));
        }
Beispiel #6
0
 private bool EveryCertificateRefAreThere(IValidationContext ctx, IList <CertificateRef> refs, X509Certificate signingCert, ICAdESLogger logger)
 {
     foreach (CertificateAndContext neededCert in ctx.NeededCertificates)
     {
         if (neededCert.Certificate.Equals(ctx.Certificate))
         {
             logger.Info("Don't check for the signing certificate");
             continue;
         }
         logger.Info("Looking for the CertificateRef of " + neededCert);
         bool found = false;
         foreach (CertificateRef referencedCert in refs)
         {
             logger.Info("Compare to " + referencedCert);
             byte[] hash = DigestUtilities.CalculateDigest(referencedCert.DigestAlgorithm, neededCert.Certificate.GetEncoded());
             if (hash.SequenceEqual(referencedCert.DigestValue))
             {
                 found = true;
                 break;
             }
         }
         logger.Info("Ref " + (found ? " found" : " not found"));
         if (!found)
         {
             return(false);
         }
     }
     return(true);
 }
        public CertificateConfirmationContent Build()
        {
            Asn1EncodableVector v = new Asn1EncodableVector();

            for (int i = 0; i != acceptedCerts.Count; i++)
            {
                X509Certificate cert  = (X509Certificate)acceptedCerts[i];
                BigInteger      reqId = (BigInteger)acceptedReqIds[i];


                AlgorithmIdentifier algorithmIdentifier = sigAlgFinder.Find(cert.SigAlgName);

                AlgorithmIdentifier digAlg = digestAlgFinder.find(algorithmIdentifier);
                if (null == digAlg)
                {
                    throw new CmpException("cannot find algorithm for digest from signature");
                }

                byte[] digest = DigestUtilities.CalculateDigest(digAlg.Algorithm, cert.GetEncoded());

                v.Add(new CertStatus(digest, reqId));
            }

            return(new CertificateConfirmationContent(CertConfirmContent.GetInstance(new DerSequence(v)),
                                                      digestAlgFinder));
        }
Beispiel #8
0
        /// <summary>
        /// Berechnet den Hash des öffentlichen Schlüssels
        /// </summary>
        /// <param name="rsaPubKey">RSA-Schlüssel-Parameter</param>
        /// <returns>Der MD5-Hash</returns>
        public static byte[] CalculatePublicKeyHash(RsaKeyParameters rsaPubKey)
        {
            var rawPubKeyData = new RsaPublicKeyStructure(rsaPubKey.Modulus, rsaPubKey.Exponent).ToAsn1Object().GetDerEncoded();
            var pubKeyHash    = DigestUtilities.CalculateDigest("MD5", rawPubKeyData);

            return(pubKeyHash);
        }
Beispiel #9
0
        private void rawModeTest(string sigName, DerObjectIdentifier digestOID,
                                 AsymmetricKeyParameter privKey, AsymmetricKeyParameter pubKey, SecureRandom random)
        {
            byte[] sampleMessage = new byte[1000 + random.Next() % 100];
            random.NextBytes(sampleMessage);

            ISigner normalSig = SignerUtilities.GetSigner(sigName);

            normalSig.Init(true, privKey);
            normalSig.BlockUpdate(sampleMessage, 0, sampleMessage.Length);
            byte[] normalResult = normalSig.GenerateSignature();

            byte[] hash    = DigestUtilities.CalculateDigest(digestOID.Id, sampleMessage);
            byte[] digInfo = derEncode(digestOID, hash);

            ISigner rawSig = SignerUtilities.GetSigner("RSA");

            rawSig.Init(true, privKey);
            rawSig.BlockUpdate(digInfo, 0, digInfo.Length);
            byte[] rawResult = rawSig.GenerateSignature();

            if (!Arrays.AreEqual(normalResult, rawResult))
            {
                Fail("raw mode signature differs from normal one");
            }

            rawSig.Init(false, pubKey);
            rawSig.BlockUpdate(digInfo, 0, digInfo.Length);

            if (!rawSig.VerifySignature(rawResult))
            {
                Fail("raw mode signature verification failed");
            }
        }
Beispiel #10
0
        /// <summary>
        /// Generates the value for DNS TXT record.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="token">The challenge token.</param>
        /// <returns></returns>
        public static string DnsTxt(this IKey key, string token)
        {
            var keyAuthz = key.KeyAuthorization(token);
            var hashed   = DigestUtilities.CalculateDigest("SHA256", Encoding.UTF8.GetBytes(keyAuthz));

            return(JwsConvert.ToBase64String(hashed));
        }
        public bool checkResponseHeader(Dictionary <string, string> reqHeaders, Dictionary <string, string> responseHeaders, string responseContent, string password)
        {
            string text = CreateMD5Hash(password) + ":";

            responseContent = responseContent.Replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
            if (!reqHeaders["Hyread-Message-Id"].Equals(responseHeaders["Hyread-Origin-Message-Id"]))
            {
                return(false);
            }
            long ticks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;

            new DateTime(ticks + Convert.ToInt64(reqHeaders["Hyread-Message-Timestamp"]) * 10000000);
            new DateTime(ticks + Convert.ToInt64(responseHeaders["Hyread-Message-Timestamp"]) * 10000000);
            string            fileName  = Directory.GetCurrentDirectory() + "\\HyreadDRMRI.cer";
            ICipherParameters publicKey = getPublicKey(FileToByteArray(fileName));

            byte[] array   = Base64.Encode(decodeByRSA(Base64.Decode(Encoding.UTF8.GetBytes(responseHeaders["Hyread-Message-Digest"])), publicKey));
            string @string = Encoding.UTF8.GetString(array, 0, array.Length);
            string s       = new StringBuilder(responseContent).Append("||").Append(responseHeaders["Hyread-Message-Timestamp"]).ToString();

            byte[] array2  = Base64.Encode(DigestUtilities.CalculateDigest("SHA-256", Encoding.UTF8.GetBytes(s)));
            string string2 = Encoding.UTF8.GetString(array2, 0, array2.Length);

            if ([email protected](string2))
            {
                return(false);
            }
            return(true);
        }
Beispiel #12
0
        public TimeStampTokenGenerator(AsymmetricKeyParameter key, X509Certificate cert, string digestOID, string tsaPolicyOID, Org.BouncyCastle.Asn1.Cms.AttributeTable signedAttr, Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAttr)
        {
            this.key          = key;
            this.cert         = cert;
            this.digestOID    = digestOID;
            this.tsaPolicyOID = tsaPolicyOID;
            this.unsignedAttr = unsignedAttr;
            TspUtil.ValidateCertificate(cert);
            IDictionary dictionary;

            if (signedAttr != null)
            {
                dictionary = signedAttr.ToDictionary();
            }
            else
            {
                dictionary = Platform.CreateHashtable();
            }
            try
            {
                byte[]    hash      = DigestUtilities.CalculateDigest("SHA-1", cert.GetEncoded());
                EssCertID essCertID = new EssCertID(hash);
                Org.BouncyCastle.Asn1.Cms.Attribute attribute = new Org.BouncyCastle.Asn1.Cms.Attribute(PkcsObjectIdentifiers.IdAASigningCertificate, new DerSet(new SigningCertificate(essCertID)));
                dictionary[attribute.AttrType] = attribute;
            }
            catch (CertificateEncodingException e)
            {
                throw new TspException("Exception processing certificate.", e);
            }
            catch (SecurityUtilityException e2)
            {
                throw new TspException("Can't find a SHA-1 implementation.", e2);
            }
            this.signedAttr = new Org.BouncyCastle.Asn1.Cms.AttributeTable(dictionary);
        }
Beispiel #13
0
        private Attribute MakeSigningCertificateAttribute(SignatureParameters parameters)
        {
            try
            {
                byte[] certHash = DigestUtilities.CalculateDigest
                                      (parameters.DigestAlgorithm.GetName(),
                                      parameters.SigningCertificate.GetEncoded());

                if (parameters.DigestAlgorithm == DigestAlgorithm.SHA1)
                {
                    SigningCertificate sc = new SigningCertificate(new EssCertID(certHash));
                    return(new Attribute(PkcsObjectIdentifiers.IdAASigningCertificate, new DerSet(sc
                                                                                                  )));
                }
                else
                {
                    EssCertIDv2 essCert = new EssCertIDv2(new AlgorithmIdentifier(parameters.DigestAlgorithm
                                                                                  .GetOid()), certHash);
                    SigningCertificateV2 scv2 = new SigningCertificateV2(new EssCertIDv2[] { essCert }
                                                                         );
                    return(new Attribute(PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet
                                             (scv2)));
                }
            }
            catch (NoSuchAlgorithmException e)
            {
                throw new RuntimeException(e);
            }
            catch (CertificateException e)
            {
                throw new RuntimeException(e);
            }
        }
Beispiel #14
0
        /// <summary>Create a reference to a X509Crl</summary>
        /// <param name="crl"></param>
        /// <returns></returns>
        /// <exception cref="Sharpen.NoSuchAlgorithmException">Sharpen.NoSuchAlgorithmException
        ///     </exception>
        /// <exception cref="Sharpen.CrlException">Sharpen.CrlException</exception>
        private CrlValidatedID MakeCrlValidatedID(X509Crl crl)
        {
            OtherHash hash = new OtherHash(DigestUtilities.CalculateDigest
                                               (X509ObjectIdentifiers.IdSha1, crl.GetEncoded()));
            BigInteger          crlnumber;
            CrlIdentifier       crlid;
            DerObjectIdentifier crlExt = new DerObjectIdentifier("2.5.29.20");

            if (crl.GetExtensionValue(crlExt) != null)
            {
                //crlnumber = new DerInteger(crl.GetExtensionValue(crlExt)).GetPositiveValue();
                crlnumber = new DerInteger(crl.GetExtensionValue(crlExt).GetDerEncoded()).PositiveValue;
                //crlid = new CrlIdentifier(new X509Name(crl.IssuerDN.GetName()), new
                crlid = new CrlIdentifier(crl.IssuerDN,
                                          //new DerUtcTime(crl.ThisUpdate), crlnumber);
                                          crl.ThisUpdate, crlnumber);
            }
            else
            {
                //crlid = new CrlIdentifier(new X509Name(crl.IssuerDN.GetName()),
                crlid = new CrlIdentifier(crl.IssuerDN,
                                          //new DerUtcTime(crl.ThisUpdate));
                                          crl.ThisUpdate);
            }
            CrlValidatedID crlvid = new CrlValidatedID(hash, crlid);

            return(crlvid);
        }
        /// <summary>
        /// Calculates hash (digest) of the given CSR using the specified hash algorithm OID
        /// </summary>
        /// <param name="csr">CSR without password</param>
        /// <param name="algorithm">digest algorithm OID, for example for SHA256 use: "2.16.840.1.101.3.4.2.1"</param>
        /// <returns>Hash of csr</returns>
        public byte[] BuildHash(byte[] csr, string algorithm)
        {
            var originalCsr = new Pkcs10CertificationRequestDelaySigned(csr);

            // parse CSR to Org.BouncyCastle.Pkcs.Pkcs10CertificationRequestDelaySigned
            //  requires CSR to have:
            // 1. Subject
            //      a. X509Name
            //      b. subject public key
            //      c. attributes
            //          c1. password - should be empty
            //          c2. extensions - should contain ... doesn't matter - don't touch
            // 2. SignatureAlgorithmId - keep as it is defined by user request
            // 3. SignBits of user for the given CSR

            // hash = function(csrWithPassword without signature/signature algorithm)
            // for some hash algorithms Hash may depend on a random number,
            // thus giving different Hash every time it is calculated even for the same Data, PrivateKey

            byte[] dataToSign = originalCsr.GetDataToSign();

            //byte[] digest = DigestUtilities.CalculateDigest(CmsSignedGenerator.DigestSha256, dataToSign);
            byte[] digest = DigestUtilities.CalculateDigest(algorithm, dataToSign);

            return(digest);
        }
Beispiel #16
0
 public void Should_Validate_Root_Ca_Signature()
 {
     string rootCertFilePath = "../../../test-data/certs/test-ca/Test-Root-CA-RSA-2048.cer";
     byte[] rootCertEncoded = File.ReadAllBytes(rootCertFilePath);
     byte[] rootCertDigest = DigestUtilities.CalculateDigest("SHA_256", rootCertEncoded);
     Certificate rootCertificate = CertificateParser.Parse(rootCertEncoded);
     bool validationResult = CertificateSignatureValidator.ValidateCertificateSignature(rootCertificate, rootCertificate);
     Assert.True(validationResult);
 }
Beispiel #17
0
        /// <summary>Check if the TimeStampToken matches the data</summary>
        /// <param name="data"></param>
        /// <returns>true if the data are verified by the TimeStampToken</returns>
        /// <exception cref="Sharpen.NoSuchAlgorithmException">Sharpen.NoSuchAlgorithmException
        ///     </exception>
        public virtual bool MatchData(byte[] data)
        {
            string hashAlgorithm = timeStamp.TimeStampInfo.HashAlgorithm.ObjectID.Id;

            byte[] computedDigest = DigestUtilities.CalculateDigest
                                        (hashAlgorithm, data);
            return(Arrays.Equals(computedDigest, timeStamp.TimeStampInfo.GetMessageImprintDigest
                                     ()));
        }
Beispiel #18
0
        /// <summary>
        /// Create a reference to a X509Certificate
        /// </summary>
        private static OtherCertID MakeOtherCertID(X509Certificate cert)
        {
            byte[] d = DigestUtilities.CalculateDigest(X509ObjectIdentifiers.IdSha1, cert.GetEncoded());
            logger.Info(new DerOctetString(d).ToString());
            OtherHash   hash        = new OtherHash(d);
            OtherCertID othercertid = new OtherCertID(hash);

            return(othercertid);
        }
Beispiel #19
0
        public void TestSha1WithRsa()
        {
            MemoryStream bOut = new MemoryStream();

            IX509Store x509Certs = CmsTestUtil.MakeCertStore(OrigCert, SignCert);
            IX509Store x509Crls  = CmsTestUtil.MakeCrlStore(SignCrl, OrigCrl);

            CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();

            gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1);
            gen.AddCertificates(x509Certs);
            gen.AddCrls(x509Crls);

            Stream sigOut = gen.Open(bOut);

            byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);
            sigOut.Write(testBytes, 0, testBytes.Length);

            sigOut.Close();

            CheckSigParseable(bOut.ToArray());

            CmsSignedDataParser sp = new CmsSignedDataParser(
                new CmsTypedStream(new MemoryStream(testBytes, false)), bOut.ToArray());

            sp.GetSignedContent().Drain();

            // compute expected content digest
            byte[] hash = DigestUtilities.CalculateDigest("SHA1", testBytes);

            VerifySignatures(sp, hash);

            //
            // try using existing signer
            //
            gen = new CmsSignedDataStreamGenerator();
            gen.AddSigners(sp.GetSignerInfos());
            gen.AddCertificates(sp.GetCertificates("Collection"));
            gen.AddCrls(sp.GetCrls("Collection"));

            bOut.SetLength(0);

            sigOut = gen.Open(bOut, true);
            sigOut.Write(testBytes, 0, testBytes.Length);
            sigOut.Close();

            VerifyEncodedData(bOut);

            //
            // look for the CRLs
            //
            ArrayList col = new ArrayList(x509Crls.GetMatches(null));

            Assert.AreEqual(2, col.Count);
            Assert.IsTrue(col.Contains(SignCrl));
            Assert.IsTrue(col.Contains(OrigCrl));
        }
Beispiel #20
0
        /// <summary>
        /// Generates the thumbprint for the given account <paramref name="key"/>.
        /// </summary>
        /// <param name="key">The account key.</param>
        /// <returns>The thumbprint.</returns>
        internal static byte[] GenerateThumbprint(this IKey key)
        {
            var jwk    = key.JsonWebKey;
            var json   = JsonConvert.SerializeObject(jwk, Formatting.None, thumbprintSettings);
            var bytes  = Encoding.UTF8.GetBytes(json);
            var hashed = DigestUtilities.CalculateDigest("SHA256", bytes);

            return(hashed);
        }
Beispiel #21
0
        public void DigestTest()
        {
            var sharedSeedData = new[] { "1948679508", "-4721854150932553650", "3486951862276399275" };

            var aggregated = Encoding.ASCII.GetBytes(string.Join(";", sharedSeedData));

            var hashedBytes = DigestUtilities.CalculateDigest("KECCAK-384", aggregated);

            var tx = HexConverter.ToHex(hashedBytes);
        }
Beispiel #22
0
        /// <exception cref="System.IO.IOException"></exception>
        public virtual EU.Europa.EC.Markt.Dss.Digest Digest(Document document, SignatureParameters
                                                            parameters)
        {
            Stream input = ToBeSigned(document, parameters);

            byte[] data        = Streams.ReadAll(input);
            byte[] digestValue = DigestUtilities.CalculateDigest(
                parameters.DigestAlgorithm.GetName(), data);
            return(new EU.Europa.EC.Markt.Dss.Digest(parameters.DigestAlgorithm, digestValue));
        }
 public void Validate(X509Certificate cert)
 {
     try
     {
         byte[] b = DigestUtilities.CalculateDigest(certID.GetHashAlgorithmName(), cert.GetEncoded());
         if (!Arrays.ConstantTimeAreEqual(certID.GetCertHash(), b))
         {
             throw new TspValidationException("certificate hash does not match certID hash.");
         }
         if (certID.IssuerSerial != null)
         {
             if (!certID.IssuerSerial.Serial.Value.Equals(cert.SerialNumber))
             {
                 throw new TspValidationException("certificate serial number does not match certID for signature.");
             }
             GeneralName[] names = certID.IssuerSerial.Issuer.GetNames();
             X509Name      issuerX509Principal = PrincipalUtilities.GetIssuerX509Principal(cert);
             bool          flag = false;
             for (int i = 0; i != names.Length; i++)
             {
                 if (names[i].TagNo == 4 && X509Name.GetInstance(names[i].Name).Equivalent(issuerX509Principal))
                 {
                     flag = true;
                     break;
                 }
             }
             if (!flag)
             {
                 throw new TspValidationException("certificate name does not match certID for signature. ");
             }
         }
         TspUtil.ValidateCertificate(cert);
         cert.CheckValidity(tstInfo.GenTime);
         if (!tsaSignerInfo.Verify(cert))
         {
             throw new TspValidationException("signature not created by certificate.");
         }
     }
     catch (CmsException ex)
     {
         if (ex.InnerException != null)
         {
             throw new TspException(ex.Message, ex.InnerException);
         }
         throw new TspException("CMS exception: " + ex, ex);
     }
     catch (CertificateEncodingException ex2)
     {
         throw new TspException("problem processing certificate: " + ex2, ex2);
     }
     catch (SecurityUtilityException ex3)
     {
         throw new TspException("cannot find algorithm: " + ex3.Message, ex3);
     }
 }
Beispiel #24
0
        public void Should_Return_False_When_Request_Signature_Is_Invalid_In_Add_Trusted_Root_Certificate()
        {
            string rootCertFilePath = "../../../test-data/certs/test-ca/Test-Root-CA-RSA-2048.cer";

            byte[] rootCertEncoded  = File.ReadAllBytes(rootCertFilePath);
            byte[] rootCertDigest   = DigestUtilities.CalculateDigest("SHA_256", rootCertEncoded);
            byte[] requestSignature = StringUtil.StringToByteArray("InvalidSignature");
            bool   result           = RootCaCertificateHandler.AddTrustedRootCaCertificate(rootCertDigest, rootCertEncoded, requestSignature);

            Assert.False(result);
        }
Beispiel #25
0
 public byte[] ComputeSha256(byte[] bytes)
 {
     try
     {
         return(DigestUtilities.CalculateDigest("SHA-256", bytes));
     }
     catch (SecurityUtilityException e)
     {
         throw new U2FException("Cannot compute SHA-256", e);
     }
 }
        public static byte[] GetMethodId(FunctionABI func)
        {
            List <Parameter> list = new List <Parameter>(func.InputParameters);

            byte[] hash = DigestUtilities.CalculateDigest
                              ("SM3", System.Text.Encoding.UTF8.GetBytes(string.Format("{0}({1})", func.Name,
                                                                                       string.Join(',', list.ConvertAll(a => a.Type)))));
            byte[] id = new byte[4];
            Array.Copy(hash, id, 4);
            return(id);
        }
Beispiel #27
0
        /// <summary>Create a reference to a X509Certificate</summary>
        /// <param name="cert"></param>
        /// <returns></returns>
        /// <exception cref="Sharpen.NoSuchAlgorithmException">Sharpen.NoSuchAlgorithmException
        ///     </exception>
        /// <exception cref="Sharpen.CertificateEncodingException">Sharpen.CertificateEncodingException
        ///     </exception>
        private OtherCertID MakeOtherCertID(X509Certificate cert)
        {
            byte[] d = DigestUtilities.CalculateDigest
                           (X509ObjectIdentifiers.IdSha1, cert.GetEncoded());
            //LOG.Info(new DerOctetString(d).ToString());
            OtherHash hash = new OtherHash(d);
            //OtherCertID othercertid = new OtherCertID(new DerSequence(hash.ToAsn1Object()));
            OtherCertID othercertid = new OtherCertID(hash);

            return(othercertid);
        }
Beispiel #28
0
        /// <summary>
        /// Create a reference on a OcspResp
        /// </summary>
        private static OcspResponsesID MakeOcspResponsesID(BasicOcspResp ocspResp)
        {
            byte[] digestValue = DigestUtilities.CalculateDigest
                                     (X509ObjectIdentifiers.IdSha1, ocspResp.GetEncoded());
            OtherHash       hash       = new OtherHash(digestValue);
            OcspResponsesID ocsprespid = new OcspResponsesID(new OcspIdentifier(ocspResp.ResponderId
                                                                                .ToAsn1Object(), ocspResp.ProducedAt), hash);

            logger.Info("Incorporate OcspResponseId[hash=" + Hex.ToHexString(digestValue) +
                        ",producedAt=" + ocspResp.ProducedAt);
            return(ocsprespid);
        }
        /**
         * Test the hash against a standard value for the string "abc"
         *
         * @param algorithm algorithm to test
         * @param hash expected value
         * @return the test result.
         */
        void doAbcTest(
            string algorithm,
            string hash)
        {
            byte[] abc    = { (byte)0x61, (byte)0x62, (byte)0x63 };
            byte[] result = DigestUtilities.CalculateDigest(algorithm, abc);

            if (!AreEqual(result, Hex.Decode(hash)))
            {
                Fail("abc result not equal for " + algorithm);
            }
        }
Beispiel #30
0
        /**
         * create with a signer with extra signed/unsigned attributes.
         */
        public TimeStampTokenGenerator(
            AsymmetricKeyParameter key,
            X509Certificate cert,
            string digestOID,
            string tsaPolicyOID,
            Asn1.Cms.AttributeTable signedAttr,
            Asn1.Cms.AttributeTable unsignedAttr)
        {
            this.key          = key;
            this.cert         = cert;
            this.digestOID    = digestOID;
            this.tsaPolicyOID = tsaPolicyOID;
            this.unsignedAttr = unsignedAttr;

            TspUtil.ValidateCertificate(cert);

            //
            // Add the ESSCertID attribute
            //
            Hashtable signedAttrs;

            if (signedAttr != null)
            {
                signedAttrs = signedAttr.ToHashtable();
            }
            else
            {
                signedAttrs = new Hashtable();
            }

            try
            {
                byte[] hash = DigestUtilities.CalculateDigest("SHA-1", cert.GetEncoded());

                EssCertID essCertid = new EssCertID(hash);

                Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(
                    PkcsObjectIdentifiers.IdAASigningCertificate,
                    new DerSet(new SigningCertificate(essCertid)));

                signedAttrs[attr.AttrType] = attr;
            }
            catch (CertificateEncodingException e)
            {
                throw new TspException("Exception processing certificate.", e);
            }
            catch (SecurityUtilityException e)
            {
                throw new TspException("Can't find a SHA-1 implementation.", e);
            }

            this.signedAttr = new Asn1.Cms.AttributeTable(signedAttrs);
        }