Beispiel #1
0
        protected internal static byte[] GetCurrentPrfHash(TlsContext context, TlsHandshakeHash handshakeHash, byte[] sslSender)
        {
            IDigest digest = handshakeHash.ForkPrfHash();

            if (sslSender != null && TlsUtilities.IsSsl(context))
            {
                digest.BlockUpdate(sslSender, 0, sslSender.Length);
            }
            return(DigestUtilities.DoFinal(digest));
        }
Beispiel #2
0
 protected virtual void Ssl3Complete(IDigest d, byte[] ipad, byte[] opad, int padLength)
 {
     byte[] masterSecret = mContext.SecurityParameters.masterSecret;
     d.BlockUpdate(masterSecret, 0, masterSecret.Length);
     d.BlockUpdate(ipad, 0, padLength);
     byte[] array = DigestUtilities.DoFinal(d);
     d.BlockUpdate(masterSecret, 0, masterSecret.Length);
     d.BlockUpdate(opad, 0, padLength);
     d.BlockUpdate(array, 0, array.Length);
 }
 private static BigInteger CalculateHashForZeroKnowledgeProof(BigInteger g, BigInteger gr, BigInteger gx, string participantId, IDigest digest)
 {
     digest.Reset();
     UpdateDigestIncludingSize(digest, g);
     UpdateDigestIncludingSize(digest, gr);
     UpdateDigestIncludingSize(digest, gx);
     UpdateDigestIncludingSize(digest, participantId);
     byte[] bytes = DigestUtilities.DoFinal(digest);
     return(new BigInteger(bytes));
 }
Beispiel #4
0
        /// <summary>
        /// Calculates <code>MD5</code> hash
        /// </summary>
        /// <param name="data">The data to calculate the hash for</param>
        /// <returns>The calculated hash</returns>
        public static byte[] MD5(byte[] data)
        {
#if USE_BOUNCYCASTLE
            var digest = new MD5Digest();
            return(DigestUtilities.DoFinal(digest, data));
#else
            using (var digest = System.Security.Cryptography.MD5.Create())
                return(digest.ComputeHash(data));
#endif
        }
Beispiel #5
0
        public static string Compute(string data)
        {
            var digest = new SM3Digest();
            var bytes  = Encoding.UTF8.GetBytes(data);

            digest.BlockUpdate(bytes, 0, bytes.Length);
            var result = DigestUtilities.DoFinal(digest);

            return(BitConverter.ToString(result).Replace("-", "").ToLower());
        }
        internal SignerInfo ToSignerInfo(DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random)
        {
            AlgorithmIdentifier digestAlgorithmID = DigestAlgorithmID;
            string digestAlgName = Helper.GetDigestAlgName(digestOID);
            string algorithm     = digestAlgName + "with" + Helper.GetEncryptionAlgName(encOID);

            byte[] array;
            if (outer._digests.Contains(digestOID))
            {
                array = (byte[])outer._digests[digestOID];
            }
            else
            {
                IDigest digestInstance = Helper.GetDigestInstance(digestAlgName);
                content?.Write(new DigOutputStream(digestInstance));
                array = DigestUtilities.DoFinal(digestInstance);
                outer._digests.Add(digestOID, array.Clone());
            }
            IStreamCalculator streamCalculator = sigCalc.CreateCalculator();
            Stream            stream           = new BufferedStream(streamCalculator.Stream);
            Asn1Set           asn1Set          = null;

            if (sAttr != null)
            {
                IDictionary baseParameters = outer.GetBaseParameters(contentType, digestAlgorithmID, array);
                Org.BouncyCastle.Asn1.Cms.AttributeTable attributeTable = sAttr.GetAttributes(baseParameters);
                if (contentType == null && attributeTable != null && attributeTable[CmsAttributes.ContentType] != null)
                {
                    IDictionary dictionary = attributeTable.ToDictionary();
                    dictionary.Remove(CmsAttributes.ContentType);
                    attributeTable = new Org.BouncyCastle.Asn1.Cms.AttributeTable(dictionary);
                }
                asn1Set = outer.GetAttributeSet(attributeTable);
                new DerOutputStream(stream).WriteObject(asn1Set);
            }
            else
            {
                content?.Write(stream);
            }
            Platform.Dispose(stream);
            byte[]  array2 = ((IBlockResult)streamCalculator.GetResult()).Collect();
            Asn1Set unauthenticatedAttributes = null;

            if (unsAttr != null)
            {
                IDictionary baseParameters2 = outer.GetBaseParameters(contentType, digestAlgorithmID, array);
                baseParameters2[CmsAttributeTableParameter.Signature] = array2.Clone();
                Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = unsAttr.GetAttributes(baseParameters2);
                unauthenticatedAttributes = outer.GetAttributeSet(attributes);
            }
            Asn1Encodable       defaultX509Parameters  = SignerUtilities.GetDefaultX509Parameters(algorithm);
            AlgorithmIdentifier encAlgorithmIdentifier = Helper.GetEncAlgorithmIdentifier(new DerObjectIdentifier(encOID), defaultX509Parameters);

            return(new SignerInfo(signerIdentifier, digestAlgorithmID, asn1Set, encAlgorithmIdentifier, new DerOctetString(array2), unauthenticatedAttributes));
        }
