SetHashAlgorithm() публичный Метод

public SetHashAlgorithm ( string strName ) : void
strName string
Результат void
Пример #1
1
        /// <summary>
        /// 数字签名处理.
        /// </summary>
        /// <param name="HashToSign"></param>
        /// <param name="DSAKeyInfo"></param>
        /// <param name="HashAlg"></param>
        /// <returns></returns>
        public static byte[] DSASignHash(byte[] HashToSign, DSAParameters DSAKeyInfo, string HashAlg)
        {
            try
            {
                //Create a new instance of DSACryptoServiceProvider.
                DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();

                //Import the key information.
                DSA.ImportParameters(DSAKeyInfo);

                //Create an DSASignatureFormatter object and pass it the
                //DSACryptoServiceProvider to transfer the private key.
                DSASignatureFormatter DSAFormatter = new DSASignatureFormatter(DSA);

                //Set the hash algorithm to the passed value.
                DSAFormatter.SetHashAlgorithm(HashAlg);

                //Create a signature for HashValue and return it.
                return DSAFormatter.CreateSignature(HashToSign);
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);

                return null;
            }
        }
Пример #2
0
        //-------------------------------------------------------------------------
        // Шифруем закрытым ключем Хеш-таблицу
        public static byte[] DSASignHash(byte[] HashToSign, DSAParameters DSAKeyInfo,
        string HashAlg)
        {
            byte[] sig = null;

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

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

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

                // Создаем подпись для хеш-таблицы и возвращаем ее значение
                sig = DSAFormatter.CreateSignature(HashToSign);
            }
            }
            catch (CryptographicException e)
            {
            Console.WriteLine(e.Message);
            }

            return sig;
        }
Пример #3
0
        public byte[] sign()
        {
            m_cs.Close();
            DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();
            DSA.ImportParameters(m_DSAKeyInfo);
            DSASignatureFormatter DSAFormatter = new DSASignatureFormatter(DSA);
            DSAFormatter.SetHashAlgorithm("SHA1");

            byte[] sig = DSAFormatter.CreateSignature(m_sha1);
            return sig;
        }
 public string CreateSignatureForStream(Stream stream)
 {
     byte[] hash = (new SHA1Managed()).ComputeHash(stream);//for file or text
     try
     {
         using (var dsaCryptoProvider = new DSACryptoServiceProvider())
         {
             dsaCryptoProvider.ImportParameters(PrivateKey);
             var dsaFormatter = new DSASignatureFormatter(dsaCryptoProvider);
             dsaFormatter.SetHashAlgorithm("SHA1");
             byte[] signature = dsaFormatter.CreateSignature(hash);
             return ByteArrayToString(signature);
         }
     }
     catch (CryptographicException e)
     {
         return null;
     }
 }
Пример #5
0
        /// <summary>署名</summary>
        private void button51_Click(object sender, EventArgs e)
        {
            this.textBox52.Text = "";
            this.textBox53.Text = "";
            this.textBox54.Text = "";
            this.textBox55.Text = "";
            this.textBox56.Text = "";

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

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

                // 秘密鍵
                aa.FromXmlString(this.textBox51c.Text);

                // 元文字列をbyte型配列に変換する(UTF-8 Enc)
                byte[] asb  = Encoding.UTF8.GetBytes(this.textBox51a.Text);
                // ハッシュ値
                byte[] ahb = null;
                // 署名
                byte[] ab_sign = null;

                if (aa is DSACryptoServiceProvider)
                {
                    // キャスト
                    DSACryptoServiceProvider dsa = (DSACryptoServiceProvider)aa;

                    // DSASignatureFormatterオブジェクトを作成
                    DSASignatureFormatter dsaFormatter = new DSASignatureFormatter(dsa);

                    // 署名の作成に使用するハッシュアルゴリズムを指定し、ハッシュ値を計算
                    if (this.comboBox5.SelectedItem.ToString().IndexOf("SHA1") != -1)
                    {
                        dsaFormatter.SetHashAlgorithm("SHA1");
                        ahb = SHA1.Create().ComputeHash(asb);
                    }

                    // 署名を作成
                    ab_sign = dsaFormatter.CreateSignature(ahb);
                }
                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;

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

                    // 署名の作成に使用するハッシュアルゴリズムを指定し、ハッシュ値を計算
                    if (this.comboBox5.SelectedItem.ToString().IndexOf("SHA1") != -1)
                    {
                        rsaFormatter.SetHashAlgorithm("SHA1");
                        ahb = SHA1.Create().ComputeHash(asb);
                    }
                    else if (this.comboBox5.SelectedItem.ToString().IndexOf("MD5") != -1)
                    {
                        rsaFormatter.SetHashAlgorithm("MD5");
                        ahb = MD5.Create().ComputeHash(asb);
                    }

                    // 署名を作成
                    ab_sign = rsaFormatter.CreateSignature(ahb);
                }

                // 結果を表示

                // ハッシュ

                // 生バイト
                this.textBox52.Text = CustomEncode.ToHexString(ahb);
                // Base64
                this.textBox53.Text = Convert.ToBase64String(ahb);

                // 署名

                // 生バイト
                this.textBox54.Text = CustomEncode.ToHexString(ab_sign);
                // Base64
                this.textBox55.Text = Convert.ToBase64String(ab_sign);
            }
            catch (Exception ex)
            {
                // 結果を表示
                this.textBox56.Text = "エラーです。キーを変更した可能性があります。\r\n"
                    + ex.ToString();
            }
        }
