SetHashAlgorithm() public method

public SetHashAlgorithm ( string strName ) : void
strName string
return void
Beispiel #1
0
        //-------------------------------------------------------------------
        public static bool DSAVerifyHash(byte[] HashValue, byte[] SignedHashValue,
        DSAParameters DSAKeyInfo, string HashAlg)
        {
            bool verified = false;

            try
            {
            // Создаем новый экземпляр класса DSACryptoServiceProvider.
            using (DSACryptoServiceProvider DSA = new DSACryptoServiceProvider())
            {
                // Импортируем ключи
                DSA.ImportParameters(DSAKeyInfo);

                //Создаем объект класса DSASignatureFormatter и передаем ему DSACryptoServiceProvider закрытый ключ
                DSASignatureDeformatter DSADeformatter = new DSASignatureDeformatter(DSA);

                // Устанавливаем алгоритм шифрования
                DSADeformatter.SetHashAlgorithm(HashAlg);

                // Сверяем подписи и возвращаем результат
                verified = DSADeformatter.VerifySignature(HashValue, SignedHashValue);
            }
            }
            catch (CryptographicException e)
            {
            Console.WriteLine(e.Message);
            }

            return verified;
        }
Beispiel #2
0
        public bool verify(byte[] sig)
        {
            m_cs.Close();
            DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();
            DSA.ImportParameters(m_DSAKeyInfo);
            DSASignatureDeformatter DSADeformatter = new DSASignatureDeformatter(DSA);
            DSADeformatter.SetHashAlgorithm("SHA1");

            long i = 0;
            long j = 0;
            byte[] tmp;

            //This makes sure sig is always 40 bytes?
            if (sig[0] == 0 && sig[1] == 0 && sig[2] == 0)
            {
                long i1 = (sig[i++] << 24) & 0xff000000;
                long i2 = (sig[i++] << 16) & 0x00ff0000;
                long i3 = (sig[i++] << 8) & 0x0000ff00;
                long i4 = (sig[i++]) & 0x000000ff;
                j = i1 | i2 | i3 | i4;

                i += j;

                i1 = (sig[i++] << 24) & 0xff000000;
                i2 = (sig[i++] << 16) & 0x00ff0000;
                i3 = (sig[i++] << 8) & 0x0000ff00;
                i4 = (sig[i++]) & 0x000000ff;
                j = i1 | i2 | i3 | i4;

                tmp = new byte[j];
                Array.Copy(sig, i, tmp, 0, j);
                sig = tmp;
            }
            return DSADeformatter.VerifySignature(m_sha1, sig);
        }
Beispiel #3
0
		internal bool VerifySignature (DSA dsa) 
		{
			// signatureOID is check by both this.Hash and this.Signature
			DSASignatureDeformatter v = new DSASignatureDeformatter (dsa);
			// only SHA-1 is supported
			v.SetHashAlgorithm ("SHA1");
			return v.VerifySignature (this.Hash, this.Signature);
		}