Beispiel #7
0
        private byte[] CalculateInnerHash(IDigest digest, ECPoint u, byte[] za, byte[] zb, ECPoint p1, ECPoint p2)
        {
            AddFieldElement(digest, u.AffineXCoord);
            digest.BlockUpdate(za, 0, za.Length);
            digest.BlockUpdate(zb, 0, zb.Length);
            AddFieldElement(digest, p1.AffineXCoord);
            AddFieldElement(digest, p1.AffineYCoord);
            AddFieldElement(digest, p2.AffineXCoord);
            AddFieldElement(digest, p2.AffineYCoord);

            return(DigestUtilities.DoFinal(digest));
        }
Beispiel #8
0
        private byte[] MakeTestHash(
            IDigest digest)
        {
            for (int i = 0; i < digest.GetDigestSize(); ++i)
            {
                digest.Update((byte)i);
            }

            digest.BlockUpdate(TestBytes, 0, TestBytes.Length);

            return(DigestUtilities.DoFinal(digest));
        }
        /// <summary>
        /// SM3加密
        /// <para>
        /// SM3是中华人民共和国政府采用的一种密码散列函数标准,由国家密码管理局于2010年12月17日发布。相关标准为“GM/T 0004-2012 《SM3密码杂凑算法》”。
        /// 在商用密码体系中,SM3主要用于数字签名及验证、消息认证码生成及验证、随机数生成等,其算法公开。据国家密码管理局表示,其安全性及效率与SHA-256相当。
        /// </para>
        /// </summary>
        /// <param name="data">待加密的数据</param>
        /// <returns>返回SM3加密后的二进制字节数组</returns>
        public static byte[] SM3(this string data)
        {
            if (string.IsNullOrEmpty(data))
            {
                return(null);
            }
            var digest = new SM3Digest();
            var bytes  = Encoding.UTF8.GetBytes(data);

            digest.BlockUpdate(bytes, 0, bytes.Length);
            return(DigestUtilities.DoFinal(digest));
        }
Beispiel #10
0
        private byte[] GetZ(byte[] userID)
        {
            AddUserID(digest, userID);

            AddFieldElement(digest, ecParams.Curve.A);
            AddFieldElement(digest, ecParams.Curve.B);
            AddFieldElement(digest, ecParams.G.AffineXCoord);
            AddFieldElement(digest, ecParams.G.AffineYCoord);
            AddFieldElement(digest, pubPoint.AffineXCoord);
            AddFieldElement(digest, pubPoint.AffineYCoord);

            return(DigestUtilities.DoFinal(digest));
        }