Пример #6
0
		public virtual byte[] Sign (DSA key) 
		{
			string oid = "1.2.840.10040.4.3";
			ASN1 tbs = ToBeSigned (oid);
			HashAlgorithm ha = HashAlgorithm.Create (hashName);
			if (!(ha is SHA1))
				throw new NotSupportedException ("Only SHA-1 is supported for DSA");
			byte[] hash = ha.ComputeHash (tbs.GetBytes ());

			DSASignatureFormatter dsa = new DSASignatureFormatter (key);
			dsa.SetHashAlgorithm (hashName);
			byte[] rs = dsa.CreateSignature (hash);

			// split R and S
			byte[] r = new byte [20];
			Buffer.BlockCopy (rs, 0, r, 0, 20);
			byte[] s = new byte [20];
			Buffer.BlockCopy (rs, 20, s, 0, 20);
			ASN1 signature = new ASN1 (0x30);
			signature.Add (new ASN1 (0x02, r));
			signature.Add (new ASN1 (0x02, s));

			// dsaWithSha1 (1 2 840 10040 4 3)
			return Build (tbs, oid, signature.GetBytes ());
		}
Пример #7
0
		//#region 文件处理
		///// <summary>
		///// 加密文件
		///// </summary>
		///// <param name="inName">来源文件</param>
		///// <param name="outName">输出文件</param>
		///// <param name="xmlString">密钥(至少含公钥)</param>
		//public static void EncryptFile(string inName, string outName, string xmlString)
		//{
		//    DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
		//    dsa.FromXmlString(xmlString);
		//    FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
		//    using (FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write))
		//    {
		//        fout.SetLength(0);

		//        long rdlen = 0;					//This is the total number of bytes written.
		//        int len;						//This is the number of bytes to be written at a time.
		//        byte[] bin = new byte[FileReadStep];
		//        while (rdlen < fin.Length)
		//        {
		//            len = fin.Read(bin, 0, FileReadStep);
		//            byte[] bs = dsa.Encrypt(bin, false);
		//            fout.Write(bs, 0, bs.Length);
		//            rdlen += len;
		//        }

		//        fin.Close();
		//    }
		//}

		///// <summary>
		///// 解密文件
		///// </summary>
		///// <param name="inName">来源文件</param>
		///// <param name="outName">输出文件</param>
		///// <param name="xmlString">密钥(公钥私钥俱有)</param>
		//public static void DecryptFile(string inName, string outName, string xmlString)
		//{
		//    DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
		//    dsa.FromXmlString(xmlString);
		//    FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
		//    using (FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write))
		//    {
		//        fout.SetLength(0);

		//        long rdlen = 0;					//This is the total number of bytes written.
		//        int len;						//This is the number of bytes to be written at a time.
		//        byte[] bin = new byte[FileReadStep];
		//        while (rdlen < fin.Length)
		//        {
		//            len = fin.Read(bin, 0, FileReadStep);
		//            byte[] bs = dsa.Decrypt(bin, false);
		//            fout.Write(bs, 0, bs.Length);
		//            rdlen += len;
		//        }

		//        fin.Close();
		//    }
		//}
		//#endregion

		#region 字符串处理
		/// <summary>
		/// DSA签名
		/// </summary>
		/// <param name="PlainText">原始字符串</param>
		/// <param name="xmlString">密钥(公钥私钥俱有)</param>
		/// <returns>Base64编码后的已签名字符串</returns>
		public static string SignString(string PlainText, string xmlString)
		{
			DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
			dsa.FromXmlString(xmlString);

			if (!string.IsNullOrEmpty(PlainText))
			{
				byte[] bText = System.Text.Encoding.UTF8.GetBytes(PlainText.ToCharArray());

				DSASignatureFormatter DSAFormatter = new DSASignatureFormatter(dsa);
				DSAFormatter.SetHashAlgorithm("SHA1");
				byte[] bEnc = DSAFormatter.CreateSignature(bText);

				return System.Convert.ToBase64String(bEnc);
			}
			return string.Empty;
		}
        /// <summary>
        /// Gets the signature.
        /// </summary>
        /// <param name="key">The key data bytes.</param>
        /// <returns></returns>
        public override byte[] GetSignature(IEnumerable<byte> key)
        {
            var data = key.ToArray();
            //using (var sha1 = new Renci.SshNet.Security.Cryptography.SHA1Hash())
            using (var sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider())
            {
                using (var cs = new System.Security.Cryptography.CryptoStream(System.IO.Stream.Null, sha1, System.Security.Cryptography.CryptoStreamMode.Write))
                {
                    cs.Write(data, 0, data.Length);
                }

                var dsaKeyInfo = new System.Security.Cryptography.DSAParameters();

                dsaKeyInfo.X = this._privateKey.TrimLeadingZero().ToArray();
                dsaKeyInfo.P = this._p.TrimLeadingZero().ToArray();
                dsaKeyInfo.Q = this._q.TrimLeadingZero().ToArray();
                dsaKeyInfo.G = this._g.TrimLeadingZero().ToArray();

                using (var DSA = new System.Security.Cryptography.DSACryptoServiceProvider())
                {
                    DSA.ImportParameters(dsaKeyInfo);
                    var DSAFormatter = new DSASignatureFormatter(DSA);
                    DSAFormatter.SetHashAlgorithm("SHA1");

                    var signature = DSAFormatter.CreateSignature(sha1);

                    return new SignatureKeyData
                    {
                        AlgorithmName = this.Name,
                        Signature = signature,
                    }.GetBytes().ToArray();
                }
            }
        }
        /// <summary>
        /// Método crea firma digital.
        /// </summary>
        /// <param name="pClaveHash">Array byte de clave hash.</param>
        /// <param name="pClavesXML">Claves xml pública y privada.</param>
        /// <returns>
        /// Firma digital.
        /// </returns>
        private static byte[] CrearFirmaDigitalDSA(byte[] pClaveHash, string pClavesXML)
        {
            // Instancia servicio criptor DSA.
            DSACryptoServiceProvider vServicioCriptorDSA = new DSACryptoServiceProvider();

            // Asignamos las claves públicas y privadas a servicio criptor.
            vServicioCriptorDSA.FromXmlString(pClavesXML);

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

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

            // Creamos la firma digital y se retorna.
            return vFormateadorFirmaDSA.CreateSignature(pClaveHash);
        }