Beispiel #4
0
        private void button52_Click(object sender, EventArgs e)
        {
            this.textBox56.Text = "";

            if (this.textBox51a.Text == ""
                || this.textBox51b.Text == ""
                || this.textBox51c.Text == "")
            {
                return;
            }

            // 公開鍵・暗号化サービスプロバイダ
            AsymmetricAlgorithm aa = this.CreateAsymmetricAlgorithmServiceProvider2();

            // 公開鍵
            aa.FromXmlString(this.textBox51b.Text);

            try
            {
                // 結果フラグ
                bool flg = false;

                // 元文字列をbyte型配列に変換する(UTF-8 Enc)
                byte[] asb = Encoding.UTF8.GetBytes(this.textBox51a.Text);

                // ハッシュ値を取得
                byte[] ahb = Convert.FromBase64String(this.textBox53.Text);

                if (aa is DSACryptoServiceProvider)
                {
                    // キャスト
                    DSACryptoServiceProvider dsa = (DSACryptoServiceProvider)aa;
                    
                    // DSASignatureFormatterオブジェクトを作成
                    DSASignatureDeformatter dsaSignatureDeformatter = new DSASignatureDeformatter(dsa);

                    // 検証に使用するハッシュアルゴリズムを指定し
                    // 上記で、ハッシュ値を計算した際と同じアルゴリズムを使用すること。
                    if (this.comboBox5.SelectedItem.ToString().IndexOf("SHA1") != -1)
                    {
                        dsaSignatureDeformatter.SetHashAlgorithm("SHA1");
                    }

                    // 検証する
                    flg = dsaSignatureDeformatter.VerifySignature(ahb, Convert.FromBase64String(this.textBox55.Text));
                }
                else if (aa is ECDiffieHellmanCng)
                {
                    // キャスト
                    ECDiffieHellmanCng ecdhcng = (ECDiffieHellmanCng)aa;

                    // 検証する
                    throw new NotImplementedException("ECDiffieHellmanCng:未実装");
                }
                else if (aa is ECDsaCng)
                {
                    // キャスト
                    ECDsaCng ecdsa = (ECDsaCng)aa;

                    // 検証する
                    throw new NotImplementedException("ECDsaCng:未実装");
                }
                else if (aa is RSACryptoServiceProvider)
                {
                    // キャスト
                    RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)aa;

                    // RSAPKCS1SignatureDeformatterオブジェクトを作成
                    RSAPKCS1SignatureDeformatter rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa);

                    // 検証に使用するハッシュアルゴリズムを指定し
                    // 上記で、ハッシュ値を計算した際と同じアルゴリズムを使用すること。
                    if (this.comboBox5.SelectedItem.ToString().IndexOf("SHA1") != -1)
                    {
                        rsaDeformatter.SetHashAlgorithm("SHA1");
                    }
                    else if (this.comboBox5.SelectedItem.ToString().IndexOf("MD5") != -1)
                    {
                        rsaDeformatter.SetHashAlgorithm("MD5");
                    }

                    // 検証する
                    flg = rsaDeformatter.VerifySignature(ahb, Convert.FromBase64String(this.textBox55.Text));
                }

                // 検証結果を表示
                if (flg)
                {
                    this.textBox56.Text = "デジタル署名は署名前のメッセージであることが検証されました。";
                }
                else
                {
                    this.textBox56.Text = "デジタル署名は署名前のメッセージであることが検証されませんでした。";
                }
            }
            catch (Exception ex)
            {
                // 結果を表示
                this.textBox56.Text = "エラーです。キーを変更した可能性があります。\r\n"
                    + ex.ToString();
            }
        }
 static bool VerifyDsaMessage(byte[] keyData, byte[] message, byte[] signature)
 {
     // Load the Public Key X.509 Format
     AsnKeyParser keyParser = new AsnKeyParser(keyData);
     DSAParameters publicKey = keyParser.ParseDSAPublicKey();
     CspParameters csp = new CspParameters();
     // Cannot use PROV_DSS_DH
     const int PROV_DSS = 3;
     csp.ProviderType = PROV_DSS;
     const int AT_SIGNATURE = 2;
     csp.KeyNumber = AT_SIGNATURE;
     csp.KeyContainerName = "DSA Test (OK to Delete)";
     DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(csp);
     dsa.PersistKeyInCsp = false;
     dsa.ImportParameters(publicKey);
     SHA1 sha = new SHA1CryptoServiceProvider();
     byte[] hash = sha.ComputeHash(message);
     DSASignatureDeformatter verifier = new DSASignatureDeformatter(dsa);
     verifier.SetHashAlgorithm("SHA1");
     bool result = verifier.VerifySignature(hash, signature);
     // See http://blogs.msdn.com/tess/archive/2007/10/31/
     //   asp-net-crash-system-security-cryptography-cryptographicexception.aspx
     dsa.Clear();
     return result;
 }
 /// <summary>
 /// Validates the signature that follows the Licence data
 /// </summary>
 /// <param name="hashValue">Hash value</param>
 /// <param name="signedHashValue">Signed hash value</param>
 /// <param name="xmlKeyInfo">Public Key</param>
 /// <param name="hashAlg">Hash Algorithm</param>
 /// <returns>True if signature is valid</returns>
 private static bool DSAVerifyHash(byte[] hashValue, byte[] signedHashValue, string xmlKeyInfo, string hashAlg)
 {
     DSACryptoServiceProvider.UseMachineKeyStore = false;
     using (DSACryptoServiceProvider DSA = new DSACryptoServiceProvider())
     {
         DSA.FromXmlString(xmlKeyInfo);
         DSASignatureDeformatter DSAFormatter = new DSASignatureDeformatter(DSA);
         DSAFormatter.SetHashAlgorithm(hashAlg);
         return DSAFormatter.VerifySignature(hashValue, signedHashValue);
     }
 }