Beispiel #11
0
        /// <summary>
        /// Calculates the MacKey (i.e. the key to use when calculating the MagTag for key confirmation).
        ///
        /// MacKey = H(K || "JPAKE_KC")
        /// </summary>
        private static byte[] CalculateMacKey(BigInteger keyingMaterial, IDigest digest)
        {
            digest.Reset();

            UpdateDigest(digest, keyingMaterial);

            /*
             * This constant is used to ensure that the macKey is NOT the same as the derived key.
             */
            UpdateDigest(digest, "JPAKE_KC");

            return(DigestUtilities.DoFinal(digest));
        }
            internal SignerInfo ToSignerInfo(DerObjectIdentifier contentType, CmsProcessable content, SecureRandom random)
            {
                AlgorithmIdentifier digestAlgorithmID = this.DigestAlgorithmID;
                string  digestAlgName     = CmsSignedDataGenerator.Helper.GetDigestAlgName(this.digestOID);
                IDigest digestInstance    = CmsSignedDataGenerator.Helper.GetDigestInstance(digestAlgName);
                string  algorithm         = digestAlgName + "with" + CmsSignedDataGenerator.Helper.GetEncryptionAlgName(this.encOID);
                ISigner signatureInstance = CmsSignedDataGenerator.Helper.GetSignatureInstance(algorithm);

                if (content != null)
                {
                    content.Write(new DigOutputStream(digestInstance));
                }
                byte[] array = DigestUtilities.DoFinal(digestInstance);
                this.outer._digests.Add(this.digestOID, array.Clone());
                signatureInstance.Init(true, new ParametersWithRandom(this.key, random));
                Stream  stream  = new BufferedStream(new SigOutputStream(signatureInstance));
                Asn1Set asn1Set = null;

                if (this.sAttr != null)
                {
                    IDictionary baseParameters = this.outer.GetBaseParameters(contentType, digestAlgorithmID, array);
                    Org.BouncyCastle.Asn1.Cms.AttributeTable attributeTable = this.sAttr.GetAttributes(baseParameters);
                    if (contentType == null && attributeTable != null && attributeTable[CmsAttributes.ContentType] != null)
                    {
                        IDictionary dictionary = attributeTable.ToDictionary();
                        dictionary.Remove(CmsAttributes.ContentType);
                        attributeTable = new Org.BouncyCastle.Asn1.Cms.AttributeTable(dictionary);
                    }
                    asn1Set = this.outer.GetAttributeSet(attributeTable);
                    new DerOutputStream(stream).WriteObject(asn1Set);
                }
                else if (content != null)
                {
                    content.Write(stream);
                }
                stream.Close();
                byte[]  array2 = signatureInstance.GenerateSignature();
                Asn1Set unauthenticatedAttributes = null;

                if (this.unsAttr != null)
                {
                    IDictionary baseParameters2 = this.outer.GetBaseParameters(contentType, digestAlgorithmID, array);
                    baseParameters2[CmsAttributeTableParameter.Signature] = array2.Clone();
                    Org.BouncyCastle.Asn1.Cms.AttributeTable attributes = this.unsAttr.GetAttributes(baseParameters2);
                    unauthenticatedAttributes = this.outer.GetAttributeSet(attributes);
                }
                Asn1Encodable       defaultX509Parameters  = SignerUtilities.GetDefaultX509Parameters(algorithm);
                AlgorithmIdentifier encAlgorithmIdentifier = CmsSignedGenerator.GetEncAlgorithmIdentifier(new DerObjectIdentifier(this.encOID), defaultX509Parameters);

                return(new SignerInfo(this.signerIdentifier, digestAlgorithmID, asn1Set, encAlgorithmIdentifier, new DerOctetString(array2), unauthenticatedAttributes));
            }
        public void TestSha1WithRsaNonData()
        {
            IList        certList = new ArrayList();
            IList        crlList  = new ArrayList();
            MemoryStream bOut     = new MemoryStream();

            certList.Add(OrigCert);
            certList.Add(SignCert);

            crlList.Add(SignCrl);
            crlList.Add(OrigCrl);

            IX509Store x509Certs = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certList));
            IX509Store x509Crls = X509StoreFactory.Create(
                "CRL/Collection",
                new X509CollectionStoreParameters(crlList));

            CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();

            gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1);

            gen.AddCertificates(x509Certs);
            gen.AddCrls(x509Crls);

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

            byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);
            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
            //
            IDigest md = DigestUtilities.GetDigest("SHA1");

            md.BlockUpdate(testBytes, 0, testBytes.Length);
            byte[] hash = DigestUtilities.DoFinal(md);

            VerifySignatures(sp, hash);
        }