Пример #10
0
        /// <summary>
        /// Generate a signature file using a private key.
        /// </summary>
        /// <param name="filePath">The file whose contents will be hashed.</param>
        /// <param name="signatureFilePath">The path of the generated signature file.</param>
        /// <param name="privateBlob">The private key.</param>
        public static void SignFile(string filePath, string signatureFilePath, byte[] privateBlob)
        {  
            try
            {
                if (privateBlob.Length == 0)
                {
                    throw new Exception("The specified private key is invalid.");
                }

                byte[] hash = null;

                using (Stream fileStream = File.Open(filePath, FileMode.Open))
                {
                    SHA1 sha1 = new SHA1CryptoServiceProvider();
                    hash = sha1.ComputeHash(fileStream);
                }

                // Import the private key
                var dsa = new DSACryptoServiceProvider();
                dsa.ImportCspBlob(privateBlob);
                var rsaFormatter = new DSASignatureFormatter(dsa);
                rsaFormatter.SetHashAlgorithm("SHA1");

                // Create a signature based on the private key
                byte[] signature = rsaFormatter.CreateSignature(hash);

                // Write the signature file
                File.WriteAllBytes(signatureFilePath, signature);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }
        }
Пример #11
0
        private void SignFileButton_Click(object sender, RoutedEventArgs e)
        {
            DSACryptoServiceProvider provider = new DSACryptoServiceProvider();
            provider.ImportCspBlob(SelectedKey.PrivateKey);

            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "All Files|*.*";
            dialog.Title = "Please choose the file to sign";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) {
                return;
            }

            if (!String.IsNullOrEmpty(dialog.FileName)) {

                try {

                    DSASignatureFormatter formatter = new DSASignatureFormatter(provider);
                    formatter.SetHashAlgorithm("SHA1");

                    SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                    byte[] hash = sha1.ComputeHash(File.ReadAllBytes(dialog.FileName));

                    string signature = Convert.ToBase64String(formatter.CreateSignature(hash));

                    SignatureBox.Text = signature;

                } catch (Exception ex) {
                    System.Windows.MessageBox.Show(String.Format("File could not be signed: {0}", ex.Message));
                    return;
                }

            } else {
                return;
            }
        }