Beispiel #7
0
		/// <summary>
		/// DSA验证
		/// </summary>
		/// <param name="CypherText">签名后的Base64字符串</param>
		/// <param name="xmlString">密钥(至少含公钥)</param>
		/// <param name="signString">签名串</param>
		public static bool VerifyString(string CypherText, string xmlString, string signString)
		{
			DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
			dsa.FromXmlString(xmlString);

			if (!string.IsNullOrEmpty(CypherText))
			{
				byte[] bEnc = System.Convert.FromBase64String(CypherText);
				byte[] bText = System.Text.Encoding.UTF8.GetBytes(signString.ToCharArray());

				DSASignatureDeformatter DSADeformatter = new DSASignatureDeformatter(dsa);
				DSADeformatter.SetHashAlgorithm("SHA1");
				return DSADeformatter.VerifySignature(bEnc, bText);
			}
			return false;
		}
		internal bool VerifySignature (DSA dsa) 
		{
			if (signatureOID != "1.2.840.10040.4.3")
				throw new CryptographicException ("Unsupported hash algorithm: " + signatureOID);
			DSASignatureDeformatter v = new DSASignatureDeformatter (dsa);
			// only SHA-1 is supported
			string hashName = "SHA1";
			v.SetHashAlgorithm (hashName);
			ASN1 sign = new ASN1 (signature);
			if ((sign == null) || (sign.Count != 2))
				return false;
			// parts may be less than 20 bytes (i.e. first bytes were 0x00)
			byte[] part1 = sign [0].Value;
			byte[] part2 = sign [1].Value;
			byte[] sig = new byte [40];
			Buffer.BlockCopy (part1, 0, sig, (20 - part1.Length), part1.Length);
			Buffer.BlockCopy (part2, 0, sig, (40 - part2.Length), part2.Length);
			return v.VerifySignature (GetHash (hashName), sig);
		}
 public bool VerifySignature(Stream stream, string signature)
 {
     try
     {
         using (var dsaCryptoProvider = new DSACryptoServiceProvider())
         {
             byte[] hash = (new SHA1Managed()).ComputeHash(stream);//for file or text
             dsaCryptoProvider.ImportParameters(PublicKey);
             var dsaDeformatter = new DSASignatureDeformatter(dsaCryptoProvider);
             dsaDeformatter.SetHashAlgorithm("SHA1");
             return dsaDeformatter.VerifySignature(hash, StringToByteArray(signature));
         }
     }
     catch (CryptographicException e)
     {
         return false;
     }
 }
        /// <summary>
        /// Método verifica si firma digital es correcta.
        /// </summary>
        /// <param name="pClavePublica">Cadena clave pública.</param>
        /// <param name="pFirmaDigital">Array byte de firma digital.</param>
        /// <param name="pClaveHash">Array byte clave hash.</param>
        /// <returns>
        /// Resultado booleano de verificación.
        /// </returns>
        private static bool ComprobarFirmaDigitalDSA(string pClavePublica, byte[] pFirmaDigital, byte[] pClaveHash)
        {
            // Instancia servicio de criptación DSA.
            DSACryptoServiceProvider vServicioCriptorDSA = new DSACryptoServiceProvider();

            // Asigna clave pública a servicio criptor.
            vServicioCriptorDSA.FromXmlString(pClavePublica);

            // Instancia por medio de servicio criptor a formateador de firma por medio de DSA.
            DSASignatureDeformatter vFormateadorFirmaDSA = new DSASignatureDeformatter(vServicioCriptorDSA);

            // Indica el algoritmo hash a utilizar.
            vFormateadorFirmaDSA.SetHashAlgorithm(ALGORITMO);

            // Verifica si firma digital es correcto y asigna  resultado a una variable booleana.
            bool vFirmaEsCorrecta = vFormateadorFirmaDSA.VerifySignature(pClaveHash, pFirmaDigital);

            // Retorna resultado.
            return vFirmaEsCorrecta;
        }
Beispiel #11
0
        /// <summary>
        /// Verify a file using a signature file and a public key.
        /// </summary>
        /// <param name="filePath">The file whose contents will be hashed.</param>
        /// <param name="signatureFilePath">The path of the signature file.</param>
        /// <param name="publicBlob">The public key.</param>
        /// <returns> True if the file is verified, otherwise false.</returns>
        public static bool VerifyFile(string filePath, string signatureFilePath, byte[] publicBlob)
        {
            if (publicBlob.Length == 0)
                return false;

            bool verified = false;
            byte[] hash = null;

            try
            {
                // Compute a hash of the installer
                using (Stream fileStream = File.Open(filePath, FileMode.Open))
                {
                    SHA1 sha1 = new SHA1CryptoServiceProvider();
                    hash = sha1.ComputeHash(fileStream);
                }

                // Import the public key
                var dsa = new DSACryptoServiceProvider();
                dsa.ImportCspBlob(publicBlob);

                var dsaDeformatter = new DSASignatureDeformatter(dsa);
                dsaDeformatter.SetHashAlgorithm("SHA1");

                // Read the signature file
                byte[] signature = File.ReadAllBytes(signatureFilePath);

                // Verify the signature against the hash of the installer
                verified = dsaDeformatter.VerifySignature(hash, signature);

                Console.WriteLine("File verified: {0}", verified);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);

                return false;
            }

            return verified;
        }