Beispiel #14
0
        public bool Match(X509Certificate x509Cert)
        {
            try
            {
                if (holder.BaseCertificateID != null)
                {
                    return(holder.BaseCertificateID.Serial.Value.Equals(x509Cert.SerialNumber) && MatchesDN(PrincipalUtilities.GetIssuerX509Principal(x509Cert), holder.BaseCertificateID.Issuer));
                }
                if (holder.EntityName != null && MatchesDN(PrincipalUtilities.GetSubjectX509Principal(x509Cert), holder.EntityName))
                {
                    return(true);
                }
                if (holder.ObjectDigestInfo != null)
                {
                    IDigest digest = null;
                    try
                    {
                        digest = DigestUtilities.GetDigest(DigestAlgorithm);
                    }
                    catch (global::System.Exception)
                    {
                        return(false);
                    }
                    switch (DigestedObjectType)
                    {
                    case 0:
                    {
                        byte[] encoded2 = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(x509Cert.GetPublicKey()).GetEncoded();
                        digest.BlockUpdate(encoded2, 0, encoded2.Length);
                        break;
                    }

                    case 1:
                    {
                        byte[] encoded = x509Cert.GetEncoded();
                        digest.BlockUpdate(encoded, 0, encoded.Length);
                        break;
                    }
                    }
                    if (!Arrays.AreEqual(DigestUtilities.DoFinal(digest), GetObjectDigest()))
                    {
                        return(false);
                    }
                }
            }
            catch (CertificateEncodingException)
            {
                return(false);
            }
            return(false);
        }
Beispiel #15
0
        public override byte[] GenerateServerKeyExchange()
        {
            if (this.mDHParameters == null)
            {
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }

            DigestInputBuffer buf = new DigestInputBuffer();

            this.mDHAgreeServerPrivateKey = TlsDHUtilities.GenerateEphemeralServerKeyExchange(context.SecureRandom,
                                                                                              this.mDHParameters, buf);

            /*
             * RFC 5246 4.7. digitally-signed element needs SignatureAndHashAlgorithm from TLS 1.2
             */
            SignatureAndHashAlgorithm signatureAndHashAlgorithm;
            IDigest d;

            if (TlsUtilities.IsTlsV12(context))
            {
                signatureAndHashAlgorithm = mServerCredentials.SignatureAndHashAlgorithm;
                if (signatureAndHashAlgorithm == null)
                {
                    throw new TlsFatalAlert(AlertDescription.internal_error);
                }

                d = TlsUtilities.CreateHash(signatureAndHashAlgorithm.Hash);
            }
            else
            {
                signatureAndHashAlgorithm = null;
                d = new CombinedHash();
            }

            SecurityParameters securityParameters = context.SecurityParameters;

            d.BlockUpdate(securityParameters.clientRandom, 0, securityParameters.clientRandom.Length);
            d.BlockUpdate(securityParameters.serverRandom, 0, securityParameters.serverRandom.Length);
            buf.UpdateDigest(d);

            byte[] hash = DigestUtilities.DoFinal(d);

            byte[] signature = mServerCredentials.GenerateCertificateSignature(hash);

            DigitallySigned signed_params = new DigitallySigned(signatureAndHashAlgorithm, signature);

            signed_params.Encode(buf);

            return(buf.ToArray());
        }
Beispiel #16
0
        public virtual byte[] GetFinalHash(byte hashAlgorithm)
        {
            IDigest digest = (IDigest)this.mHashes[hashAlgorithm];

            if (digest == null)
            {
                throw new InvalidOperationException("HashAlgorithm " + hashAlgorithm + " is not being tracked");
            }
            digest = TlsUtilities.CloneHash(hashAlgorithm, digest);
            if (this.mBuf != null)
            {
                this.mBuf.UpdateDigest(digest);
            }
            return(DigestUtilities.DoFinal(digest));
        }
Beispiel #17
0
 /// <summary>
 /// sha256
 /// </summary>
 /// <param name="dataStr"></param>
 /// <param name="encoding"></param>
 /// <returns></returns>
 public static byte[] Sha256(string dataStr, Encoding encoding)
 {
     try
     {
         byte[]  data   = encoding.GetBytes(dataStr);
         IDigest digest = DigestUtilities.GetDigest("SHA256");
         digest.BlockUpdate(data, 0, data.Length);
         byte[] result = DigestUtilities.DoFinal(digest);
         return(result);
     }
     catch (Exception e)
     {
         return(null);
     }
 }
Beispiel #18
0
        public static string Compute(string data)
        {
            if (string.IsNullOrEmpty(data))
            {
                throw new ArgumentNullException(nameof(data));
            }

            var digest = new SM3Digest();
            var bytes  = Encoding.UTF8.GetBytes(data);

            digest.BlockUpdate(bytes, 0, bytes.Length);
            var result = DigestUtilities.DoFinal(digest);

            return(BitConverter.ToString(result).Replace("-", "").ToLower());
        }
        public virtual byte[] GetFinalHash(byte hashAlgorithm)
        {
            IDigest hash = (IDigest)this.mHashes[hashAlgorithm];

            if (hash == null)
            {
                throw new InvalidOperationException("HashAlgorithm." + HashAlgorithm.GetText(hashAlgorithm) + " is not being tracked");
            }
            hash = TlsUtilities.CloneHash(hashAlgorithm, hash);
            if (this.mBuf != null)
            {
                this.mBuf.UpdateDigest(hash);
            }
            return(DigestUtilities.DoFinal(hash));
        }
Beispiel #20
0
 /// <summary>
 /// sha1
 /// </summary>
 /// <param name="dataStr"></param>
 /// <param name="encoding"></param>
 /// <returns></returns>
 public static byte[] Sm3(string dataStr, Encoding encoding)
 {
     try
     {
         byte[]    data   = encoding.GetBytes(dataStr);
         SM3Digest digest = new SM3Digest();
         digest.BlockUpdate(data, 0, data.Length);
         byte[] result = DigestUtilities.DoFinal(digest);
         return(result);
     }
     catch
     {
         return(null);
     }
 }
Beispiel #21
0
    private static byte[] Kdf(HashAlgorithmTag digestAlg, ECPoint s, int keyLen, byte[] parameters)
    {
        byte[]  encoded    = s.XCoord.GetEncoded();
        string  digestName = PgpUtilities.GetDigestName(digestAlg);
        IDigest digest     = DigestUtilities.GetDigest(digestName);

        digest.Update(0);
        digest.Update(0);
        digest.Update(0);
        digest.Update(1);
        digest.BlockUpdate(encoded, 0, encoded.Length);
        digest.BlockUpdate(parameters, 0, parameters.Length);
        byte[] data = DigestUtilities.DoFinal(digest);
        return(Arrays.CopyOfRange(data, 0, keyLen));
    }