Beispiel #12
-1
 public static bool myVerifyHash(byte[] HashValue, byte[] SignedHashValue, DSAParameters DSAKeyInfo, string HashAlg)
 {
     try
     {
         //Create a new instance of DSACryptoServiceProvider.
         DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();
         //Import the key information.
         DSA.ImportParameters(DSAKeyInfo);
         //DSAKeyInfo.
         //Create an DSASignatureDeformatter object and pass it the
         //DSACryptoServiceProvider to transfer the private key.
         DSASignatureDeformatter DSADeformatter = new DSASignatureDeformatter(DSA);
         //Set the hash algorithm to the passed value.
         DSADeformatter.SetHashAlgorithm(HashAlg);
         //Verify signature and return the result.
         return DSADeformatter.VerifySignature(HashValue, SignedHashValue);
     }
     catch (CryptographicException e)
     {
         Console.WriteLine(e.Message);
         return false;
     }
 }
Beispiel #13
-1
		internal bool VerifySignature (DSA dsa) 
		{
			if (signatureOID != "1.2.840.10040.4.3")
				throw new CryptographicException ("Unsupported hash algorithm: " + signatureOID);
			DSASignatureDeformatter v = new DSASignatureDeformatter (dsa);
			// only SHA-1 is supported
			v.SetHashAlgorithm ("SHA1");
			ASN1 sign = new ASN1 (signature);
			if ((sign == null) || (sign.Count != 2))
				return false;
			// parts may be less than 20 bytes (i.e. first bytes were 0x00)
			byte[] part1 = sign [0].Value;
			byte[] part2 = sign [1].Value;
			byte[] sig = new byte [40];
			// parts may be less than 20 bytes (i.e. first bytes were 0x00)
			// parts may be more than 20 bytes (i.e. first byte > 0x80, negative)
			int s1 = System.Math.Max (0, part1.Length - 20);
			int e1 = System.Math.Max (0, 20 - part1.Length);
			Buffer.BlockCopy (part1, s1, sig, e1, part1.Length - s1);
			int s2 = System.Math.Max (0, part2.Length - 20);
			int e2 = System.Math.Max (20, 40 - part2.Length);
			Buffer.BlockCopy (part2, s2, sig, e2, part2.Length - s2);
			return v.VerifySignature (Hash, sig);
		}
        /// <summary>
        /// Verifies the signature.
        /// </summary>
        /// <param name="hash">The hash.</param>
        /// <param name="signature">The signature.</param>
        /// <returns>
        /// true if signature verified; otherwise false.
        /// </returns>
        public override bool VerifySignature(IEnumerable<byte> hash, IEnumerable<byte> signature)
        {
            using (var sha1 = new SHA1CryptoServiceProvider())
            {
                using (var cs = new CryptoStream(System.IO.Stream.Null, sha1, CryptoStreamMode.Write))
                {
                    var data = hash.ToArray();
                    cs.Write(data, 0, data.Length);
                }

                using (var dsa = new DSACryptoServiceProvider())
                {
                    dsa.ImportParameters(new DSAParameters
                    {
                        Y = _publicKey.TrimLeadingZero().ToArray(),
                        P = _p.TrimLeadingZero().ToArray(),
                        Q = _q.TrimLeadingZero().ToArray(),
                        G = _g.TrimLeadingZero().ToArray(),
                    });
                    var dsaDeformatter = new DSASignatureDeformatter(dsa);
                    dsaDeformatter.SetHashAlgorithm("SHA1");

                    long i = 0;
                    long j = 0;
                    byte[] tmp;

                    var sig = signature.ToArray();
                    if (sig[0] == 0 && sig[1] == 0 && sig[2] == 0)
                    {
                        long i1 = (sig[i++] << 24) & 0xff000000;
                        long i2 = (sig[i++] << 16) & 0x00ff0000;
                        long i3 = (sig[i++] << 8) & 0x0000ff00;
                        long i4 = (sig[i++]) & 0x000000ff;
                        j = i1 | i2 | i3 | i4;

                        i += j;

                        i1 = (sig[i++] << 24) & 0xff000000;
                        i2 = (sig[i++] << 16) & 0x00ff0000;
                        i3 = (sig[i++] << 8) & 0x0000ff00;
                        i4 = (sig[i++]) & 0x000000ff;
                        j = i1 | i2 | i3 | i4;

                        tmp = new byte[j];
                        Array.Copy(sig, (int)i, tmp, 0, (int)j);
                        sig = tmp;
                    }

                    return dsaDeformatter.VerifySignature(sha1, sig);
                }
            }
        }