Beispiel #22
0
 public SignerInformationStore GetSignerInfos()
 {
     //IL_00e9: Expected O, but got Unknown
     if (_signerInfoStore == null)
     {
         PopulateCertCrlSets();
         global::System.Collections.IList list = Platform.CreateArrayList();
         IDictionary val = Platform.CreateHashtable();
         {
             global::System.Collections.IEnumerator enumerator = ((global::System.Collections.IEnumerable)_digests.get_Keys()).GetEnumerator();
             try
             {
                 while (enumerator.MoveNext())
                 {
                     object current = enumerator.get_Current();
                     val.set_Item(current, (object)DigestUtilities.DoFinal((IDigest)_digests.get_Item(current)));
                 }
             }
             finally
             {
                 global::System.IDisposable disposable = enumerator as global::System.IDisposable;
                 if (disposable != null)
                 {
                     disposable.Dispose();
                 }
             }
         }
         try
         {
             Asn1SetParser    signerInfos = _signedData.GetSignerInfos();
             IAsn1Convertible asn1Convertible;
             while ((asn1Convertible = signerInfos.ReadObject()) != null)
             {
                 SignerInfo instance      = SignerInfo.GetInstance(asn1Convertible.ToAsn1Object());
                 string     digestAlgName = Helper.GetDigestAlgName(instance.DigestAlgorithm.Algorithm.Id);
                 byte[]     digest        = (byte[])val.get_Item((object)digestAlgName);
                 list.Add((object)new SignerInformation(instance, _signedContentType, null, new BaseDigestCalculator(digest)));
             }
         }
         catch (IOException val2)
         {
             IOException val3 = val2;
             throw new CmsException("io exception: " + ((global::System.Exception)(object) val3).get_Message(), (global::System.Exception)(object) val3);
         }
         _signerInfoStore = new SignerInformationStore((global::System.Collections.ICollection)list);
     }
     return(_signerInfoStore);
 }
        private AsicePackageEntry CreateEntry(Stream contentStream, AsicePackageEntry entry)
        {
            var fileName   = entry.FileName ?? throw new ArgumentNullException(nameof(entry), "File name must be provided");
            var dataStream = contentStream ?? throw new ArgumentNullException(nameof(contentStream));
            var zipEntry   = Archive.CreateEntry(fileName);

            using (var zipStream = zipEntry.Open())
                using (var digestStream = new DigestStream(zipStream, null, MessageDigestAlgorithm.Digest))
                {
                    dataStream.CopyTo(digestStream);
                    dataStream.Flush();
                    entry.Digest = new DigestContainer(DigestUtilities.DoFinal(digestStream.WriteDigest()), MessageDigestAlgorithm);
                }

            return(entry);
        }
Beispiel #24
0
        /// <summary>
        /// Initializes the wrapper.
        /// </summary>
        /// <returns></returns>
        private AesWrapEngine InitializeWrapper()
        {
            var digest = DigestUtilities.GetDigest(_publicKey.HashAlgorithm.ToString());

            this.UpdateDigestWithKDFParameters(digest);
            var hash = DigestUtilities.DoFinal(digest);
            var size = _publicKey.SymmetricKeyAlgorithm == SymmetricKeyAlgorithmTag.Aes256
                ? 32 : _publicKey.SymmetricKeyAlgorithm == SymmetricKeyAlgorithmTag.Aes192
                ? 24 : _publicKey.SymmetricKeyAlgorithm == SymmetricKeyAlgorithmTag.Aes128
                ? 16 : 0;

            var wrap = new AesWrapEngine();

            wrap.Init(_forEncryption, new KeyParameter(hash, 0, size));
            return(wrap);
        }
Beispiel #25
0
        // Returns the signed digest
        byte[] IBlockResult.Collect()
        {
            // The collected array contains the document digest and parameters
            // to be signed but it needs to be further digested by the indended
            // hashing algorithm
            byte[]  toDigest = m_stream.ToArray();
            IDigest digester = DigestUtilities.GetDigest(m_digestAlgorithm.GetName());

            digester.BlockUpdate(toDigest, 0, toDigest.Length);
            byte[] digestValue = DigestUtilities.DoFinal(digester);
            // Wrap digest value in DER encoding (should be RFC3770 compliant)
            DigestInfo digestInfo = new DigestInfo(m_digestAlgorithm.GetAlgorithmIdentifier(), digestValue);

            byte[] wrapped = digestInfo.GetDerEncoded();
            return(signer(wrapped));
        }
Beispiel #26
0
 /// <summary>
 /// sha1
 /// </summary>
 /// <param name="dataStr"></param>
 /// <param name="encoding"></param>
 /// <returns></returns>
 public static byte[] Sm3(string dataStr, Encoding encoding)
 {
     try
     {
         byte[]    data   = encoding.GetBytes(dataStr);
         SM3Digest digest = new SM3Digest();
         digest.BlockUpdate(data, 0, data.Length);
         byte[] result = DigestUtilities.DoFinal(digest);
         return(result);
     }
     catch (Exception e)
     {
         log.Error("sm3失败:" + e.Message);
         return(null);
     }
 }
Beispiel #27
0
        public virtual byte[] GetFinalHash(byte hashAlgorithm)
        {
            //IL_002f: Unknown result type (might be due to invalid IL or missing references)
            IDigest digest = (IDigest)mHashes.get_Item((object)hashAlgorithm);

            if (digest == null)
            {
                throw new InvalidOperationException("HashAlgorithm." + HashAlgorithm.GetText(hashAlgorithm) + " is not being tracked");
            }
            digest = TlsUtilities.CloneHash(hashAlgorithm, digest);
            if (mBuf != null)
            {
                mBuf.UpdateDigest(digest);
            }
            return(DigestUtilities.DoFinal(digest));
        }
Beispiel #28
0
        private byte[] Decrypt(byte[] input, int inOff, int inLen)
        {
            byte[] c1 = new byte[mCurveLength * 2 + 1];

            Array.Copy(input, inOff, c1, 0, c1.Length);

            ECPoint c1P = mECParams.Curve.DecodePoint(c1);

            ECPoint s = c1P.Multiply(mECParams.H);

            if (s.IsInfinity)
            {
                throw new InvalidCipherTextException("[h]C1 at infinity");
            }

            c1P = c1P.Multiply(((ECPrivateKeyParameters)mECKey).D).Normalize();

            byte[] c2 = new byte[inLen - c1.Length - mDigest.GetDigestSize()];

            Array.Copy(input, inOff + c1.Length, c2, 0, c2.Length);

            Kdf(mDigest, c1P, c2);

            AddFieldElement(mDigest, c1P.AffineXCoord);
            mDigest.BlockUpdate(c2, 0, c2.Length);
            AddFieldElement(mDigest, c1P.AffineYCoord);

            byte[] c3 = DigestUtilities.DoFinal(mDigest);

            int check = 0;

            for (int i = 0; i != c3.Length; i++)
            {
                check |= c3[i] ^ input[inOff + c1.Length + c2.Length + i];
            }

            Arrays.Fill(c1, 0);
            Arrays.Fill(c3, 0);

            if (check != 0)
            {
                Arrays.Fill(c2, 0);
                throw new InvalidCipherTextException("invalid cipher text");
            }

            return(c2);
        }
Beispiel #29
0
        /**
         * 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 };

            IDigest digest = DigestUtilities.GetDigest(algorithm);

//			byte[] result = digest.digest(abc);
            digest.BlockUpdate(abc, 0, abc.Length);
            byte[] result = DigestUtilities.DoFinal(digest);

            if (!AreEqual(result, Hex.Decode(hash)))
            {
                Fail("abc result not equal for " + algorithm);
            }
        }
Beispiel #30
0
        public override byte[] GenerateServerKeyExchange()
        {
            DigestInputBuffer output = new DigestInputBuffer();

            base.mECAgreePrivateKey = TlsEccUtilities.GenerateEphemeralServerKeyExchange(base.mContext.SecureRandom, base.mNamedCurves, base.mClientECPointFormats, output);
            SignatureAndHashAlgorithm signatureAndHashAlgorithm = TlsUtilities.GetSignatureAndHashAlgorithm(base.mContext, this.mServerCredentials);
            IDigest            d = TlsUtilities.CreateHash(signatureAndHashAlgorithm);
            SecurityParameters securityParameters = base.mContext.SecurityParameters;

            d.BlockUpdate(securityParameters.clientRandom, 0, securityParameters.clientRandom.Length);
            d.BlockUpdate(securityParameters.serverRandom, 0, securityParameters.serverRandom.Length);
            output.UpdateDigest(d);
            byte[] hash      = DigestUtilities.DoFinal(d);
            byte[] signature = this.mServerCredentials.GenerateCertificateSignature(hash);
            new DigitallySigned(signatureAndHashAlgorithm, signature).Encode(output);
            return(output.ToArray());
        }